Beispiel #1
0
 private EMObject(EMDocument doc, EMElementOrigin origin, EMElement parent, string templateFile)
     : base(doc, origin, parent)
 {
     template            = Templates.GetCached(templateFile);
     this.literalParams  = new Dictionary <string, List <string> >();
     this.markdownParams = new Dictionary <string, List <EMObjectParam> >();
 }
 public EMHeader(EMDocument doc, EMElementOrigin origin, EMElement parent, int level, string text, bool isOptional = false)
     : base(doc, origin, parent, ToName(text))
 {
     Text = text;
     Level = level;
     IsOptional = isOptional;
 }
Beispiel #3
0
 protected void ParseElements(TransformationData data, EMDocument doc, List <TextFragment> fragments, IEnumerable <IParser> parsers)
 {
     foreach (var parser in parsers)
     {
         ParseElements(data, doc, fragments, parser);
     }
 }
Beispiel #4
0
 public EMHeader(EMDocument doc, EMElementOrigin origin, EMElement parent, int level, string text, bool isOptional = false)
     : base(doc, origin, parent, ToName(text))
 {
     Text       = text;
     Level      = level;
     IsOptional = isOptional;
 }
 private EMImage(EMDocument doc, EMElementOrigin origin, EMElement parent, EMLocalFilePath path, string title, string alt, ImageOptions options)
     : base(doc, origin, parent)
 {
     Path = path;
     Title = title;
     Alt = alt;
     Options = options;
 }
Beispiel #6
0
        public static EMElement CreateRegion(EMElementOrigin origin, EMDocument doc, EMElement parent, TransformationData data, EMMarkdownTaggedElementMatch match, string regionParameters)
        {
            var content = new EMRegion(doc, origin, parent, match, regionParameters);

            content.Elements.Parse(0, Markdown.OutdentIfPossible(match.Content, content.Elements.TextMap), data);

            return content;
        }
        private static EMElement CreateItem(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var item = new EMDefinitionListItem(doc, origin, parent);

            item.Parse(doc, match, data);

            return(item);
        }
Beispiel #8
0
 private EMTOCInline(EMDocument doc, EMElementOrigin origin, EMElement parent, int startLevel, int endLevel, EMDocument linkedDocument, string path)
     : base(doc, origin, parent)
 {
     this.startLevel     = startLevel;
     this.endLevel       = endLevel != 0 ? endLevel : int.MaxValue;
     this.linkedDocument = linkedDocument;
     this.path           = path;
 }
Beispiel #9
0
        public static EMElement CreateFromInline(EMDocument doc, EMElementOrigin orig, EMElement parent, TransformationData data, EMSpanElements content, string parameters)
        {
            var match = InlineParametersPattern.Match(parameters);
            var path  = match.Groups["path"].Value.Trim();
            var title = match.Groups["title"].Value;

            return(Create(doc, orig, parent, data, content, path, title));
        }
        public static EMElement CreateList(EMListParserMatch match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var list = new EMList(doc, origin, parent, match.Type);

            list.Parse(match.Text, data);

            return(list);
        }
Beispiel #11
0
        public static EMElement CreateRegion(EMElementOrigin origin, EMDocument doc, EMElement parent, TransformationData data, EMMarkdownTaggedElementMatch match, string regionParameters)
        {
            var content = new EMRegion(doc, origin, parent, match, regionParameters);

            content.Elements.Parse(0, Markdown.OutdentIfPossible(match.Content, content.Elements.TextMap), data);

            return(content);
        }
Beispiel #12
0
 private EMImage(EMDocument doc, EMElementOrigin origin, EMElement parent, EMLocalFilePath path, string title, string alt, ImageOptions options)
     : base(doc, origin, parent)
 {
     Path    = path;
     Title   = title;
     Alt     = alt;
     Options = options;
 }
 private EMTOCInline(EMDocument doc, EMElementOrigin origin, EMElement parent, int startLevel, int endLevel, EMDocument linkedDocument, string path)
     : base(doc, origin, parent)
 {
     this.startLevel = startLevel;
     this.endLevel = endLevel != 0 ? endLevel : int.MaxValue;
     this.linkedDocument = linkedDocument;
     this.path = path;
 }
Beispiel #14
0
        protected EMElement(EMDocument doc, EMElementOrigin origin, EMElement parent = null)
        {
            Origin   = origin;
            Parent   = parent;
            Document = doc;

            Messages = new List <EMReadingMessage>();
        }
Beispiel #15
0
 public EMInclude(EMDocument doc, EMElementOrigin origin, EMElement parent, EMExcerpt excerpt, int headerOffset = 1, bool languageChanged = false, bool includeTOC = true)
     : base(doc, origin, parent)
 {
     Excerpt         = excerpt;
     HeaderOffset    = headerOffset;
     LanguageChanged = languageChanged;
     IncludeTOC      = includeTOC;
 }
Beispiel #16
0
        private static EMElement CreateParagraph(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var contentGroup = match.Groups["content"];
            var spanContent  = new EMSpanElements(doc, new EMElementOrigin(origin.Start, contentGroup.Value), parent);

            spanContent.Parse(contentGroup.Value, data);

            return(new EMParagraph(doc, origin, parent, spanContent));
        }
Beispiel #17
0
        private static List <TableRowInformation> GetHeaders(EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data, int headerOffset, string tableHeader, out bool useRowHeader)
        {
            // Add headers
            // May be multiple lines, may have columns spanning
            // May also have no header if we are intending the 1st column to be the header

            var map = new PreprocessedTextLocationMap();

            tableHeader = RemoveTrailingWhitespaceAndNewLines(tableHeader, map);

            List <TableRowInformation> templateHeaderRows = null;

            useRowHeader = true;

            if (!String.IsNullOrWhiteSpace(tableHeader))
            {
                templateHeaderRows = new List <TableRowInformation>();

                var headerRowOffset = 0;

                var headerRows = Regex.Split(tableHeader, @"\n");
                foreach (var headerRow in headerRows)
                {
                    var count = 0;

                    var headerColumns = Regex.Matches(headerRow, @"[ ]?([^\|]+)[ ]?([\|]*)");
                    var row           = new TableRowInformation();

                    foreach (Match headerColumn in headerColumns)
                    {
                        var cellGroup        = headerColumn.Groups[1];
                        var columnSpanLength = 1;

                        if (Regex.Match(headerColumn.Groups[2].Value, @"(\|{2,})").Success)
                        {
                            columnSpanLength = Regex.Match(headerColumn.Groups[2].Value, @"(\|{2,})").Length;
                        }

                        var cell = new TableCellInformation(doc, new EMElementOrigin(headerOffset + map.GetOriginalPosition(headerRowOffset + cellGroup.Index, PositionRounding.Down), cellGroup.Value), parent, data, columnSpanLength, null, true);

                        if (count == 0)
                        {
                            useRowHeader = !Regex.Match(cell.ToString(), @"(\S)").Success;
                        }

                        count++;

                        row.Cells.Add(cell);
                    }

                    headerRowOffset += headerRow.Length + 1;
                    templateHeaderRows.Add(row);
                }
            }

            return(templateHeaderRows);
        }
            private void Reload()
            {
                FailWhenDisposed();

                var text = FileHelper.SafeReadAllText(path);

                document = new EMDocument(path, cache.TransformationData);
                document.Parse(text,true,false);
            }
        private static EMHeader CreateFromSetextMatch(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var headerText = match.Groups[2].Value;
            var level = match.Groups[3].Value.StartsWith("=") ? 1 : 2;
            var isOptional = string.IsNullOrWhiteSpace(match.Groups[1].Value);

            headerText = Markdown.Unescape(data.Markdown.RunSpanGamut(headerText, data));

            return new EMHeader(doc, origin, parent, level, headerText, isOptional);
        }
Beispiel #20
0
 public static EMErrorElement Create(
     EMDocument doc,
     EMElementOrigin origin,
     EMElement parent,
     TransformationData data,
     string messageId,
     params string[] messageArgs)
 {
     return new EMErrorElement(doc, origin, parent, new EMReadingMessage(MessageClass.Error, messageId, messageArgs), data);
 }
 public static EMErrorElement Create(
     EMDocument doc,
     EMElementOrigin origin,
     EMElement parent,
     TransformationData data,
     string messageId,
     params string[] messageArgs)
 {
     return(new EMErrorElement(doc, origin, parent, new EMReadingMessage(MessageClass.Error, messageId, messageArgs), data));
 }
Beispiel #22
0
        private static EMHeader CreateFromSetextMatch(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var headerText = match.Groups[2].Value;
            var level      = match.Groups[3].Value.StartsWith("=") ? 1 : 2;
            var isOptional = string.IsNullOrWhiteSpace(match.Groups[1].Value);

            headerText = Markdown.Unescape(data.Markdown.RunSpanGamut(headerText, data));

            return(new EMHeader(doc, origin, parent, level, headerText, isOptional));
        }
Beispiel #23
0
        private static EMElement CreateTOCInline(
            Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var start = 0;
            var end   = 0;

            SpacePattern.Split(match.Groups["params"].Value).ToList().ForEach(
                param =>
            {
                if (string.IsNullOrWhiteSpace(param))
                {
                    return;
                }

                var parts = param.Split(':');
                var name  = parts[0];
                var value = int.Parse(parts[1]);

                switch (name)
                {
                case "start":
                    start = value;
                    break;

                case "end":
                    end = value;
                    break;
                }
            });

            var path = match.Groups["path"].Value;
            ClosestFileStatus status;
            var linkedDoc = data.ProcessedDocumentCache.GetClosest(path, out status);

            if (status == ClosestFileStatus.FileMissing)
            {
                return(EMErrorElement.Create(doc, origin, parent, data, "BadIncludeOrMissingMarkdownFile", path));
            }

            if (status == ClosestFileStatus.ChangedToIntVersion || status == ClosestFileStatus.ExactMatch)
            {
                EMElement output = new EMTOCInline(doc, origin, parent, start, end, linkedDoc, path);

                if (status == ClosestFileStatus.ChangedToIntVersion)
                {
                    output.AddMessage(new EMReadingMessage(MessageClass.Info, "BadIncludeOrMissingMarkdownFileINTUsed", path), data);
                }

                return(output);
            }

            // should never happen!
            throw new InvalidOperationException("Bad linking file status.");
        }
Beispiel #24
0
        public EMTable(EMDocument doc, EMElementOrigin origin, EMElement parent, Match match, TransformationData data)
            : base(doc, origin, parent)
        {
            var tableAlignment = RemoveTrailingWhitespaceAndNewLines(match.Groups[3].Value, null);

            bool useRowHeader;

            optionalCaption       = data.Markdown.RunSpanGamut(GetOptionalCaption(match.Groups[0].Value), data);
            tableHeaderRows       = GetHeaders(doc, origin, this, data, match.Groups[2].Index - match.Index, match.Groups[2].Value, out useRowHeader);
            tableColumnAlignments = new List <Hash>();
            tableRows             = GetRows(this, data, match.Groups[5].Index - match.Index, match.Groups[5].Value, GetAlignments(tableAlignment, tableColumnAlignments), useRowHeader, !String.IsNullOrWhiteSpace(match.Groups[2].Value));
        }
Beispiel #25
0
        public static EMElement CreateFromText(string text, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data, bool imageLink = false)
        {
            try
            {
                var path = EMPathProvider.CreatePath(text, doc, data);

                return new EMRelativeLink(doc, origin, parent, path);
            }
            catch (EMPathVerificationException e)
            {
                return new EMErrorElement(doc, origin, parent, e.AddToErrorList(data, origin.Text));
            }
        }
        public PreprocessedData(EMDocument document, ProcessedDocumentCache manager)
        {
            Excerpts = new ExcerptsManager(this);
            Variables = new VariableManager(this);
            Metadata = new MetadataManager(this);
            ReferenceLinks = new ReferenceLinksManager(this);
            TextMap = new PreprocessedTextLocationMap();
            PreprocessedTextBounds = new List<PreprocessedTextBound>();

            Document = document;

            this.manager = manager;
        }
        public static EMElement CreateFromText(string text, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data, bool imageLink = false)
        {
            try
            {
                var path = EMPathProvider.CreatePath(text, doc, data);

                return(new EMRelativeLink(doc, origin, parent, path));
            }
            catch (EMPathVerificationException e)
            {
                return(new EMErrorElement(doc, origin, parent, e.AddToErrorList(data, origin.Text)));
            }
        }
        private static EMElement CreateItem(EMListType type, EMDocument doc, Match match, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var itemGroup = match.Groups[4];

            var item = new EMListItem(doc, origin, parent, type);

            // adding offset to text map
            item.Elements.TextMap.ApplyChanges(new List<PreprocessingTextChange>() { new PreprocessingTextChange(0, itemGroup.Index - match.Index, 0) });

            item.Elements.Parse(0, Markdown.Outdent(itemGroup.Value, item.Elements.TextMap), data);

            return item;
        }
        private static EMElement Create(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var bqTextGroup = match.Groups[1];
            var bqText = bqTextGroup.Value;

            bqText = Regex.Replace(bqText, @"^[ ]*>[ ]?", "", RegexOptions.Multiline);       // trim one level of quoting
            bqText = Regex.Replace(bqText, @"^[ ]+$", "", RegexOptions.Multiline);           // trim whitespace-only lines

            var bq = new EMBlockQuotes(doc, origin, parent);

            bq.Elements.Parse(origin.Start + bqTextGroup.Index, bqText, data);

            return bq;
        }
        private static EMElement Create(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var bqTextGroup = match.Groups[1];
            var bqText      = bqTextGroup.Value;

            bqText = Regex.Replace(bqText, @"^[ ]*>[ ]?", "", RegexOptions.Multiline);       // trim one level of quoting
            bqText = Regex.Replace(bqText, @"^[ ]+$", "", RegexOptions.Multiline);           // trim whitespace-only lines

            var bq = new EMBlockQuotes(doc, origin, parent);

            bq.Elements.Parse(origin.Start + bqTextGroup.Index, bqText, data);

            return(bq);
        }
Beispiel #31
0
 public TableCellInformation(
     EMDocument doc,
     EMElementOrigin origin,
     EMElement parent,
     TransformationData data,
     int colSpanCount     = 1,
     string alignment     = null,
     bool isRowHeader     = false,
     bool isDummy         = false,
     int rowSpanCount     = 1,
     bool isRowSpanColumn = false)
     : this(colSpanCount, alignment, isRowHeader, isDummy, rowSpanCount, isRowSpanColumn)
 {
     Content = new EMSpanElements(doc, origin, parent);
     Content.Parse(0, origin.Text, data);
 }
        private static EMHeader CreateFromAtxMatch(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var headerText = match.Groups[3].Value;

            if (headerText.Contains("ifndef") || headerText.Contains("endif"))
            {
                return null;
            }

            var level = match.Groups[1].Value.Length;
            var isOptional = string.IsNullOrWhiteSpace(match.Groups[2].Value);

            headerText = Markdown.Unescape(data.Markdown.RunSpanGamut(headerText, data));

            return new EMHeader(doc, origin, parent, level, headerText, isOptional);
        }
        private static EMElement CreateItem(EMListType type, EMDocument doc, Match match, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var itemGroup = match.Groups[4];

            var item = new EMListItem(doc, origin, parent, type);

            // adding offset to text map
            item.Elements.TextMap.ApplyChanges(new List <PreprocessingTextChange>()
            {
                new PreprocessingTextChange(0, itemGroup.Index - match.Index, 0)
            });

            item.Elements.Parse(0, Markdown.Outdent(itemGroup.Value, item.Elements.TextMap), data);

            return(item);
        }
Beispiel #34
0
        public static EMElement CreateFromAnchorRef(EMDocument doc, EMElementOrigin orig, EMElement parent, TransformationData data, EMSpanElements content, string parameters)
        {
            var match = AnchorRefParametersPattern.Match(parameters);

            var linkId = match.Groups["id"].Value.ToLowerInvariant();

            if (!data.ReferenceLinks.Urls.ContainsKey(linkId))
            {
                throw new EMSkipParsingException();
            }

            var url = data.ReferenceLinks.Urls[linkId];

            return(Create(doc, orig, parent, data, content, url,
                          GetReferenceTitle(data, linkId)));
        }
Beispiel #35
0
        public EMLink(EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data, EMPathProvider path, string title, EMSpanElements content)
            : base(doc, origin, parent)
        {
            Path = path;

            Title   = title;
            Content = content;

            if (path.ChangedLanguage)
            {
                AddMessage(
                    new EMReadingMessage(
                        MessageClass.Info, "BadLinkOrMissingMarkdownFileForLinkINTUsed", path.GetPath(data)),
                    data);
            }
        }
Beispiel #36
0
        private static EMHeader CreateFromAtxMatch(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var headerText = match.Groups[3].Value;

            if (headerText.Contains("ifndef") || headerText.Contains("endif"))
            {
                return(null);
            }

            var level      = match.Groups[1].Value.Length;
            var isOptional = string.IsNullOrWhiteSpace(match.Groups[2].Value);

            headerText = Markdown.Unescape(data.Markdown.RunSpanGamut(headerText, data));

            return(new EMHeader(doc, origin, parent, level, headerText, isOptional));
        }
        public static EMElements ExcerptLazyParser(EMDocument doc, EMElement parent, string content, TransformationData data)
        {
            content = Preprocessor.CutoutComments(content, null);

            var elements = new EMElements(doc, new EMElementOrigin(0, content), parent);

            var previousCurrentFolder = data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf;
            var newCurrentFolder = doc.GetAbsoluteMarkdownPath();

            data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf = newCurrentFolder;

            elements.Parse(content, data);

            data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf = previousCurrentFolder;

            return elements;
        }
Beispiel #38
0
        public static EMElements ExcerptLazyParser(EMDocument doc, EMElement parent, string content, TransformationData data)
        {
            content = Preprocessor.CutoutComments(content, null);

            var elements = new EMElements(doc, new EMElementOrigin(0, content), parent);

            var previousCurrentFolder = data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf;
            var newCurrentFolder      = doc.GetAbsoluteMarkdownPath();

            data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf = newCurrentFolder;

            elements.Parse(content, data);

            data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf = previousCurrentFolder;

            return(elements);
        }
Beispiel #39
0
        private static EMElement CreateFromInline(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var alt            = match.Groups[2].Value;
            var url            = match.Groups[3].Value;
            var title          = match.Groups[6].Value;
            var width          = match.Groups[9].Value;
            var height         = match.Groups[11].Value;
            var align          = match.Groups[13].Value;
            var convert        = match.Groups[15].Value;
            var convertType    = match.Groups[17].Value;
            var convertQuality = match.Groups[19].Value;
            var hexFillColor   = match.Groups[21].Value;

            return(Create(
                       data, doc, origin, parent, url, alt, title, convert, width,
                       height, convertQuality, hexFillColor, convertType,
                       new ImageOptions(width, height, align)));
        }
Beispiel #40
0
        private static EMElement CreateFromReference(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var alt = match.Groups[2].Value;


            var linkId = match.Groups[3].Value.ToLowerInvariant();

            // for shortcut links like ![this][].
            if (linkId == "")
            {
                linkId = alt.ToLowerInvariant();
            }

            alt = alt.Replace("\"", "&quot;");

            if (!data.ReferenceLinks.Urls.ContainsKey(linkId))
            {
                return(EMErrorElement.Create(doc, origin, parent, data, "MissingImageRef", linkId));
            }

            var url = data.ReferenceLinks.Urls[linkId];

            var imageFormat = data.ReferenceLinks.ReferenceAttributes[linkId];

            var width          = imageFormat.Width;
            var height         = imageFormat.Height;
            var convert        = imageFormat.DoCompressImages;
            var convertType    = imageFormat.ConvertImageFormat;
            var convertQuality = imageFormat.ImageQuality;
            var hexFillColor   = imageFormat.ImageFill;

            var options = data.ReferenceLinks.ImageAlignment.ContainsKey(linkId)
                              ? data.ReferenceLinks.ImageAlignment[linkId]
                              : new ImageOptions();

            var title = data.ReferenceLinks.Titles.ContainsKey(linkId)
                            ? Markdown.EscapeBoldItalic(data.ReferenceLinks.Titles[linkId])
                            : null;

            return(Create(
                       data, doc, origin, parent, url, alt, title, convert, width,
                       height, convertQuality, hexFillColor, convertType, options));
        }
Beispiel #41
0
        public static EMElement CreateFromAnchorRefShortcut(Match match, EMDocument doc, EMElementOrigin orig, EMElement parent, TransformationData data)
        {
            var linkText = match.Groups[2].Value;
            var linkId   = Regex.Replace(linkText.ToLowerInvariant(), @"[ ]*\n[ ]*", " ");

            if (!data.ReferenceLinks.Urls.ContainsKey(linkId))
            {
                throw new EMSkipParsingException();
            }

            var url = data.ReferenceLinks.Urls[linkId];

            var content = new EMSpanElements(
                doc, new EMElementOrigin(orig.Start + match.Groups[2].Index, linkText), parent);

            content.Parse(match.Groups[2].Value, data);

            return(Create(doc, orig, parent, data, content, url, GetReferenceTitle(data, linkId)));
        }
        public static EMObjectParam CreateParam(EMElementOrigin origin, EMDocument doc, EMElement parent, TransformationData data, EMMarkdownTaggedElementMatch match, string paramName, string paramIndentation)
        {
            var content = new EMObjectParam(doc, origin, parent, match, paramName);

            var text =
                Preprocessor.Replace(
                    new Regex(
                        "^" + Regex.Escape(paramIndentation), RegexOptions.Multiline),
                    content.Elements.Origin.Text,
                    "",
                    content.Elements.TextMap);

            text = Preprocessor.Trim(text, '\n', content.Elements.TextMap);

            text = Markdown.OutdentIfPossible(text, content.Elements.TextMap);

            content.Elements.Parse(0, text, data);

            return content;
        }
Beispiel #43
0
        public static EMObjectParam CreateParam(EMElementOrigin origin, EMDocument doc, EMElement parent, TransformationData data, EMMarkdownTaggedElementMatch match, string paramName, string paramIndentation)
        {
            var content = new EMObjectParam(doc, origin, parent, match, paramName);

            var text =
                Preprocessor.Replace(
                    new Regex(
                        "^" + Regex.Escape(paramIndentation), RegexOptions.Multiline),
                    content.Elements.Origin.Text,
                    "",
                    content.Elements.TextMap);

            text = Preprocessor.Trim(text, '\n', content.Elements.TextMap);

            text = Markdown.OutdentIfPossible(text, content.Elements.TextMap);

            content.Elements.Parse(0, text, data);

            return(content);
        }
Beispiel #44
0
        public static TOCBranch GetFromDocument(EMDocument linkedDocument, int startLevel, int endLevel)
        {
            var root = new TOCBranch();

            linkedDocument.Data.ForEachWithContext(
                new TOCTreeBuildingContext(
                    (header, includesStack) =>
                    {
                        var level = header.GetLevelWithOffsets(includesStack);

                        if(level >= startLevel && level <= endLevel)
                        {
                            root.Add(level, header.Text, "#" + header.UniqueKey);
                        }
                    }));

            root.DeleteNonRootVirtualBranches();

            return root;
        }
Beispiel #45
0
        public static TOCBranch GetFromDocument(EMDocument linkedDocument, int startLevel, int endLevel)
        {
            var root = new TOCBranch();

            linkedDocument.Data.ForEachWithContext(
                new TOCTreeBuildingContext(
                    (header, includesStack) =>
            {
                var level = header.GetLevelWithOffsets(includesStack);

                if (level >= startLevel && level <= endLevel)
                {
                    root.Add(level, header.Text, "#" + header.UniqueKey);
                }
            }));

            root.DeleteNonRootVirtualBranches();

            return(root);
        }
        public string ReplaceVariables(EMDocument doc, string text, TransformationData data, PreprocessedTextLocationMap map = null)
        {
            text = EMTOCInline.ConvertVariableLikeTOCInlines(text, map);

            var stack = new Stack<Tuple<string, string>>();
            var currentFile = new FileInfo(doc.LocalPath);

            return map == null
                       ? InLineVariableOrMetadata.Replace(
                           text,
                           everyMatch =>
                           ParseInLineVariableOrMetadata(everyMatch, currentFile, currentFile, data, doc, stack))
                       : Preprocessor.Replace(
                           InLineVariableOrMetadata,
                           text,
                           everyMatch =>
                           ParseInLineVariableOrMetadata(everyMatch, currentFile, currentFile, data, doc, stack),
                           map);
        }
        private string ParseInLineVariableOrMetadata(Match match, FileInfo currentFile, FileInfo originalScope, TransformationData data, EMDocument doc, Stack<Tuple<string, string>> visitedVariables)
        {
            var pathToLinkedFile = match.Groups["path"].Value;
            var variableName = match.Groups["variableName"].Value.ToLower();
            var originalString = match.Value;
            string relativePathToLinkedFile = null;

            var outString = "";
            var isProblem = false;
            var changedLanguage = false;

            var errorId = 0;
            var OnErrorStringToUseForMatch = originalString;

            //ignore if the value is STOPPUBLISH STARTPUBLISH
            if (variableName.Equals("STOPPUBLISH") || variableName.Equals("STARTPUBLISH") || originalString.ToUpper() == "%ROOT%" || VariableManager.IsKeywordToSkip(originalString))
            {
                return originalString;
            }
            else
            {
                if (pathToLinkedFile.Equals("doxygen"))
                {
                    var excerptName = ("doxygen:" + match.Groups["variableName"].Value).Replace(':', 'x');

                    if (!doc.Excerpts.Exists(excerptName))
                    {
                        var content =
                            DoxygenHelper.GetSymbolDescriptionAndCatchExceptionIntoMarkdownErrors(
                                match.Groups["variableName"].Value,
                                match.Value,
                                DoxygenHelper.DescriptionType.Full,
                                data,
                                data.Markdown,
                                data.FoundDoxygenSymbols).Trim();

                        content = Normalizer.Normalize(content, null);

                        doc.Excerpts.AddExcerpt(
                            excerptName, new EMExcerpt(doc, 0, 0, content, data, excerptName == ""));
                    }

                    return string.Format("[INCLUDE:#{0}]", excerptName);
                }
                if (pathToLinkedFile.Equals("orig"))
                {
                    currentFile = originalScope;
                    relativePathToLinkedFile = data.CurrentFolderDetails.CurrentFolderFromMarkdownAsTopLeaf;
                }
                else if (!String.IsNullOrWhiteSpace(pathToLinkedFile))
                {
                    // Link other file and get metadata from there.
                    var languageForFile = data.CurrentFolderDetails.Language;
                    relativePathToLinkedFile = pathToLinkedFile;

                    var linkedFileDir = new DirectoryInfo(Path.Combine(Path.Combine(data.CurrentFolderDetails.AbsoluteMarkdownPath, pathToLinkedFile)));

                    if (!linkedFileDir.Exists || linkedFileDir.GetFiles(string.Format("*.{0}.udn", data.CurrentFolderDetails.Language)).Length == 0)
                    {
                        // if this is not an INT file check for the INT version.
                        if (data.CurrentFolderDetails.Language != "INT")
                        {
                            if (!linkedFileDir.Exists || linkedFileDir.GetFiles("*.INT.udn").Length == 0)
                            {
                                errorId = data.ErrorList.Count;
                                data.ErrorList.Add(
                                    Markdown.GenerateError(
                                        Language.Message(
                                            "BadLinkOrMissingMarkdownFileAndNoINTFile", pathToLinkedFile, variableName),
                                        MessageClass.Error,
                                        Markdown.Unescape(OnErrorStringToUseForMatch),
                                        errorId,
                                        data));

                                isProblem = true;
                            }
                            else
                            {
                                // Found int file
                                languageForFile = "INT";

                                // Raise info so that now we are allowing missing linked files to still allow processing of the file if INT file is there
                                errorId = data.ErrorList.Count;
                                data.ErrorList.Add(
                                    Markdown.GenerateError(
                                        Language.Message(
                                            "BadLinkOrMissingMarkdownFileINTUsed", pathToLinkedFile, variableName),
                                        MessageClass.Info,
                                        Markdown.Unescape(OnErrorStringToUseForMatch),
                                        errorId,
                                        data));

                                isProblem = true;

                                changedLanguage = true;
                            }
                        }
                        else
                        {
                            errorId = data.ErrorList.Count;
                            data.ErrorList.Add(
                                Markdown.GenerateError(
                                    Language.Message("BadLinkOrMissingMarkdownFile", pathToLinkedFile, variableName),
                                    MessageClass.Error,
                                    Markdown.Unescape(OnErrorStringToUseForMatch),
                                    errorId,
                                    data));

                            isProblem = true;
                            outString = OnErrorStringToUseForMatch;
                        }
                    }

                    if (linkedFileDir.Exists && linkedFileDir.GetFiles(string.Format("*.{0}.udn", languageForFile)).Length > 0)
                    {
                        currentFile = linkedFileDir.GetFiles(string.Format("*.{0}.udn", languageForFile))[0];
                    }
                }

                // Cycle detection mechanism. First check if there was request for that variable in the visited stack.
                var currentVisitedVariableTuple = new Tuple<string, string>(currentFile.FullName, variableName);
                if (visitedVariables != null && visitedVariables.Contains(currentVisitedVariableTuple))
                {
                    // cycle detected
                    visitedVariables.Push(currentVisitedVariableTuple);
                    string visitedVariablesMessage = string.Join(", ", visitedVariables.Select(
                            (v) =>
                            {
                                return string.Format("[{0}, {1}]", v.Item1, v.Item2);
                            }));
                    visitedVariables.Pop();

                    data.ErrorList.Add(
                        Markdown.GenerateError(Language.Message("CycleDetectedInVariableRefs", visitedVariablesMessage), MessageClass.Error,
                        "", data.ErrorList.Count, data));

                    return "";
                }

                if (!data.ProcessedDocumentCache.TryGetLinkedFileVariable(currentFile, variableName, out outString))
                {
                    if (doc.PerformStrictConversion())
                    {
                        //error
                        errorId = data.ErrorList.Count;
                        data.ErrorList.Add(
                            Markdown.GenerateError(
                                Language.Message("VariableOrMetadataNotFoundInFile", variableName, currentFile.FullName),
                                MessageClass.Error,
                                OnErrorStringToUseForMatch,
                                errorId,
                                data));

                        isProblem = true;
                    }
                    outString = OnErrorStringToUseForMatch.Replace("%", "&#37;");
                }
                else
                {
                    // If there was no request for this variable then push it.
                    visitedVariables.Push(currentVisitedVariableTuple);

                    outString = InLineVariableOrMetadata.Replace(
                        outString,
                        everyMatch =>
                        ParseInLineVariableOrMetadata(everyMatch, currentFile, originalScope, data, doc, visitedVariables));

                    // After parsing inner string pop visited variable from the stack.
                    visitedVariables.Pop();
                }

                if (changedLanguage)
                {
                    //If we had to replace the language with INT then update the linkText to include link to image of flag
                    outString += Templates.ImageFrame.Render(
                        Hash.FromAnonymousObject(
                            new
                            {
                                imageClass = "languageinline",
                                imagePath = Path.Combine(
                                    data.CurrentFolderDetails.RelativeHTMLPath,
                                    "Include", "Images", "INT_flag.jpg")
                            }));
                }
            }

            if (data.Markdown.ThisIsPreview && isProblem)
            {
                return Templates.ErrorHighlight.Render(
                    Hash.FromAnonymousObject(
                        new
                        {
                            errorId = errorId,
                            errorText = outString
                        }));
            }

            return outString;
        }
Beispiel #48
0
        private static EMElement CreateFromInline(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var alt = match.Groups[2].Value;
            var url = match.Groups[3].Value;
            var title = match.Groups[6].Value;
            var width = match.Groups[9].Value;
            var height = match.Groups[11].Value;
            var align = match.Groups[13].Value;
            var convert = match.Groups[15].Value;
            var convertType = match.Groups[17].Value;
            var convertQuality = match.Groups[19].Value;
            var hexFillColor = match.Groups[21].Value;

            return Create(
                data, doc, origin, parent, url, alt, title, convert, width,
                height, convertQuality, hexFillColor, convertType,
                new ImageOptions(width, height, align));
        }
 private EMListItem(EMDocument doc, EMElementOrigin origin, EMElement parent, EMListType type)
     : base(doc, origin, parent, 0, origin.Length)
 {
 }
Beispiel #50
0
        private static EMElement CreateTOCInline(
            Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var start = 0;
            var end = 0;
            
            SpacePattern.Split(match.Groups["params"].Value).ToList().ForEach(
                param =>
                    {
                        if (string.IsNullOrWhiteSpace(param))
                        {
                            return;
                        }

                        var parts = param.Split(':');
                        var name = parts[0];
                        var value = int.Parse(parts[1]);

                        switch (name)
                        {
                            case "start":
                                start = value;
                                break;
                            case "end":
                                end = value;
                                break;
                        }
                    });

            var path = match.Groups["path"].Value;
            ClosestFileStatus status;
            var linkedDoc = data.ProcessedDocumentCache.GetClosest(path, out status);

            if (status == ClosestFileStatus.FileMissing)
            {
                return EMErrorElement.Create(doc, origin, parent, data, "BadIncludeOrMissingMarkdownFile", path);
            }

            if (status == ClosestFileStatus.ChangedToIntVersion || status == ClosestFileStatus.ExactMatch)
            {
                EMElement output = new EMTOCInline(doc, origin, parent, start, end, linkedDoc, path);

                if (status == ClosestFileStatus.ChangedToIntVersion)
                {
                    output.AddMessage(new EMReadingMessage(MessageClass.Info, "BadIncludeOrMissingMarkdownFileINTUsed", path), data);
                }

                return output;
            }

            // should never happen!
            throw new InvalidOperationException("Bad linking file status.");
        }
        public static List<PathElement> GetSuggestionList(EMDocument doc, string userPath, PathElementType options)
        {
            var list = new List<PathElement>();
            var emptyInputPath = false;

            if (string.IsNullOrWhiteSpace(userPath))
            {
                emptyInputPath = true;
                userPath = "";
            }

            var langId = LangIdPattern.Match(Path.GetFileName(doc.LocalPath)).Groups["langId"].Value;

            var m = RootKeywordPattern.Match(userPath);

            userPath = m.Success
                           ? userPath.Replace(m.Value, GetSourceDir(doc.LocalPath))
                           : Path.Combine(Path.GetDirectoryName(doc.LocalPath), userPath);

            DirectoryInfo userDir;

            try
            {
                userDir = new DirectoryInfo(userPath);
            }
            catch (Exception e)
            {
                if (e is ArgumentNullException || e is SecurityException || e is ArgumentException
                    || e is PathTooLongException)
                {
                    // ignore and output empty list
                    return list;
                }

                throw;
            }

            if (userDir.Exists)
            {
                if ((options & (PathElementType.Image | PathElementType.Attachment | PathElementType.Folder)) > 0)
                {
                    // File system infos.

                    var dirs = userDir.GetDirectories();

                    if (options.HasFlag(PathElementType.Image))
                    {
                        var imagesDirs = dirs.Where(d => d.Name.ToLower() == "images").ToArray();

                        if (imagesDirs.Length > 0)
                        {
                            list.AddRange(
                                imagesDirs[0].GetFiles().Select(f => new PathElement(f.Name, PathElementType.Image)));
                        }
                    }

                    if (options.HasFlag(PathElementType.Attachment))
                    {
                        var attachmentsDirs = dirs.Where(d => d.Name.ToLower() == "attachments").ToArray();

                        if (attachmentsDirs.Length > 0)
                        {
                            list.AddRange(
                                attachmentsDirs[0].GetFiles()
                                                  .Select(f => new PathElement(f.Name, PathElementType.Attachment)));
                        }
                    }

                    if (options.HasFlag(PathElementType.Folder))
                    {
                        if (emptyInputPath)
                        {
                            list.Add(new PathElement("%ROOT%", PathElementType.Folder));
                        }

                        list.AddRange(
                            dirs.Where(d => d.Name.ToLower() != "attachments" && d.Name.ToLower() != "images")
                                .Select(d => new PathElement(d.Name, PathElementType.Folder)));
                    }
                }

                if ((options & (PathElementType.Bookmark | PathElementType.Excerpt | PathElementType.Variable)) > 0)
                {
                    var files = userDir.GetFiles(string.Format("*.{0}.udn", langId));

                    if (files.Length > 0)
                    {
                        var linkedDocument = files[0].FullName.Equals(doc.LocalPath, StringComparison.InvariantCultureIgnoreCase)
                                                 ? doc
                                                 : doc.TransformationData.ProcessedDocumentCache.Get(files[0].FullName);

                        if (options.HasFlag(PathElementType.Bookmark) && emptyInputPath)
                        {
                            list.AddRange(linkedDocument.GetBookmarkKeys().Select(n => new PathElement(n, PathElementType.Bookmark)));
                        }

                        if (options.HasFlag(PathElementType.Excerpt))
                        {
                            list.AddRange(linkedDocument.GetExcerptNames().Select(n => new PathElement(n, PathElementType.Excerpt)));
                        }

                        if (options.HasFlag(PathElementType.Variable))
                        {
                            list.AddRange(linkedDocument.GetVariableNames().Select(n => new PathElement(n, PathElementType.Variable)));
                        }
                    }
                }
            }

            return list;
        }
 public EMSpanElements(EMDocument doc, EMElementOrigin origin, EMElement parent)
     : base(doc, origin, parent)
 {
 }
        private static EMElement Create(Match match, EMDocument doc, EMElementOrigin origin, EMElement parent, TransformationData data)
        {
            var bookmark = match.Groups["BookmarkName"].Value;

            return new EMBookmark(doc, origin, parent, bookmark);
        }
 protected EMBookmark(EMDocument doc, EMElementOrigin origin, EMElement parent, string bookmark)
     : base(doc, origin, parent)
 {
     Name = bookmark;
     UniqueKey = MakeUniqueKey(Name.ToLower());
 }
 private EMBlockQuotes(EMDocument doc, EMElementOrigin origin, EMElement parent)
     : base(doc, origin, parent, 0, origin.Length)
 {
 }
 public EMFormattedText(EMDocument doc, EMElementOrigin origin, EMElement parent)
     : base(doc, origin, parent)
 {
 }
Beispiel #57
0
 public EMRegion(EMDocument doc, EMElementOrigin origin, EMElement parent, EMMarkdownTaggedElementMatch match, string regionParam, bool singleLine = false)
     : base(doc, origin, parent, match.ContentStart, match.ContentLength)
 {
     this.singleLine = singleLine;
     RegionParam = regionParam;
 }
Beispiel #58
0
        private static EMElement Create(
            TransformationData data,
            EMDocument doc,
            EMElementOrigin origin,
            EMElement parent,
            string url,
            string alt,
            string title,
            string convert,
            string width,
            string height,
            string convertQuality,
            string hexFillColor,
            string convertType,
            ImageOptions options)
        {
            ImageFormat imageFormatType;

            if (String.IsNullOrWhiteSpace(url))
            {
                return EMErrorElement.Create(doc, origin, parent, data, "EmptyLink", origin.Text);
            }

            alt = alt.Replace("\"", "&quot;");

            if (title != null)
            {
                title = title.Replace("\"", "&quot;");
            }

            if (url.StartsWith("<") && url.EndsWith(">"))
            {
                url = url.Substring(1, url.Length - 2); // Remove <>'s surrounding URL, if present
            }

            if (String.IsNullOrWhiteSpace(alt))
            {
                //if no alt text provided use the file name.
                alt = Regex.Replace(url, @".*[\\|/](.*)", "$1");
            }

            var doConvert = !convert.ToLower().Equals("false") && data.Markdown.DefaultImageDoCompress;

            int widthIntConverted;
            int heightIntConverted;
            int quality;

            Color fillColor;

            if (doConvert)
            {
                //if we are converting try to get the other values
                //try parse the strings for width and height into integers
                try
                {
                    widthIntConverted = Int32.Parse(width);
                }
                catch (FormatException)
                {
                    widthIntConverted = 0;
                }

                try
                {
                    heightIntConverted = Int32.Parse(height);
                }
                catch (FormatException)
                {
                    heightIntConverted = 0;
                }

                try
                {
                    quality = Int32.Parse(convertQuality);
                }
                catch (FormatException)
                {
                    quality = data.Markdown.DefaultImageQuality;
                }

                try
                {
                    fillColor = ImageConversion.GetColorFromHexString(hexFillColor);
                }
                catch (Exception)
                {
                    fillColor = data.Markdown.DefaultImageFillColor;
                }

                if (String.IsNullOrWhiteSpace(convertType))
                {
                    convertType = data.Markdown.DefaultImageFormatExtension;
                    imageFormatType = data.Markdown.DefaultImageFormat;
                }
                else
                {
                    try
                    {
                        imageFormatType = ImageConversion.GetImageFormat(convertType.ToLower());
                    }
                    catch (Exception)
                    {
                        return EMErrorElement.Create(
                            doc,
                            origin,
                            parent,
                            data,
                            "UnsupportedImageFileTypeConversion",
                            Markdown.Unescape(url),
                            convertType.ToLower());
                    }
                }
            }
            else
            {
                //set width and height to zero indicating to converter that we want to use the images values
                widthIntConverted = 0;
                heightIntConverted = 0;

                //set conversion type to itself, but do check it is a supported image type.
                convertType =
                    Regex.Match(Markdown.Unescape(url), @"\.(png|gif|tga|bmp|jpg)", RegexOptions.IgnoreCase).Groups[1].Value;

                try
                {
                    imageFormatType = ImageConversion.GetImageFormat(convertType.ToLower());
                }
                catch (Exception)
                {
                    return EMErrorElement.Create(
                        doc,
                        origin,
                        parent,
                        data,
                        "UnsupportedImageFileTypeConversion",
                        Markdown.Unescape(url),
                        convertType.ToLower());
                }

                quality = 100;
                fillColor = data.Markdown.DefaultImageFillColor;
            }

            if (!String.IsNullOrWhiteSpace(convertType))
            {
                try
                {
                    var path = new EMLocalFilePath(Markdown.Unescape(url), doc, data,
                        fileName => System.IO.Path.GetFileNameWithoutExtension(fileName) + "." + ImageConversion.GetImageExt(imageFormatType));

                    if (!path.IsImage)
                    {
                        throw new EMPathVerificationException(Language.Message("GivenPathIsNotAnImage", url));
                    }

                    data.ImageDetails.Add(
                        new ImageConversion(
                            path.GetSource(),
                            path.GetAbsolutePath(data),
                            widthIntConverted,
                            heightIntConverted,
                            doConvert,
                            imageFormatType,
                            fillColor,
                            quality));

                    return new EMImage(doc, origin, parent, path, title, alt, options);
                }
                catch (EMPathVerificationException e)
                {
                    return new EMErrorElement(doc, origin, parent, e.AddToErrorList(data, origin.Text));
                }
            }

            throw new InvalidOperationException("Should not happen!");
        }
Beispiel #59
0
 public EMRawHTML(EMDocument doc, EMElementOrigin origin, EMElement parent, string name, string attributesString)
     : base(doc, origin, parent, 0, origin.Length)
 {
     this.name = name;
     this.attributesString = attributesString;
 }
Beispiel #60
0
 private EMRelativeLink(EMDocument doc, EMElementOrigin origin, EMElement parent, EMPathProvider path)
     : base(doc, origin, parent)
 {
     this.path = path;
 }