private string GetContent(string content, CodeSnippet obj)
        {
            var allLines = ReadAllLines(content).ToArray();

            // code range priority: tag > #L1 > start/end > range > default
            if (!string.IsNullOrEmpty(obj.TagName))
            {
                var lang = obj.Language ?? Path.GetExtension(obj.CodePath);
                if (!CodeLanguageExtractors.TryGetValue(lang, out List <CodeSnippetExtrator> extrators))
                {
                    _context.LogError("unknown-language-code", $"{lang} is not supported languaging name, alias or extension for parsing code snippet with tag name, you can use line numbers instead");
                }

                if (extrators != null)
                {
                    var tagWithPrefix = tagPrefix + obj.TagName;
                    foreach (var extrator in extrators)
                    {
                        HashSet <int> tagLines = new HashSet <int>();
                        var           tagToCoderangeMapping = extrator.GetAllTags(allLines, ref tagLines);
                        CodeRange     cr;
                        if (tagToCoderangeMapping.TryGetValue(obj.TagName, out cr) ||
                            tagToCoderangeMapping.TryGetValue(tagWithPrefix, out cr))
                        {
                            return(GetCodeLines(allLines, obj, new List <CodeRange> {
                                cr
                            }, tagLines));
                        }
                    }
                }
            }
            else if (obj.BookMarkRange != null)
            {
                return(GetCodeLines(allLines, obj, new List <CodeRange> {
                    obj.BookMarkRange
                }));
            }
            else if (obj.StartEndRange != null)
            {
                return(GetCodeLines(allLines, obj, new List <CodeRange> {
                    obj.StartEndRange
                }));
            }
            else if (obj.CodeRanges != null)
            {
                return(GetCodeLines(allLines, obj, obj.CodeRanges));
            }
            else
            {
                return(GetCodeLines(allLines, obj, new List <CodeRange> {
                    new CodeRange()
                    {
                        Start = 0, End = allLines.Length
                    }
                }));
            }

            return(string.Empty);
        }
Example #2
0
        public override BlockState TryOpen(BlockProcessor processor)
        {
            var slice          = processor.Line;
            var column         = processor.Column;
            var sourcePosition = processor.Start;

            if (processor.IsCodeIndent ||
                ExtensionsHelper.IsEscaped(slice) ||
                !ExtensionsHelper.MatchStart(ref slice, ":::"))
            {
                return(BlockState.None);
            }

            ExtensionsHelper.SkipSpaces(ref slice);

            var extensionName = "triple-colon";
            ITripleColonExtensionInfo    extension;
            IDictionary <string, string> attributes;
            HtmlAttributes  htmlAttributes;
            Action <string> logError = (string message) => _context.LogError($"invalid-{extensionName}", $"Invalid {extensionName} on line {processor.LineIndex}. \"{slice.Text}\" is invalid. {message}", line: processor.LineIndex);

            if (!TryMatchIdentifier(ref slice, out extensionName) ||
                !_extensions.TryGetValue(extensionName, out extension) ||
                !extension.TryValidateAncestry(processor.CurrentContainer, logError) ||
                !TryMatchAttributes(ref slice, out attributes, extensionName, logError) ||
                !extension.TryProcessAttributes(attributes, out htmlAttributes, logError))
            {
                return(BlockState.None);
            }

            var block = new TripleColonBlock(this)
            {
                Column    = column,
                Span      = new SourceSpan(sourcePosition, slice.End),
                Extension = extension
            };

            if (htmlAttributes != null)
            {
                block.SetData(typeof(HtmlAttributes), htmlAttributes);
            }

            processor.NewBlocks.Push(block);

            return(BlockState.ContinueDiscard);
        }
        private string GetNoteBookContent(string content, string tagName, CodeSnippet obj)
        {
            JObject contentObject = null;

            try
            {
                contentObject = JObject.Parse(content);
            }
            catch (JsonReaderException ex)
            {
                _context.LogError("not-notebook-content", "Not a valid Notebook. " + ex.ToString(), obj);
                return(string.Empty);
            }

            string sourceJsonPath = $"$..cells[?(@.metadata.name=='{tagName}')].source";
            JToken sourceObject   = null;

            try
            {
                sourceObject = contentObject.SelectToken(sourceJsonPath);
            }
            catch (JsonException)
            {
                _context.LogError("multiple-tags-with-same-name", $"Multiple entries with the name '{tagName}' where found in the notebook.", obj);
                return(string.Empty);
            }

            if (sourceObject == null)
            {
                _context.LogError("tag-not-found", $"The name '{tagName}' is not present in the notebook file.", obj);
                return(string.Empty);
            }

            StringBuilder showCode = new StringBuilder();

            string[] lines = ((JArray)sourceObject).ToObject <string[]>();
            for (int i = 0; i < lines.Length; i++)
            {
                showCode.Append(lines[i]);
            }

            return(showCode.ToString());
        }
Example #4
0
        private void ValidateCore(Tag tag, MarkdownTagValidationRule validator)
        {
            switch (validator.Behavior)
            {
            case TagValidationBehavior.Warning:
                _context.LogWarning("invalid-markdown-tag", string.Format(validator.MessageFormatter, tag.Name, tag.Content), line: tag.Line);
                return;

            case TagValidationBehavior.Error:
                _context.LogError("invalid-markdown-tag", string.Format(validator.MessageFormatter, tag.Name, tag.Content), line: tag.Line);
                return;

            case TagValidationBehavior.None:
            default:
                return;
            }
        }
        public override bool Match(InlineProcessor processor, ref StringSlice slice)
        {
            if (!ExtensionsHelper.MatchStart(ref slice, ":::"))
            {
                return(false);
            }

            if (!TripleColonBlockParser.TryMatchIdentifier(ref slice, out var extensionName) ||
                !_extensions.TryGetValue(extensionName, out var extension))
            {
                return(false);
            }

            var inline = new TripleColonInline(this)
            {
                Closed = false,
                Column = 0,
                Line   = processor.LineIndex,
                Span   = new SourceSpan(processor.LineIndex, slice.End),
            };

            var logError   = new Action <string>(message => _context.LogError($"invalid-{extensionName}", message, inline));
            var logWarning = new Action <string>(message => _context.LogWarning($"invalid-{extensionName}", message, inline));

            if (!TripleColonBlockParser.TryMatchAttributes(ref slice, out var attributes, extension.SelfClosing, logError) ||
                !extension.TryProcessAttributes(attributes, out var htmlAttributes, out var renderProperties, logError, logWarning, inline))
            {
                return(false);
            }

            inline.Extension        = extension;
            inline.Attributes       = attributes;
            inline.RenderProperties = renderProperties;

            if (htmlAttributes != null)
            {
                inline.SetData(typeof(HtmlAttributes), htmlAttributes);
            }

            processor.Inline = inline;

            return(true);
        }
Example #6
0
        public override BlockState TryOpen(BlockProcessor processor)
        {
            var slice          = processor.Line;
            var column         = processor.Column;
            var sourcePosition = processor.Start;

            if (processor.IsCodeIndent ||
                !ExtensionsHelper.MatchStart(ref slice, ":::"))
            {
                return(BlockState.None);
            }

            ExtensionsHelper.SkipSpaces(ref slice);

            var             extensionName = "triple-colon";
            Action <string> logError      = (string message) => _context.LogError(
                $"invalid-{extensionName}",
                $"Invalid {extensionName} on line {processor.LineIndex}. {message}",
                null,
                line: processor.LineIndex);

            if (!TryMatchIdentifier(ref slice, out extensionName) ||
                !_extensions.TryGetValue(extensionName, out var extension) ||
                !extension.TryValidateAncestry(processor.CurrentContainer, logError) ||
                !TryMatchAttributes(ref slice, out var attributes, extensionName, extension.SelfClosing, logError) ||
                !extension.TryProcessAttributes(attributes, out var htmlAttributes, out var renderProperties, logError, processor))
            {
                return(BlockState.None);
            }

            var block = new TripleColonBlock(this)
            {
                Closed           = false,
                Column           = column,
                Line             = processor.LineIndex,
                Span             = new SourceSpan(sourcePosition, slice.End),
                Extension        = extension,
                RenderProperties = renderProperties,
                Attributes       = attributes
            };

            if (htmlAttributes != null)
            {
                block.SetData(typeof(HtmlAttributes), htmlAttributes);
            }

            processor.NewBlocks.Push(block);

            if (extension.GetType() == typeof(ImageExtension) &&
                htmlAttributes != null &&
                ImageExtension.RequiresClosingTripleColon(attributes))
            {
                ((TripleColonBlock)block).EndingTripleColons = true;
                return(BlockState.ContinueDiscard);
            }

            if (extension.SelfClosing)
            {
                return(BlockState.BreakDiscard);
            }

            return(BlockState.ContinueDiscard);
        }
Example #7
0
        public override BlockState TryOpen(BlockProcessor processor)
        {
            if (processor.IsCodeIndent)
            {
                return(BlockState.None);
            }

            var slice = processor.Line;

            if (ExtensionsHelper.IsEscaped(slice))
            {
                return(BlockState.None);
            }

            var column         = processor.Column;
            var sourcePosition = processor.Start;
            var colonCount     = 0;

            var c = slice.CurrentChar;

            while (c == Colon)
            {
                c = slice.NextChar();
                colonCount++;
            }

            if (colonCount < 3)
            {
                return(BlockState.None);
            }

            ExtensionsHelper.SkipSpaces(ref slice);

            if (!ExtensionsHelper.MatchStart(ref slice, StartString, false))
            {
                return(BlockState.None);
            }

            ExtensionsHelper.SkipSpaces(ref slice);

            if (!ExtensionsHelper.MatchStart(ref slice, "render=\"", false))
            {
                return(BlockState.None);
            }

            var range = StringBuilderCache.Local();

            c = slice.CurrentChar;

            while (c != '\0' && c != '"')
            {
                range.Append(c);
                c = slice.NextChar();
            }

            if (c != '"')
            {
                _context.LogWarning("invalid-render-zone", "Zone render does not have ending character (\").");
                return(BlockState.None);
            }

            c = slice.NextChar();
            while (c.IsSpace())
            {
                c = slice.NextChar();
            }

            if (!c.IsZero())
            {
                _context.LogWarning("invalid-render-zone", $"Zone render has some invalid chars in the beginning.");
            }

            // Check the blockprocessor context to see if we are already inside of a zone
            // container. If so, break.
            var containerBlock = processor.CurrentContainer;

            do
            {
                if (processor.CurrentContainer.GetType() == typeof(RenderZoneBlock))
                {
                    _context.LogError("invalid-render-zone", "Zone render cannot be nested.");
                    return(BlockState.None);
                }
                containerBlock = containerBlock.Parent;
            } while (containerBlock != null);

            processor.NewBlocks.Push(new RenderZoneBlock(this)
            {
                Closed     = false,
                ColonCount = colonCount,
                Column     = column,
                Span       = new SourceSpan(sourcePosition, slice.End),
                Target     = range.ToString(),
            });

            return(BlockState.ContinueDiscard);
        }