public static MarkdownDeep.Markdown CreateRenderer()
        {
            var result = new MarkdownDeep.Markdown {SafeMode = true, ExtraMode = true};
            result.FormatCodeBlock += FormatCodeBlock;

            return result;
        }
Exemple #2
0
        public static string ResolveMarkdown(this string content, IDocsOutput output, string currentSlug)
        {
            // http://www.toptensoftware.com/markdowndeep/api
            var md = new Markdown
                        {
                            AutoHeadingIDs = true,
                            ExtraMode = true,
                            NoFollowLinks = false,
                            SafeMode = false,
                            HtmlClassTitledImages = "figure",
                            UrlRootLocation = output.RootUrl,
                        };

            if (!string.IsNullOrWhiteSpace(output.RootUrl))
            {
                if (!string.IsNullOrWhiteSpace(currentSlug) && !currentSlug.Equals("index"))
                    md.UrlBaseLocation = output.RootUrl + "/" + currentSlug.Replace('\\', '/');
                else
                    md.UrlBaseLocation = output.RootUrl;
            }

            ////if (!string.IsNullOrWhiteSpace(output.ImagesPath))
            //    md.QualifyUrl = delegate(string image) { return output.ImagesPath + "/" + image; };

            md.PrepareImage = (tag, titledImage) => PrepareImage(output.ImagesPath, tag);

            return md.Transform(content);
        }
Exemple #3
0
 public static string Markdown(string text)
 {
     if (text == null)
         return "";
     var md = new Markdown();
     return md.Transform(text.Trim());
 }
 private Negotiator GetDocument(IDocumentFolder documentFolder, string path)
 {
     var markdown = documentFolder.ReadAllText(path);
     var converter = new Markdown();
     var html = converter.Transform(markdown);
     return View["Index", new { Title = path, Content = html }];
 }
Exemple #5
0
        public static string FormatCodePrettyPrint(Markdown m, string code)
        {
            var match = rxExtractLanguage.Match(code);
            string language = null;

            if (match.Success)
            {
                // Save the language
                var g=(Group)match.Groups[2];
                language = g.ToString();

                // Remove the first line
                code = code.Substring(match.Groups[1].Length);
            }

            if (language == null)
            {
                var d = m.GetLinkDefinition("default_syntax");
                if (d!=null)
                    language = d.title;
            }
            if (language == "C#")
                language = "csharp";
            if (language == "C++")
                language = "cpp";

            if (string.IsNullOrEmpty(language))
                return string.Format("<pre><code>{0}</code></pre>\n", code);
            else
                return string.Format("<pre class=\"prettyprint lang-{0}\"><code>{1}</code></pre>\n", language.ToLowerInvariant(), code);
        }
        public static IHtmlString CompiledContent(this IDynamicContent contentItem, bool trustContent = false)
        {
            if (contentItem == null) return NonEncodedHtmlString.Empty;

            switch (contentItem.ContentType)
            {
                case DynamicContentType.Markdown:
                    var md = new Markdown
                    {
                        AutoHeadingIDs = true,
                        ExtraMode = true,
                        NoFollowLinks = !trustContent,
                        SafeMode = false,
                        NewWindowForExternalLinks = true,
                    };

                    var contents = contentItem.Content;
                    // TODO contents = CodeBlockFinder.Replace(contents, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value));
                    contents = md.Transform(contents);
                    return new NonEncodedHtmlString(contents);
                case DynamicContentType.Html:
                    return trustContent ? new NonEncodedHtmlString(contentItem.Content) : NonEncodedHtmlString.Empty;
            }
            return NonEncodedHtmlString.Empty;
        }
        public static MvcHtmlString CompiledContent(this IDynamicContent contentItem, bool trustContent)
        {
            if (contentItem == null) return MvcHtmlString.Empty;

            switch (contentItem.ContentType)
            {
                case DynamicContentType.Markdown:
                    var md = new Markdown
                    {
                        AutoHeadingIDs = true,
                        ExtraMode = true,
                        NoFollowLinks = !trustContent,
                        SafeMode = false,
                        NewWindowForExternalLinks = true,
                    };

                    var contents = contentItem.Body;
                    contents = CodeBlockFinder.Replace(contents, match => GenerateCodeBlock(match.Groups[1].Value.Trim(), match.Groups[2].Value));

                    try
                    {
                        contents = md.Transform(contents);
                    }
                    catch (Exception)
                    {
                        contents = string.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(contents));
                    }

                    return MvcHtmlString.Create(contents);
                case DynamicContentType.Html:
                    return trustContent ? MvcHtmlString.Create(contentItem.Body) : MvcHtmlString.Empty;
            }
            return MvcHtmlString.Empty;
        }
Exemple #8
0
        public ActionResult Show(string page)
        {
            if (page == "" || page == null)
                page = "README";
            string path = string.Concat(HttpContext.Request.PhysicalApplicationPath, "\\Docs\\", page, ".md");
            string contents;

            try
            {
                using (StreamReader sr = new StreamReader(path))
                {
                    Markdown md = new Markdown();
                    contents = md.Transform(sr.ReadToEnd());

                }

                ViewBag.ConvertedMarkdown = contents;
                return View();
            }
            catch (Exception ex)
            {
                this.Response.StatusCode = 404;
                ViewBag.ConvertedMarkdown = "File not found.";
                return View();
            }
        }
Exemple #9
0
        static void Main(string[] args)
        {
            Markdown m = new Markdown();
            m.SafeMode = false;
            m.ExtraMode = true;
            m.AutoHeadingIDs = true;
            //			m.SectionHeader = "<div class=\"header\">{0}</div>\n";
            //			m.SectionHeadingSuffix = "<div class=\"heading\">{0}</div>\n";
            //			m.SectionFooter = "<div class=\"footer\">{0}</div>\n\n";
            //			m.SectionHeader = "\n<div class=\"section_links\"><a href=\"/edit?section={0}\">Edit</a></div>\n";
            //			m.HtmlClassTitledImages = "figure";
            //			m.DocumentRoot = "C:\\users\\bradr\\desktop";
            //			m.DocumentLocation = "C:\\users\\bradr\\desktop\\100D5000";
            //			m.MaxImageWidth = 500;

            string markdown=FileContents("input.txt");
            string str = m.Transform(markdown);
            Console.Write(str);

            var sections = MarkdownDeep.Markdown.SplitSections(markdown);
            for (int i = 0; i < sections.Count; i++)
            {
                Console.WriteLine("---- Section {0} ----", i);
                Console.Write(sections[i]);
                Console.WriteLine("\n");
            }
            Console.WriteLine("------------------");
        }
 public StaticContentServiceImpl(string baseLocalPath, Markdown markdownRender, ShopifyLiquidThemeEngine liquidEngine, ICacheManager<object> cacheManager)
 {
     _baseLocalPath = baseLocalPath;
     _markdownRender = markdownRender;
     _liquidEngine = liquidEngine;
     _fileSystemWatcher = MonitorContentFileSystemChanges();
     _cacheManager = cacheManager;
 }
Exemple #11
0
 public MarkdownProcessor()
 {
     _processor = new Markdown
     {
         ExtraMode = true,
         NewWindowForExternalLinks = true
     };
 }
Exemple #12
0
 public PostController(IRepository<Post> postRepo)
 {
     Posts = postRepo;
     Markdown = new Markdown()
                    {
                        ExtraMode = true
                    };
 }
Exemple #13
0
        public DALMunicipiosRepository(string connectionString)
        {
            objMarkDown = new Markdown();
            objMarkDown.ExtraMode = true;
            objMarkDown.SafeMode = true;

            _connectionString = connectionString;
        }
Exemple #14
0
        /// <summary>
        /// Converts the markdown to HTML.
        /// </summary>
        /// <param name="toConvert">The markdown string to convert.</param>
        /// <param name="destinationDocumentPath">The document path (without the document filename).</param>
        /// <param name="siteRoot">The site root.</param>
        /// <param name="sourceDocumentFilename">the filename of the source markdown file</param>
        /// <param name="createdAnchorCollector">The created anchor collector, for ToC sublinks for H2 headers.</param>
        /// <param name="convertLocalLinks">if set to <c>true</c>, convert local links to md files to target files.</param>
        /// <param name="navigationContext">The navigation context.</param>
        /// <returns></returns>
        public static string ConvertMarkdownToHtml(string toConvert, string destinationDocumentPath, string siteRoot, string sourceDocumentFilename,
                                                   List <Heading> createdAnchorCollector, bool convertLocalLinks, NavigationContext navigationContext)
        {
            var localLinkProcessor = new Func <string, string>(s =>
            {
                var result = s;

                if (!string.IsNullOrWhiteSpace(result))
                {
                    switch (navigationContext.PathSpecification)
                    {
                    case PathSpecification.Full:
                        break;

                    case PathSpecification.Relative:
                        break;

                    case PathSpecification.RelativeAsFolder:
                        // Step 1: we need to move up 1 additional folder (get out of current subfolder)
                        var relativeAsFolderIndex = result.StartsWith("./") ? 2 : 0;
                        result = result.Insert(relativeAsFolderIndex, "../");

                        // Step 2: we need an additional layer to go into (filename is now a folder)
                        result = ResolveTargetURL(result, false, navigationContext);

                        // Step 3: get the final url
                        result = result.GetFinalTargetUrl(navigationContext);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(navigationContext.PathSpecification), navigationContext.PathSpecification, null);
                    }
                }

                return(result);
            });

            var parser = new MarkdownDeep.Markdown
            {
                ExtraMode                   = true,
                GitHubCodeBlocks            = true,
                AutoHeadingIDs              = true,
                NewWindowForExternalLinks   = true,
                DocNetMode                  = true,
                ConvertLocalLinks           = convertLocalLinks,
                LocalLinkProcessor          = localLinkProcessor,
                DestinationDocumentLocation = destinationDocumentPath,
                DocumentRoot                = siteRoot,
                SourceDocumentFilename      = sourceDocumentFilename,
                HtmlClassTitledImages       = "figure",
            };

            var toReturn = parser.Transform(toConvert);

            createdAnchorCollector.AddRange(parser.Headings.ConvertToHierarchy());

            return(toReturn);
        }
		public API_MarkdownSharp(string text)
		{
			AfterTransform  = new List<Action>();
			Text 			= text;	
			Markdown 		= new Markdown()
				{
				 	SafeMode = true
				};
		}
Exemple #16
0
        /// <summary>
        /// Transforms a string of Markdown into HTML.
        /// </summary>
        /// <param name="text">The Markdown that should be transformed.</param>
        /// <returns>The HTML representation of the supplied Markdown.</returns>
        public static IHtmlString Markdown(string text)
        {
            // Transform the supplied text (Markdown) into HTML.
            var markdownTransformer = new Markdown();
            var html = markdownTransformer.Transform(text);

            // Wrap the html in an MvcHtmlString otherwise it'll be HtmlEncoded and displayed to the user as HTML :(
            return html.ToHtmlString();
        }
		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			_temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp
			File.WriteAllText(_temp.Path, md.Transform(contents));
			_browser.Url = new Uri(_temp.Path);
		}
		public void Simple()
		{
			var markdown = new Markdown
			{
				NewWindowForExternalLinks = true
			};
			Console.WriteLine(markdown.Transform("##Header"));
			Console.WriteLine(markdown.Transform("`<T>`"));
			Console.WriteLine(markdown.Transform("[a](http://e1.ru)"));
		}
		private void ShowReleaseNotesDialog_Load(object sender, EventArgs e)
		{
			string contents = File.ReadAllText(_path);

			var md = new Markdown();
			// Disposed of during dialog Dispose()
			_temp = TempFile.WithExtension("htm");
			File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents)));
			_browser.Url = new Uri(_temp.Path);
		}
	    private static Markdown GetMarkdownTransformer()
	    {
	        var md = new Markdown();
	        md.ExtraMode = true;
	        md.SafeMode = true;
	        md.NoFollowLinks = true;
	        md.NewWindowForExternalLinks = true;
	        md.MarkdownInHtml = false;
	        return md;
	    }
Exemple #21
0
 public static string Markdown(this string txt)
 {
     if (string.IsNullOrEmpty(txt)) return string.Empty;
     // spaces in urls will not work with MarkdownDeep
     txt = Regex.Replace(txt, @"\(http(.*)\)", match => match.ToString().Replace(" ", "%20"));
     // single linebreaks become double linebreaks to conform LeTour markdown
     var md = new Markdown();
     txt = md.Transform(txt);
     txt = Regex.Replace(txt, @"(?<!(</p>))\n(?!\n)", match => "<br/>");
     return txt;
 }
Exemple #22
0
        public void TransformMarkdown()
        {
            var markdownEngine = new Markdown
            {
                ExtraMode = true,
                AutoHeadingIDs = true,
                CodeBlockLanguageAttr = " data-language=\"{0}\""
            };

            this.Body = markdownEngine.Transform(this.Body);
        }
 public DocumentationViewer()
 {
     InitializeComponent();
     _markdown = new Markdown();
     _markdown.ExtraMode = true;
     var uri = new Uri("/ECalc.Docs;component/Documentation/template.html", UriKind.Relative);
     using (StreamReader sr = new StreamReader(Application.GetResourceStream(uri).Stream))
     {
         _template = sr.ReadToEnd();
     }
 }
        public void Render(Document input, Document output)
        {
            output.Extension = ".html";
            var mark = new Markdown();

            //set preferences of your markdown
            mark.SafeMode = true;
            mark.ExtraMode = true;
            
            string mdtext = input.Text;
            output.Text = mark.Transform(mdtext);
        }
Exemple #25
0
 public CommentProcessor(
     [Named("Email")] string email, [Named("SiteName")] string siteName,
     [Named("BaseUrl")] string baseUrl, string apiKey,
     [Named("Safe")] Markdown transformer, ISession session)
 {
     this.email = email;
     this.siteName = siteName;
     this.restUrl = String.Format("http://{0}.rest.akismet.com/1.1/comment-check", apiKey);
     this.baseUrl = baseUrl;
     this.transformer = transformer;
     this.session = session;
 }
Exemple #26
0
        public KnowledgeBase()
        {
            string code         = Helpers.GlobalHelper.RequestParam("code");
            string appDataPath  = System.Web.HttpContext.Current.Server.MapPath("~/assets");
            string readFilePath = "";
            string input        = "Something went wrong";

            if (code == "pptpwindows")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "windows.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "pptpandroid")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "android.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "pptpubuntu")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "ubuntu.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnubuntu")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "ubuntu.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnwindows")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "windows.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnandroid")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "android.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }

            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = false;


            _output = md.Transform(input);
        }
        public override void Render(Context context, StreamReader reader, StreamWriter writer)
        {
            var mark = new Markdown();

            //set preferences of your markdown
            mark.SafeMode = true;
            mark.ExtraMode = true;
            
            string mdtext = reader.ReadToEnd();
            string htmlmd = mark.Transform(mdtext);

            writer.Write(htmlmd);            
        }
Exemple #28
0
        public static string FormatMessage(String originalMessage, bool processContent = true)
        {
            //Test changes to this code against this markdown thread content:
            //https://voat.co/v/test/comments/53891

            if (processContent && !String.IsNullOrEmpty(originalMessage))
            {
                originalMessage = ContentProcessor.Instance.Process(originalMessage, ProcessingStage.Outbound, null);
            }

            var newWindow = false;

            if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                newWindow = UserHelper.LinksInNewWindow(System.Web.HttpContext.Current.User.Identity.Name);
            }

            var m = new Markdown
            {
                PrepareLink = new Func<HtmlTag, bool>(x =>
                {
                    //Remove [Title](javascript:alter('hello')) exploit
                    string href = x.attributes["href"];
                    if (!String.IsNullOrEmpty(href))
                    {
                        //I think it needs the javascript: prefix to work at all but there might be more holes as this is just a simple check.
                        if (href.ToLower().Trim().StartsWith("javascript:"))
                        {
                            x.attributes["href"] = "#";
                            //add it to the output for verification?
                            x.attributes.Add("data-ScriptStrip", String.Format("/* script detected: {0} */", href));
                        }
                    }
                    return true;
                }),
                ExtraMode = true,
                SafeMode = true,
                NewWindowForExternalLinks = newWindow,
                NewWindowForLocalLinks = newWindow
            };

            try
            {
                return m.Transform(originalMessage);
            }
            catch (Exception ex)
            {
                return "Content contains unsafe or unknown tags.";
            }
        }
Exemple #29
0
        public KnowledgeBase(string code, string appDataPath)
        {
            string readFilePath = "";
            string input        = "Something went wrong";

            if (code == "pptpwindows")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "windows.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "pptpandroid")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "android.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "pptpubuntu")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "pptp", "ubuntu.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnubuntu")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "ubuntu.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnwindows")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "windows.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }
            else if (code == "openvpnandroid")
            {
                readFilePath = System.IO.Path.Combine(appDataPath,
                                                      "knowledgebase", "openvpn", "android.md");
                input = System.IO.File.ReadAllText(readFilePath);
            }

            var md = new MarkdownDeep.Markdown();

            md.ExtraMode = true;
            md.SafeMode  = false;


            _output = md.Transform(input);
        }
        public static MvcHtmlString CompiledMarkdownContent(this string str, bool trustContent = false)
        {
            if (str == null) return MvcHtmlString.Empty;

            var md = new Markdown
                     	{
                     		AutoHeadingIDs = true,
                     		ExtraMode = true,
                     		NoFollowLinks = !trustContent,
                     		SafeMode = false,
                     		NewWindowForExternalLinks = true,
                     	};

            var contents = md.Transform(str);
            return MvcHtmlString.Create(contents);
        }
        private static string FormatMarkdown(string content)
        {
            var md = new Markdown();
            string result;

            try
            {
                result = md.Transform(content);
            }
            catch (Exception)
            {
                result = string.Format("<pre>{0}</pre>", HttpUtility.HtmlEncode(content));
            }

            return result;
        }
Exemple #32
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en");

            var layout = File.ReadAllText("../layout.html");
            layout = layout.Replace("{{description}}", "RedBeanPHP-inspired data access layer for .NET");
            layout = layout.Replace("{{updated_on}}", DateTime.Now.ToString("MMM d, yyyy"));

            var headerIdList = new List<string>();
            var body = new Markdown().Transform(PreprocessBody());
            body = AddHeaderAnchors(body, headerIdList);

            layout = layout.Replace("{{body}}", body);
            ValidateHeaderAnchors(headerIdList, layout);
            File.WriteAllText("../www/index.html", layout);
        }
Exemple #33
0
        public string DoTransformation()
        {
            if (File.Exists(_filePath))
            {
                string text = File.ReadAllText(_filePath);

                var clean = Regex.Replace(text, MarkdownLogic.RegEx, new MatchEvaluator(match => LinkEvaluator(match, PrefixLinks)),
                    RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);

                Markdown md = new Markdown();
                string transform = md.Transform(clean);
                return transform;
            }

            return "<h2>Not Found</h2>";
        }
Exemple #34
0
    static void TestMarkdownDeep()
    {
        var result = new Result {
            Name = "MarkdownDeep"
        };


        var stopwatch = Stopwatch.StartNew();
        var warmup    = new MarkdownDeep.Markdown
        {
            ExtraMode      = true,
            MarkdownInHtml = true,
            SafeMode       = false,
        };

        stopwatch.Stop();
        result.WarmUp = stopwatch.ElapsedMilliseconds;

        warmup.Transform(testTexts.First());

        stopwatch = Stopwatch.StartNew();
        var markdownify = new MarkdownDeep.Markdown
        {
            ExtraMode      = true,
            MarkdownInHtml = true,
            SafeMode       = false,
        };

        stopwatch.Stop();
        result.Construction = stopwatch.ElapsedMilliseconds;

        stopwatch = Stopwatch.StartNew();
        markdownify.Transform(testTexts.First());
        stopwatch.Stop();
        result.FirstRun = stopwatch.ElapsedMilliseconds;

        stopwatch = Stopwatch.StartNew();
        foreach (var text in testTexts)
        {
            markdownify.Transform(text);
        }
        stopwatch.Stop();
        result.BulkRun = stopwatch.ElapsedMilliseconds;
        result.Average = GetAverage(stopwatch.ElapsedMilliseconds);
        results.Add(result);
    }
Exemple #35
0
        public static string FormatCodePrettyPrint(MarkdownDeep.Markdown m, string code)
        {
            code = code.TrimEnd();

            // Try to extract the language from the first line
            var    match    = rxExtractLanguage.Match(code);
            string language = null;

            if (match.Success)
            {
                // Save the language
                var g = match.Groups[2];
                language = g.ToString();

                // Remove the first line
                code = code.Substring(match.Groups[1].Length);
            }

            // If not specified, look for a link definition called "default_syntax" and
            // grab the language from its title
            if (language == null)
            {
                var d = m.GetLinkDefinition("default_syntax");
                if (d != null)
                {
                    language = d.title;
                }
            }

            // Common replacements
            if (language == "C#")
            {
                language = "csharp";
            }
            if (language == "C++")
            {
                language = "cpp";
            }

            // Wrap code in pre/code tags and add PrettyPrint attributes if necessary
            if (string.IsNullOrEmpty(language))
            {
                return($"<pre><code>{code}</code></pre>\n");
            }
            return($"<textarea class='code code-sample' data-lang='{language.ToLowerInvariant()}'>{code}</textarea>\n");
        }
        public ActionResult Edit(GameViewModel gamevm)
        {
            Game game = gamevm.Game;

            if (ModelState.IsValid)
            {
                Markdown md = new MarkdownDeep.Markdown();
                game.Report = md.Transform(game.ReportMarkdown);
                gamedao.Update(game);
                return(RedirectToAction("Details", "Game", new { id = game.Id }));
            }
            else
            {
                Game g = gamedao.GetById(game.Id);
                gamevm.Stats         = g.Stats.ToList();
                gamevm.PlayerStats   = g.PlayerStats.ToList();
                ViewBag.PeriodsItems = listItems.UnsetPeriods(g.Stats.ToList <GameStats>());
                ViewBag.PlayersItems = listItems.UnsetPlayers(g.PlayerStats.ToList <PlayerStats>());
                ViewBag.PlaceItems   = listItems.Places();
                return(View(gamevm));
            }
        }
Exemple #37
0
        /// <summary>
        /// Converts the markdown to HTML.
        /// </summary>
        /// <param name="toConvert">The markdown string to convert.</param>
        /// <param name="destinationDocumentPath">The document path (without the document filename).</param>
        /// <param name="siteRoot">The site root.</param>
        /// <param name="sourceDocumentFilename">the filename of the source markdown file</param>
        /// <param name="createdAnchorCollector">The created anchor collector, for ToC sublinks for H2 headers.</param>
        /// <param name="convertLocalLinks">if set to <c>true</c>, convert local links to md files to target files.</param>
        /// <returns></returns>
        public static string ConvertMarkdownToHtml(string toConvert, string destinationDocumentPath, string siteRoot, string sourceDocumentFilename,
                                                   List <Heading> createdAnchorCollector, bool convertLocalLinks)
        {
            var parser = new MarkdownDeep.Markdown
            {
                ExtraMode                   = true,
                GitHubCodeBlocks            = true,
                AutoHeadingIDs              = true,
                NewWindowForExternalLinks   = true,
                DocNetMode                  = true,
                ConvertLocalLinks           = convertLocalLinks,
                DestinationDocumentLocation = destinationDocumentPath,
                DocumentRoot                = siteRoot,
                SourceDocumentFilename      = sourceDocumentFilename,
                HtmlClassTitledImages       = "figure",
            };

            var toReturn = parser.Transform(toConvert);

            createdAnchorCollector.AddRange(parser.Headings.ConvertToHierarchy());

            return(toReturn);
        }
Exemple #38
0
        internal void RenderLink(Markdown m, StringBuilder b, string link_text, List <string> specialAttributes)
        {
            if (this.Url.StartsWith("mailto:"))
            {
                b.Append("<a href=\"");
                Utils.HtmlRandomize(b, this.Url);
                b.Append('\"');
                if (!String.IsNullOrEmpty(this.Title))
                {
                    b.Append(" title=\"");
                    Utils.SmartHtmlEncodeAmpsAndAngles(b, this.Title);
                    b.Append('\"');
                }
                b.Append('>');
                Utils.HtmlRandomize(b, link_text);
                b.Append("</a>");
            }
            else
            {
                HtmlTag tag = new HtmlTag("a");

                var url = this.Url;

                if (m.DocNetMode && m.ConvertLocalLinks)
                {
                    // A few requirements before we can convert local links:
                    //   1. Link contains .md
                    //   2. Link is relative
                    //   3. Link is included in the index
                    var index = url.LastIndexOf(".md", StringComparison.OrdinalIgnoreCase);
                    if (index >= 0)
                    {
                        var linkProcessor = m.LocalLinkProcessor;
                        if (linkProcessor != null)
                        {
                            url = linkProcessor(url);
                        }
                        else
                        {
                            Uri uri;
                            if (Uri.TryCreate(url, UriKind.Relative, out uri))
                            {
                                url = String.Concat(url.Substring(0, index), ".htm", url.Substring(index + ".md".Length));
                            }
                        }
                    }
                }

                // encode url
                StringBuilder sb = m.GetStringBuilder();
                Utils.SmartHtmlEncodeAmpsAndAngles(sb, url);
                tag.attributes["href"] = sb.ToString();

                // encode title
                if (!String.IsNullOrEmpty(this.Title))
                {
                    sb.Length = 0;
                    Utils.SmartHtmlEncodeAmpsAndAngles(sb, this.Title);
                    tag.attributes["title"] = sb.ToString();
                }

                if (specialAttributes.Any())
                {
                    LinkDefinition.HandleSpecialAttributes(specialAttributes, sb, tag);
                }

                // Do user processing
                m.OnPrepareLink(tag);

                // Render the opening tag
                tag.RenderOpening(b);

                b.Append(link_text);                      // Link text already escaped by SpanFormatter
                b.Append("</a>");
            }
        }
Exemple #39
0
        public void RenderPlain(Markdown m, StringBuilder b, Action <Block, Token, string> customProcess)
        {
            if (customProcess != null)
            {
                customProcess(this, null, null);
            }

            switch (blockType)
            {
            case BlockType.Blank:
                return;

            case BlockType.p:
            case BlockType.span:
                m.SpanFormatter.FormatPlain(b, buf, contentStart, contentLen, customProcess);
                b.Append(" ");
                break;

            case BlockType.h1:
            case BlockType.h2:
            case BlockType.h3:
            case BlockType.h4:
            case BlockType.h5:
            case BlockType.h6:
                m.SpanFormatter.FormatPlain(b, buf, contentStart, contentLen, customProcess);
                b.Append(" - ");
                break;


            case BlockType.ol_li:
            case BlockType.ul_li:
                b.Append("* ");
                m.SpanFormatter.FormatPlain(b, buf, contentStart, contentLen, customProcess);
                b.Append(" ");
                break;

            case BlockType.dd:
                if (children != null)
                {
                    b.Append("\n");
                    RenderChildrenPlain(m, b, customProcess);
                }
                else
                {
                    m.SpanFormatter.FormatPlain(b, buf, contentStart, contentLen, customProcess);
                }
                break;

            case BlockType.dt:
            {
                if (children == null)
                {
                    foreach (var l in Content.Split('\n'))
                    {
                        var str = l.Trim();
                        m.SpanFormatter.FormatPlain(b, str, 0, str.Length, customProcess);
                    }
                }
                else
                {
                    RenderChildrenPlain(m, b, customProcess);
                }
                break;
            }

            case BlockType.dl:
                RenderChildrenPlain(m, b, customProcess);
                return;

            case BlockType.codeblock:
                foreach (var line in children)
                {
                    b.Append(line.buf, line.contentStart, line.contentLen);
                    b.Append(" ");
                }
                return;

            case BlockType.quote:
                RenderChildrenPlain(m, b, customProcess);
                if (customProcess != null)
                {
                    customProcess(new Block(BlockType.quote_end), null, null);
                }
                return;

            case BlockType.li:
                RenderChildrenPlain(m, b, customProcess);
                if (customProcess != null)
                {
                    customProcess(new Block(BlockType.li_end), null, null);
                }
                return;

            case BlockType.ol:
                RenderChildrenPlain(m, b, customProcess);
                if (customProcess != null)
                {
                    customProcess(new Block(BlockType.ol_end), null, null);
                }
                return;

            case BlockType.ul:
                RenderChildrenPlain(m, b, customProcess);
                if (customProcess != null)
                {
                    customProcess(new Block(BlockType.ul_end), null, null);
                }
                return;

            case BlockType.HtmlTag:
                RenderChildrenPlain(m, b, customProcess);
                if (customProcess != null)
                {
                    customProcess(new Block(BlockType.HtmlTag_end), null, null);
                }
                return;
            }
        }
Exemple #40
0
 public void RenderImage(Markdown m, StringBuilder sb)
 {
     this.Definition.RenderImg(m, sb, this.LinkText, this.SpecialAttributes);
 }
Exemple #41
0
 // Constructor
 // A reference to the owning markdown object is passed incase
 // we need to check for formatting options
 public SpanFormatter(Markdown m)
 {
     m_Markdown = m;
 }
Exemple #42
0
        internal void Render(Markdown m, StringBuilder b)
        {
            switch (BlockType)
            {
            case BlockType.Blank:
                return;

            case BlockType.p:
                m.SpanFormatter.FormatParagraph(b, Buf, ContentStart, ContentLen);
                break;

            case BlockType.span:
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("\n");
                break;

            case BlockType.h1:
            case BlockType.h2:
            case BlockType.h3:
            case BlockType.h4:
            case BlockType.h5:
            case BlockType.h6:
                string id = string.Empty;
                bool   insertPermalink = false;
                if (m.ExtraMode && !m.SafeMode)
                {
                    b.Append("<" + BlockType.ToString());
                    id = ResolveHeaderID(m);
                    if (!String.IsNullOrEmpty(id))
                    {
                        b.Append(" id=\"");
                        b.Append(id);
                        b.Append("\">");
                        insertPermalink = true;
                    }
                    else
                    {
                        b.Append(">");
                    }
                }
                else
                {
                    b.Append("<" + BlockType.ToString() + ">");
                }
                if (m.DocNetMode && BlockType == BlockType.h2 && !string.IsNullOrWhiteSpace(id))
                {
                    // collect h2 id + text in collector
                    var h2ContentSb = new StringBuilder();
                    m.SpanFormatter.Format(h2ContentSb, Buf, ContentStart, ContentLen);
                    var h2ContentAsString = h2ContentSb.ToString();
                    b.Append(h2ContentAsString);
                    m.CreatedH2IdCollector.Add(new Tuple <string, string>(id, h2ContentAsString));
                }
                else
                {
                    m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                }
                if (insertPermalink)
                {
                    // append header permalink link
                    b.Append("<a class=\"headerlink\" href=\"#");
                    b.Append(id);
                    b.Append("\" title=\"Permalink to this headline\"><i class=\"fa fa-link\" aria-hidden=\"true\"></i></a>");
                }
                b.Append("</" + BlockType.ToString() + ">\n");
                break;

            case BlockType.hr:
                b.Append("<hr />\n");
                return;

            case BlockType.user_break:
                return;

            case BlockType.ol_li:
            case BlockType.ul_li:
                b.Append("<li>");
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("</li>\n");
                break;

            case BlockType.dd:
                b.Append("<dd>");
                if (Children != null)
                {
                    b.Append("\n");
                    RenderChildren(m, b);
                }
                else
                {
                    m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                }
                b.Append("</dd>\n");
                break;

            case BlockType.dt:
            {
                if (Children == null)
                {
                    foreach (var l in Content.Split('\n'))
                    {
                        b.Append("<dt>");
                        m.SpanFormatter.Format(b, l.Trim());
                        b.Append("</dt>\n");
                    }
                }
                else
                {
                    b.Append("<dt>\n");
                    RenderChildren(m, b);
                    b.Append("</dt>\n");
                }
                break;
            }

            case BlockType.dl:
                b.Append("<dl>\n");
                RenderChildren(m, b);
                b.Append("</dl>\n");
                return;

            case BlockType.html:
                b.Append(Buf, ContentStart, ContentLen);
                return;

            case BlockType.unsafe_html:
                m.HtmlEncode(b, Buf, ContentStart, ContentLen);
                return;

            case BlockType.codeblock:
                if (m.FormatCodeBlockFunc == null)
                {
                    var    dataArgument = this.Data as string ?? string.Empty;
                    string tagSuffix    = "</code></pre>\n\n";

                    if (m.GitHubCodeBlocks && !string.IsNullOrWhiteSpace(dataArgument))
                    {
                        if (dataArgument == "nohighlight")
                        {
                            b.Append("<pre class=\"nocode\">");
                            tagSuffix = "</pre>";
                        }
                        else
                        {
                            b.AppendFormat("<pre><code class=\"{0}\">", dataArgument);
                        }
                    }
                    else
                    {
                        b.Append("<pre><code>");
                    }
                    foreach (var line in Children)
                    {
                        m.HtmlEncodeAndConvertTabsToSpaces(b, line.Buf, line.ContentStart, line.ContentLen);
                        b.Append("\n");
                    }
                    b.Append(tagSuffix);
                }
                else
                {
                    var sb = new StringBuilder();
                    foreach (var line in Children)
                    {
                        m.HtmlEncodeAndConvertTabsToSpaces(sb, line.Buf, line.ContentStart, line.ContentLen);
                        sb.Append("\n");
                    }
                    b.Append(m.FormatCodeBlockFunc(m, sb.ToString()));
                }
                return;

            case BlockType.quote:
                b.Append("<blockquote>\n");
                RenderChildren(m, b);
                b.Append("</blockquote>\n");
                return;

            case BlockType.li:
                b.Append("<li>\n");
                RenderChildren(m, b);
                b.Append("</li>\n");
                return;

            case BlockType.ol:
                b.Append("<ol>\n");
                RenderChildren(m, b);
                b.Append("</ol>\n");
                return;

            case BlockType.ul:
                b.Append("<ul>\n");
                RenderChildren(m, b);
                b.Append("</ul>\n");
                return;

            case BlockType.HtmlTag:
                var tag = (HtmlTag)Data;

                // Prepare special tags
                var name = tag.name.ToLowerInvariant();
                if (name == "a")
                {
                    m.OnPrepareLink(tag);
                }
                else if (name == "img")
                {
                    m.OnPrepareImage(tag, m.RenderingTitledImage);
                }

                tag.RenderOpening(b);
                b.Append("\n");
                RenderChildren(m, b);
                tag.RenderClosing(b);
                b.Append("\n");
                return;

            case BlockType.Composite:
            case BlockType.footnote:
                RenderChildren(m, b);
                return;

            case BlockType.table_spec:
                ((TableSpec)Data).Render(m, b);
                break;

            case BlockType.p_footnote:
                b.Append("<p>");
                if (ContentLen > 0)
                {
                    m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                    b.Append("&nbsp;");
                }
                b.Append((string)Data);
                b.Append("</p>\n");
                break;

// DocNet Extensions
            case BlockType.font_awesome:
                if (m.DocNetMode)
                {
                    b.Append("<i class=\"fa fa-");
                    b.Append(this.Data as string ?? string.Empty);
                    b.Append("\"></i>");
                }
                break;

            case BlockType.alert:
                if (m.DocNetMode)
                {
                    RenderAlert(m, b);
                }
                break;

            case BlockType.tabs:
                if (m.DocNetMode)
                {
                    RenderTabs(m, b);
                }
                break;

// End DocNet Extensions
            default:
                b.Append("<" + BlockType.ToString() + ">");
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("</" + BlockType.ToString() + ">\n");
                break;
            }
        }
Exemple #43
0
        internal void RenderPlain(Markdown m, StringBuilder b)
        {
            switch (BlockType)
            {
            case BlockType.Blank:
                return;

            case BlockType.p:
            case BlockType.span:
                m.SpanFormatter.FormatPlain(b, Buf, ContentStart, ContentLen);
                b.Append(" ");
                break;

            case BlockType.h1:
            case BlockType.h2:
            case BlockType.h3:
            case BlockType.h4:
            case BlockType.h5:
            case BlockType.h6:
                m.SpanFormatter.FormatPlain(b, Buf, ContentStart, ContentLen);
                b.Append(" - ");
                break;


            case BlockType.ol_li:
            case BlockType.ul_li:
                b.Append("* ");
                m.SpanFormatter.FormatPlain(b, Buf, ContentStart, ContentLen);
                b.Append(" ");
                break;

            case BlockType.dd:
                if (Children != null)
                {
                    b.Append("\n");
                    RenderChildrenPlain(m, b);
                }
                else
                {
                    m.SpanFormatter.FormatPlain(b, Buf, ContentStart, ContentLen);
                }
                break;

            case BlockType.dt:
            {
                if (Children == null)
                {
                    foreach (var l in Content.Split('\n'))
                    {
                        var str = l.Trim();
                        m.SpanFormatter.FormatPlain(b, str, 0, str.Length);
                    }
                }
                else
                {
                    RenderChildrenPlain(m, b);
                }
                break;
            }

            case BlockType.dl:
                RenderChildrenPlain(m, b);
                return;

            case BlockType.codeblock:
                foreach (var line in Children)
                {
                    b.Append(line.Buf, line.ContentStart, line.ContentLen);
                    b.Append(" ");
                }
                return;

            case BlockType.quote:
            case BlockType.li:
            case BlockType.ol:
            case BlockType.ul:
            case BlockType.HtmlTag:
                RenderChildrenPlain(m, b);
                return;
            }
        }
Exemple #44
0
        internal void Render(Markdown m, StringBuilder b)
        {
            switch (BlockType)
            {
            case BlockType.Blank:
                return;

            case BlockType.p:
                m.SpanFormatter.FormatParagraph(b, Buf, ContentStart, ContentLen);
                break;

            case BlockType.span:
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("\n");
                break;

            case BlockType.h1:
            case BlockType.h2:
            case BlockType.h3:
            case BlockType.h4:
            case BlockType.h5:
            case BlockType.h6:
                if (m.ExtraMode && !m.SafeMode)
                {
                    b.Append("<" + BlockType);
                    var id = ResolveHeaderID(m);
                    if (!string.IsNullOrEmpty(id))
                    {
                        b.Append(" id=\"");
                        b.Append(id);
                        b.Append("\">");
                    }
                    else
                    {
                        b.Append(">");
                    }
                }
                else
                {
                    b.Append("<" + BlockType + ">");
                }
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("</" + BlockType + ">\n");
                break;

            case BlockType.hr:
                b.Append("<hr />\n");
                return;

            case BlockType.user_break:
                return;

            case BlockType.ol_li:
            case BlockType.ul_li:
                b.Append("<li>");
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("</li>\n");
                break;

            case BlockType.dd:
                b.Append("<dd>");
                if (Children != null)
                {
                    b.Append("\n");
                    RenderChildren(m, b);
                }
                else
                {
                    m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                }
                b.Append("</dd>\n");
                break;

            case BlockType.dt:
            {
                if (Children == null)
                {
                    foreach (var l in Content.Split('\n'))
                    {
                        b.Append("<dt>");
                        m.SpanFormatter.Format(b, l.Trim());
                        b.Append("</dt>\n");
                    }
                }
                else
                {
                    b.Append("<dt>\n");
                    RenderChildren(m, b);
                    b.Append("</dt>\n");
                }
                break;
            }

            case BlockType.dl:
                b.Append("<dl>\n");
                RenderChildren(m, b);
                b.Append("</dl>\n");
                return;

            case BlockType.html:
                b.Append(Buf, ContentStart, ContentLen);
                return;

            case BlockType.unsafe_html:
                m.HtmlEncode(b, Buf, ContentStart, ContentLen);
                return;

            case BlockType.codeblock:
                if (m.FormatCodeBlock != null)
                {
                    var sb = new StringBuilder();
                    foreach (var line in Children)
                    {
                        m.HtmlEncodeAndConvertTabsToSpaces(sb, line.Buf, line.ContentStart, line.ContentLen);
                        sb.Append("\n");
                    }
                    b.Append(m.FormatCodeBlock(m, sb.ToString()));
                }
                else
                {
                    b.Append("<pre><code>");
                    foreach (var line in Children)
                    {
                        m.HtmlEncodeAndConvertTabsToSpaces(b, line.Buf, line.ContentStart, line.ContentLen);
                        b.Append("\n");
                    }
                    b.Append("</code></pre>\n\n");
                }
                return;

            case BlockType.quote:
                b.Append("<blockquote>\n");
                RenderChildren(m, b);
                b.Append("</blockquote>\n");
                return;

            case BlockType.li:
                b.Append("<li>\n");
                RenderChildren(m, b);
                b.Append("</li>\n");
                return;

            case BlockType.ol:
                b.Append("<ol>\n");
                RenderChildren(m, b);
                b.Append("</ol>\n");
                return;

            case BlockType.ul:
                b.Append("<ul>\n");
                RenderChildren(m, b);
                b.Append("</ul>\n");
                return;

            case BlockType.HtmlTag:
                var tag = (HtmlTag)Data;

                // Prepare special tags
                var name = tag.Name.ToLowerInvariant();
                if (name == "a")
                {
                    m.OnPrepareLink(tag);
                }
                else if (name == "img")
                {
                    m.OnPrepareImage(tag, m.RenderingTitledImage);
                }

                tag.RenderOpening(b);
                b.Append("\n");
                RenderChildren(m, b);
                tag.RenderClosing(b);
                b.Append("\n");
                return;

            case BlockType.Composite:
            case BlockType.footnote:
                RenderChildren(m, b);
                return;

            case BlockType.table_spec:
                ((TableSpec)Data).Render(m, b);
                break;

            case BlockType.p_footnote:
                b.Append("<p>");
                if (ContentLen > 0)
                {
                    m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                    b.Append("&nbsp;");
                }
                b.Append((string)Data);
                b.Append("</p>\n");
                break;

            default:
                b.Append("<" + BlockType + ">");
                m.SpanFormatter.Format(b, Buf, ContentStart, ContentLen);
                b.Append("</" + BlockType + ">\n");
                break;
            }
        }