Пример #1
0
        public static void ProcessStage2(Syntax.Block document, CommonMarkSettings settings = null)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (document.Tag != Syntax.BlockTag.Document)
            {
                throw new ArgumentException("The block element passed to this method must represent a top level document.", "document");
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            try
            {
                BlockMethods.ProcessInlines(document, document.ReferenceMap, settings);
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred during inline parsing.", ex);
            }
        }
Пример #2
0
        private string loadMDFile(string file)
        {
            CommonMark.CommonMarkSettings settings = CommonMark.CommonMarkSettings.Default.Clone();
            string itog;

            // by using a in-memory source, the disparity of results is reduced.
            if (File.Exists(file))
            {
                using (var reader = new System.IO.StreamReader(file))
                    using (var writer = new System.IO.StringWriter())
                    {
                        try
                        {
                            CommonMark.CommonMarkConverter.Convert(reader, writer, settings);
                            itog = writer.ToString();
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                return(itog);
            }
            else
            {
                MessageBox.Show(string.Format("Файл {0} не обнаружен.", file));
            }
            return(null);
        }
Пример #3
0
        public static void ProcessStage2(Syntax.Block document, CommonMarkSettings settings = null)
        {
            if (document == null)
            {
                throw new ArgumentNullException(document.ToString());
            }

            if (document.Tag != Syntax.BlockTag.Document)
            {
                throw new ArgumentException("Блочный элемент, предоставляемый методу, должен быть высокоуровневым документом.", document.ToString());
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            try
            {
                BlockMethods.ProcessInlines(document, document.ReferenceMap, settings);
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("Ошибка при инлайн-парсинге.", ex);
            }
        }
Пример #4
0
        public static void ProcessStage3(Syntax.Block document, TextWriter target, CommonMarkSettings settings = null)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            if (document.Tag != Syntax.BlockTag.Document)
            {
                throw new ArgumentException("The block element passed to this method must represent a top level document.", "document");
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            try
            {
                switch (settings.OutputFormat)
                {
                case OutputFormat.Html:
                    HtmlFormatterSlim.BlocksToHtml(target, document, settings);
                    break;

                case OutputFormat.SyntaxTree:
                    Printer.PrintBlocks(target, document, settings);
                    break;

                case OutputFormat.CustomDelegate:
                    if (settings.OutputDelegate == null)
                    {
                        throw new CommonMarkException("If `settings.OutputFormat` is set to `CustomDelegate`, the `settings.OutputDelegate` property must be populated.");
                    }
                    settings.OutputDelegate(document, target, settings);
                    break;

                default:
                    throw new CommonMarkException("Unsupported value '" + settings.OutputFormat + "' in `settings.OutputFormat`.");
                }
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred during formatting of the document.", ex);
            }
        }
Пример #5
0
        public static void ProcessStage3(Syntax.Block document, TextWriter target, CommonMarkSettings settings = null)
        {
            if (document == null)
            {
                throw new ArgumentNullException(document.ToString());
            }

            if (target == null)
            {
                throw new ArgumentNullException(target.ToString());
            }

            if (document.Tag != Syntax.BlockTag.Document)
            {
                throw new ArgumentException("Блочный элемент, предоставляемый методу, болжен быть высокоуровневым документом.", document.ToString());
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            try
            {
                switch (settings.OutputFormat)
                {
                case OutputFormat.Html:
                    HtmlFormatterSlim.BlocksToHtml(target, document, settings);
                    break;

                case OutputFormat.SyntaxTree:
                    Printer.PrintBlocks(target, document, settings);
                    break;

                case OutputFormat.CustomDelegate:
                    if (settings.OutputDelegate == null)
                    {
                        throw new CommonMarkException("Если `settings.OutputFormat` установлен в `CustomDelegate`, свойство `settings.OutputDelegate` должно быть заполнено.");
                    }
                    settings.OutputDelegate(document, target, settings);
                    break;

                default:
                    throw new CommonMarkException("Неподдерживаемое значение '" + settings.OutputFormat + "' в `settings.OutputFormat`.");
                }
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("Ошибка при форматировании документа.", ex);
            }
        }
Пример #6
0
        public static Syntax.Block ProcessStage1(TextReader source, CommonMarkSettings settings = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            var cur  = Syntax.Block.CreateDocument();
            var doc  = cur;
            var line = new LineInfo(settings.TrackSourcePosition);

            try
            {
                var reader = new TabTextReader(source);
                reader.ReadLine(line);
                while (line.Line != null)
                {
                    BlockMethods.IncorporateLine(line, ref cur);
                    reader.ReadLine(line);
                }
            }
            catch (IOException)
            {
                throw;
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred while parsing line " + line.ToString(), cur, ex);
            }

            try
            {
                do
                {
                    BlockMethods.Finalize(cur, line);
                    cur = cur.Parent;
                } while (cur != null);
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred while finalizing open containers.", cur, ex);
            }

            return(doc);
        }
Пример #7
0
        public static Syntax.Block ProcessStage1(TextReader source, CommonMarkSettings settings = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException(source.ToString());
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            var cur  = Syntax.Block.CreateDocument();
            var doc  = cur;
            var line = new LineInfo(settings.TrackSourcePosition);

            try
            {
                var reader = new TabTextReader(source);
                reader.ReadLine(line);
                while (line.Line != null)
                {
                    BlockMethods.IncorporateLine(line, ref cur);
                    reader.ReadLine(line);
                }
            }
            catch (IOException)
            {
                throw;
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("Ошибка при разборе строки " + line.ToString(), cur, ex);
            }

            try
            {
                do
                {
                    BlockMethods.Finalize(cur, line);
                    cur = cur.Parent;
                } while (cur != null);
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("Ошибка при финализации открытых контейнеров.", cur, ex);
            }

            return(doc);
        }
        /// <summary>
        /// Initializes a new instance of <see cref="InjectAnchorHtmlFormatter"/>.
        /// </summary>
        /// <param name="contextName">Initializes the required <see cref="ContextName"/></param>
        /// <param name="target">Initializes the required text writter used as output.</param>
        /// <param name="settings">Initializes the required common mark settings used by the formatting.</param>
        public InjectAnchorHtmlFormatter(string contextName, TextWriter target, CommonMarkSettings settings)
            : base(target, settings)
        {
            // Data validation
            Ensure.That(() => contextName).IsNotNullOrWhiteSpace();

            // Initialize
            this.ContextName = contextName;
        }
Пример #9
0
        /// <summary>
        /// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
        /// convert the document to HTML using the built-in converter.
        /// </summary>
        /// <param name="source">The source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static Syntax.Block Parse(string source, CommonMarkSettings settings = null)
        {
            if (source == null)
            {
                return(null);
            }

            using (var reader = new System.IO.StringReader(source))
                return(Parse(reader, settings));
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of <see cref="InjectAnchorHtmlFormatter"/>.
        /// </summary>
        /// <param name="contextName">Initializes the required <see cref="ContextName"/></param>
        /// <param name="pageSlippingIdentifier">Initializes the required <see cref="PageSplittingIdentifier"/></param>
        /// <param name="target">Initializes the required text writter used as output.</param>
        /// <param name="settings">Initializes the required common mark settings used by the formatting.</param>
        public InjectAnchorHtmlFormatter(string contextName, string pageSlippingIdentifier, TextWriter target, CommonMarkSettings settings)
            : base(target, settings)
        {
            // Data validation
            Ensure.That(() => contextName).IsNotNullOrWhiteSpace();
            Ensure.That(() => pageSlippingIdentifier).IsNotNullOrWhiteSpace();

            // Initialize
            this.ContextName = contextName;
            this.PageSplittingIdentifier = pageSlippingIdentifier;
        }
Пример #11
0
        /// <summary>
        /// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
        /// convert the document to HTML using the built-in converter.
        /// </summary>
        /// <param name="source">The reader that contains the source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static Syntax.Block Parse(TextReader source, CommonMarkSettings settings = null)
        {
            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            var document = ProcessStage1(source, settings);

            ProcessStage2(document, settings);
            return(document);
        }
Пример #12
0
        /// <summary>
        /// Converts the given source data and writes the result directly to the target.
        /// </summary>
        /// <param name="source">The reader that contains the source data.</param>
        /// <param name="target">The target text writer where the result will be written to.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> or <paramref name="target"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static void Convert(TextReader source, TextWriter target, CommonMarkSettings settings = null)
        {
            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            var document = ProcessStage1(source, settings);

            ProcessStage2(document, settings);
            ProcessStage3(document, target, settings);
        }
        public static CommonMarkSettings WithMarkdownFormatter(this CommonMarkSettings settings)
        {
            if (settings.OutputFormat == OutputFormat.CustomDelegate &&
                settings.OutputDelegate == Formatter)
            {
                return(settings);
            }

            settings = settings.Clone();
            settings.OutputFormat   = OutputFormat.CustomDelegate;
            settings.OutputDelegate = Formatter;

            return(settings);
        }
Пример #14
0
        /// <summary>
        /// Converts the given source data and returns the result as a string.
        /// </summary>
        /// <param name="source">The source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
        /// <returns>The converted data.</returns>
        public static string Convert(string source, CommonMarkSettings settings = null)
        {
            if (source == null)
            {
                return(null);
            }

            using (var reader = new System.IO.StringReader(source))
                using (var writer = new System.IO.StringWriter(System.Globalization.CultureInfo.CurrentCulture))
                {
                    Convert(reader, writer, settings);

                    return(writer.ToString());
                }
        }
        public static void ProcessStage3(Syntax.Block document, TextWriter target, CommonMarkSettings settings = null)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            if (document.Tag != Syntax.BlockTag.Document)
            {
                throw new ArgumentException("The block element passed to this method must represent a top level document.", "document");
            }

            if (settings == null)
            {
                settings = CommonMarkSettings.Default;
            }

            try
            {
                if (settings.OutputFormat == OutputFormat.SyntaxTree)
                {
                    Printer.PrintBlocks(target, document, settings);
                }
                else
                {
                    HtmlPrinter.BlocksToHtml(target, document, settings);
                }
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred during formatting of the document.", ex);
            }
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of <see cref="ProjbookHtmlFormatter"/>.
        /// </summary>
        /// <param name="contextName">Initializes the required <see cref="ContextName"/></param>
        /// <param name="target">Initializes the required text writer used as output.</param>
        /// <param name="settings">Initializes the required common mark settings used by the formatting.</param>
        /// <param name="sectionTitleBase">Initializes the section title base.</param>
        /// <param name="snippetDictionary">Initializes the snippet directory.</param>
        /// <param name="snippetReferencePrefix">Initializes the snippet reference prefix.</param>
        public ProjbookHtmlFormatter(string contextName, TextWriter target, CommonMarkSettings settings, int sectionTitleBase, Dictionary<Guid, Extension.Model.Snippet> snippetDictionary, string snippetReferencePrefix)
            : base(target, settings)
        {
            // Data validation
            Ensure.That(() => contextName).IsNotNullOrWhiteSpace();
            Ensure.That(target is StreamWriter).IsTrue();
            Ensure.That(() => sectionTitleBase).IsGte(0);
            Ensure.That(() => snippetDictionary).IsNotNull();
            Ensure.That(() => snippetReferencePrefix).IsNotNull();

            // Initialize
            this.ContextName = contextName;
            this.pageBreak = new List<PageBreakInfo>();
            this.writer = target as StreamWriter;
            this.sectionTitleBase = sectionTitleBase;
            this.snippetDictionary = snippetDictionary;
            this.snippetReferencePrefix = snippetReferencePrefix;
        }
Пример #17
0
 public CustomHtmlFormatter(System.IO.TextWriter target, CommonMarkSettings settings, HtmlFile file)
     : base(target, settings)
 {
     this.file = file;
 }
		public UnderlineLinksHtmlFormatter(System.IO.TextWriter target, CommonMarkSettings settings)
			: base(target, settings)
		{
		}
Пример #19
0
 static TopicParser()
 {
     settings = CommonMarkSettings.Default.Clone();
     settings.AdditionalFeatures = CommonMarkAdditionalFeatures.All & ~CommonMarkAdditionalFeatures.StrikethroughTilde;
 }
 static void Formatter(Block block, TextWriter writer, CommonMarkSettings settings)
 => new MarkdownFormatter(writer).WriteBlock(block);
 public MarkdownHighlightingColorizer()
 {
     _commonMarkSettings = CommonMarkSettings.Default.Clone();
     _commonMarkSettings.TrackSourcePosition = true;
 }
Пример #22
0
        public static void ProcessStage2(Syntax.Block document, CommonMarkSettings settings = null)
        {
            if (document == null)
                throw new ArgumentNullException(nameof(document));

            if (document.Tag != Syntax.BlockTag.Document)
                throw new ArgumentException("The block element passed to this method must represent a top level document.", nameof(document));

            if (settings == null)
                settings = CommonMarkSettings.Default;

            try
            {
                BlockMethods.ProcessInlines(document, document.ReferenceMap, settings);
            }
            catch(CommonMarkException)
            {
                throw;
            }
            catch(Exception ex)
            {
                throw new CommonMarkException("An error occurred during inline parsing.", ex);
            }
        }
Пример #23
0
        /// <summary>
        /// Performs a preliminary stage of the conversion, optionally handling a prologue.
        /// </summary>
        /// <param name="reader">The reader that contains the source data.</param>
        /// <param name="settings">The object containing settings for the parsing process.</param>
        /// <returns>The first line following the prologue or <c>null</c>, and the prologue line count.</returns>
        public static Tuple<string, int> ProcessPrologue(TextReader reader, CommonMarkSettings settings = null)
        {
            if (reader == null)
                throw new ArgumentNullException(nameof(reader));

            if (settings == null)
                settings = CommonMarkSettings.Default;

            var handlePrologue = settings.HandlePrologue;
            var prologueHandler = settings.PrologueLineHandler;
            if (prologueHandler != null)
                handlePrologue = true;

            string line = null;
            int lineNumber = 0;

            if (prologueHandler != null)
            {
                while (handlePrologue && (line = reader.ReadLine()) != null)
                {
                    handlePrologue = prologueHandler(ref line);
                    if (line != null)
                        ++lineNumber;
                }
            }

            return new Tuple<string, int>(line, lineNumber);
        }
Пример #24
0
 static Markdown()
 {
     CommonMarkSettings = CommonMarkSettings.Default.Clone();
     CommonMarkSettings.TrackSourcePosition = true;
 }
Пример #25
0
        public static Syntax.Block ProcessStage1(TextReader source, CommonMarkSettings settings = null, Tuple<string, int> prologue = null)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            if (settings == null)
                settings = CommonMarkSettings.Default;

            var cur = Syntax.Block.CreateDocument();
            var doc = cur;
            var line = new LineInfo(settings.TrackSourcePosition);
            if (prologue != null && settings.IncludePrologueInLineCount)
                line.LineNumber = prologue.Item2 + 1;

            try
            {
                var reader = new TabTextReader(source, prologue?.Item1);
                reader.ReadLine(line);
                while (line.Line != null)
                {
                    BlockMethods.IncorporateLine(line, ref cur, settings);
                    reader.ReadLine(line);
                }
            }
            catch(IOException)
            {
                throw;
            }
            catch(CommonMarkException)
            {
                throw;
            }
            catch(Exception ex)
            {
                throw new CommonMarkException("An error occurred while parsing line " + line.ToString(), cur, ex);
            }

            try
            {
                do
                {
                    BlockMethods.Finalize(cur, line, settings);
                    cur = cur.Parent;
                } while (cur != null);
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new CommonMarkException("An error occurred while finalizing open containers.", cur, ex);
            }

            return doc;
        }
Пример #26
0
        /// <summary>
        /// Converts the given source data and returns the result as a string.
        /// </summary>
        /// <param name="source">The source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
        /// <returns>The converted data.</returns>
        public static string Convert(string source, CommonMarkSettings settings = null)
        {
            if (source == null)
                return null;

            using (var reader = new System.IO.StringReader(source))
            using (var writer = new System.IO.StringWriter(System.Globalization.CultureInfo.CurrentCulture))
            {
                Convert(reader, writer, settings);

                return writer.ToString();
            }
        }
Пример #27
0
        /// <summary>
        /// Converts the given source data and writes the result directly to the target.
        /// </summary>
        /// <param name="source">The reader that contains the source data.</param>
        /// <param name="target">The target text writer where the result will be written to.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> or <paramref name="target"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing or formatting.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static void Convert(TextReader source, TextWriter target, CommonMarkSettings settings = null)
        {
            if (settings == null)
                settings = CommonMarkSettings.Default;

            var prologue = ProcessPrologue(source, settings);
            var document = ProcessStage1(source, settings, prologue);
            ProcessStage2(document, settings);
            ProcessStage3(document, target, settings);
        }
Пример #28
0
        /// <summary>
        /// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
        /// convert the document to HTML using the built-in converter.
        /// </summary>
        /// <param name="source">The source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static Syntax.Block Parse(string source, CommonMarkSettings settings = null)
        {
            if (source == null)
                return null;

            using (var reader = new System.IO.StringReader(source))
                return Parse(reader, settings);
        }
Пример #29
0
        static int Main(string[] args)
        {
            var sources             = new List <System.IO.TextReader>();
            var benchmark           = false;
            var benchmarkIterations = 20;
            var target       = Console.Out;
            var runPerlTests = false;
            var settings     = new CommonMarkSettings();

            try
            {
                for (var i = 0; i < args.Length; i++)
                {
                    if (string.Equals(args[i], "--version", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine("CommonMark.NET {0}", CommonMarkConverter.Version);
                        Console.WriteLine(" - (c) 2014 Kārlis Gaņģis");
                        return(0);
                    }
                    else if ((string.Equals(args[i], "--help", StringComparison.OrdinalIgnoreCase)) ||
                             (string.Equals(args[i], "-h", StringComparison.OrdinalIgnoreCase)))
                    {
                        PrintUsage();
                        return(0);
                    }
                    else if (string.Equals(args[i], "--perltest", StringComparison.OrdinalIgnoreCase))
                    {
                        runPerlTests = true;
                    }
                    else if (string.Equals(args[i], "--ast", StringComparison.OrdinalIgnoreCase))
                    {
                        settings.OutputFormat = OutputFormat.SyntaxTree;
                    }
                    else if (string.Equals(args[i], "--sourcepos", StringComparison.OrdinalIgnoreCase))
                    {
                        settings.TrackSourcePosition = true;
                    }
                    else if (string.Equals(args[i], "--bench", StringComparison.OrdinalIgnoreCase))
                    {
                        benchmark = true;
                        if (i != args.Length - 1)
                        {
                            if (!int.TryParse(args[i + 1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out benchmarkIterations))
                            {
                                benchmarkIterations = 20;
                            }
                            else
                            {
                                i++;
                            }
                        }
                    }
                    else if (string.Equals(args[i], "--out", StringComparison.OrdinalIgnoreCase))
                    {
                        if (i == args.Length - 1 || args[i + 1].StartsWith("-"))
                        {
                            PrintUsage();
                            return(1);
                        }

                        i++;
                        target = new System.IO.StreamWriter(args[i]);
                    }
                    else if (args[i].StartsWith("-"))
                    {
                        PrintUsage(args[i]);
                        return(1);
                    }
                    else
                    {
                        // treat as file argument
                        sources.Add(new System.IO.StreamReader(args[i]));
                    }
                }

                if (sources.Count == 0)
                {
                    if (runPerlTests)
                    {
                        Console.InputEncoding  = Encoding.UTF8;
                        Console.OutputEncoding = Encoding.UTF8;

                        // runtests.pl writes directly to STDIN but will not send Ctrl+C and also
                        // will get confused by the additional information written to STDOUT
                        var sb = new StringBuilder();
                        while (Console.In.Peek() != -1)
                        {
                            sb.AppendLine(Console.In.ReadLine());
                        }

                        sources.Add(new System.IO.StringReader(sb.ToString()));
                    }
                    else if (!Console.IsInputRedirected)
                    {
                        Console.InputEncoding  = Encoding.Unicode;
                        Console.OutputEncoding = Encoding.Unicode;

                        Console.WriteLine("Enter the source. Press Enter after the last line and" + Environment.NewLine + "then press Ctrl+C to run parser.");
                        Console.WriteLine();

                        Console.CancelKeyPress += (s, a) =>
                        {
                            a.Cancel = true;
                            Console.WriteLine("Output:");
                            Console.WriteLine();
                        };

                        sources.Add(Console.In);
                    }
                    else
                    {
                        Console.InputEncoding  = Encoding.UTF8;
                        Console.OutputEncoding = Encoding.UTF8;

                        sources.Add(Console.In);
                    }
                }

                if (benchmark)
                {
                    Console.WriteLine("Running the benchmark...");
                    foreach (var source in sources)
                    {
                        // by using a in-memory source, the disparity of results is reduced.
                        var data = source.ReadToEnd();

                        // in-memory source that gets reused further reduces the disparity.
                        var builder = new StringBuilder(2 * 1024 * 1024);

                        var  sw   = new System.Diagnostics.Stopwatch();
                        var  mem  = GC.GetTotalMemory(true);
                        long mem2 = 0;

                        for (var x = -1 - benchmarkIterations / 10; x < benchmarkIterations; x++)
                        {
                            if (x == 0)
                            {
                                sw.Start();
                            }

                            builder.Length = 0;
                            using (var reader = new System.IO.StringReader(data))
                                using (var twriter = new System.IO.StringWriter(builder))
                                    CommonMarkConverter.Convert(reader, twriter, settings);

                            if (mem2 == 0)
                            {
                                mem2 = GC.GetTotalMemory(false);
                            }

                            GC.Collect();
                        }

                        sw.Stop();
                        target.WriteLine("Time spent: {0:0.#}ms    Approximate memory usage: {1:0.000}MB",
                                         (decimal)sw.ElapsedMilliseconds / benchmarkIterations,
                                         (mem2 - mem) / 1024M / 1024M);
                    }
                }
                else
                {
                    foreach (var source in sources)
                    {
                        CommonMarkConverter.Convert(source, target, settings);
                    }
                }

                if (System.Diagnostics.Debugger.IsAttached)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return(-1);
            }
            finally
            {
                foreach (var s in sources)
                {
                    if (s != Console.In)
                    {
                        s.Close();
                    }
                }

                if (target != Console.Out)
                {
                    target.Close();
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Parses the given source data and returns the document syntax tree. Use <see cref="ProcessStage3"/> to
        /// convert the document to HTML using the built-in converter.
        /// </summary>
        /// <param name="source">The reader that contains the source data.</param>
        /// <param name="settings">The object containing settings for the parsing and formatting process.</param>
        /// <exception cref="ArgumentNullException">when <paramref name="source"/> is <c>null</c></exception>
        /// <exception cref="CommonMarkException">when errors occur during parsing.</exception>
        /// <exception cref="IOException">when error occur while reading or writing the data.</exception>
        public static Syntax.Block Parse(TextReader source, CommonMarkSettings settings = null)
        {
            if (settings == null)
                settings = CommonMarkSettings.Default;

            var prologue = ProcessPrologue(source, settings);
            var document = ProcessStage1(source, settings, prologue);
            ProcessStage2(document, settings);
            return document;
        }
Пример #31
0
        public static void ProcessStage3(Syntax.Block document, TextWriter target, CommonMarkSettings settings = null)
        {
            if (document == null)
                throw new ArgumentNullException(nameof(document));

            if (target == null)
                throw new ArgumentNullException(nameof(target));

            if (document.Tag != Syntax.BlockTag.Document)
                throw new ArgumentException("The block element passed to this method must represent a top level document.", nameof(document));

            if (settings == null)
                settings = CommonMarkSettings.Default;

            try
            {
                switch (settings.OutputFormat)
                {
                    case OutputFormat.Html:
                        HtmlFormatterSlim.BlocksToHtml(target, document, settings);
                        break;
                    case OutputFormat.SyntaxTree:
                        Printer.PrintBlocks(target, document, settings);
                        break;
                    case OutputFormat.CustomDelegate:
                        if (settings.OutputDelegate == null)
                            throw new CommonMarkException("If `settings.OutputFormat` is set to `CustomDelegate`, the `settings.OutputDelegate` property must be populated.");
                        settings.OutputDelegate(document, target, settings);
                        break;
                    default:
                        throw new CommonMarkException("Unsupported value '" + settings.OutputFormat + "' in `settings.OutputFormat`.");
                }
            }
            catch (CommonMarkException)
            {
                throw;
            }
            catch(IOException)
            {
                throw;
            }
            catch(Exception ex)
            {
                throw new CommonMarkException("An error occurred during formatting of the document.", ex);
            }
        }