private static void ProcessFile(MarkdownFile f, String word, String keyword) { String[] parts = f.Content.Split(keyword); Int32 partCount = parts.Length; if (2 > partCount) { return; } Int32 partIndex = 0; String content = parts[partIndex]; while (partIndex < partCount - 1) { if (StringIsPartOfLink(content)) { content += keyword + parts[++partIndex]; continue; } String link = String.Equals(word, keyword) ? $"[[{word}]]" : $"[[{word}|{keyword}]]"; content += link + parts[++partIndex]; Console.WriteLine($"- Created link for '{link}' in {f.Info.Name}"); } f.SetContent(content); }
private void Save(MarkdownFile markdown, string directory, string filename) { using (StreamWriter writer = new StreamWriter(Path.Combine(directory, filename))) { writer.Write(markdown.ToMarkdownString()); } }
public void Test() { PrepareFile(GetFilePathForName("Index"), "[[a1]] [[a2]] [[b]]"); PrepareFile(GetFilePathForName("a1"), "[[a1.1]] [[a1.2]] [[a1.3]], siehe auch: [[a2]]"); PrepareFile(GetFilePathForName("a2"), "[[a2.1]] [[a2.2]]"); PrepareFile(GetFilePathForName("b"), "[[b1]] [[b2]] [[b3]] [[b4]] [[b5]]"); PrepareFile(GetFilePathForName("b1"), "[[b]] [[b1.1]]"); PrepareFile(GetFilePathForName("b2"), "[[b]] [[b2.1]]"); PrepareFile(GetFilePathForName("b3"), "[[b]] [[b3.1]]"); PrepareFile(GetFilePathForName("b4"), "[[b]] [[b4.1]]"); PrepareFile(GetFilePathForName("b5"), "[[b]] [[b5.1]]"); PrepareFile(GetFilePathForName("b5.1"), "[[b5]] [[b5.1]]"); new PluginIdentifyHotspots().Execute(new[] { VaultDirectory } , VaultDirectory); MarkdownFile file = GetPluginOutputFile(); Assert.IsTrue(file.IsHealthy()); Assert.AreEqual(10, file.Links.Count); Assert.IsTrue(file.Content.Contains("6x [[b]]")); Assert.IsTrue(file.Content.Contains("2x [[b5.1]]")); }
private HashSet <MarkdownFile> FindReferences(IEnumerable <String> eFiles, HashSet <String> keywords) { Console.WriteLine("Starting to search for word references..."); HashSet <MarkdownFile> files = new HashSet <MarkdownFile>(); foreach (String filePath in eFiles) { try { MarkdownFile file = new MarkdownFile(filePath); String lText = file.Content.ToLower(); if (keywords.Any(k => lText.Contains(k))) { files.Add(file); } } catch (Exception x) { LogHelper.LogException($"An error occurred searching for file references in path '{filePath}'", x); } } Console.WriteLine("Searching for references done"); return(files); }
public void SimpleTableWithDescriptionAndBlankLine() { var lines = new List <string> { "| Tables | Are | Cool |", "| ------------- |:-------------:| -----:|", "| col 3 is | right - aligned | $1600 |", "| col 2 is | centered | $12 |", "| zebra stripes | are neat | $1 |", " ", "Таблица 1" }; var file = new MarkdownFile() { FilePath = "testFile", Lines = lines }; var result = _checker.Check(file); Assert.AreEqual(0, result.ImageCount); Assert.AreEqual(1, result.TableCount); // TODO: fix unstable equals Assert.IsTrue(result.Messages.ToList().Count == 0); }
private IHtmlContent Layout( string hostUrl, MarkdownFile markdownFile, IHtmlContent content, AutoEnableOptions autoEnableOptions) => $@" <!DOCTYPE html> <html lang=""en""> <head> <meta http-equiv=""Content-Type"" content=""text/html;charset=utf-8""> <script src=""/api/trydotnet.min.js?v={_cacheBuster}""></script> <link rel=""stylesheet"" href=""/css/trydotnet.css?v={_cacheBuster}""> <link rel=""icon"" type=""image/png"" href=""favicon-32x32.png""> {MathSupport()} <title>dotnet try - {markdownFile.Path.Value.HtmlEncode()}</title> </head> <body> {Header()} <section> {content} </section> {Footer()} <script> trydotnet.autoEnable({{ apiBaseAddress: new URL(""{autoEnableOptions.ApiBaseAddress}""), useBlazor: {autoEnableOptions.UseBlazor.ToString().ToLowerInvariant()} }}); </script> </body> </html>".ToHtmlContent();
public Program() { //Test DotNet namespace string outputFolder = Path.Combine(GetMainDirectory(), "DataFiles"); outputFolder = Path.Combine(outputFolder, "bin"); outputFolder = Path.Combine(outputFolder, "Release"); outputFolder = Path.Combine(outputFolder, Properties.Settings.Default.NetVersion); string xmlFilename = Path.Combine(outputFolder, "WithoutHaste.DataFiles.XML"); string dllFilename = Path.Combine(outputFolder, "WithoutHaste.DataFiles.dll"); DotNetDocumentationFile docFile = new DotNetDocumentationFile(xmlFilename); docFile.AddAssemblyInfo(dllFilename); Console.WriteLine("Found {0} types in assembly", docFile.Types.Count); //Test Markdown namespace MarkdownFile mdFile = new MarkdownFile(); mdFile.AddSection("A Header"); string mdText = mdFile.ToMarkdownString(); Console.WriteLine("Some markdown: {0}", mdText); Console.WriteLine("Done"); Console.ReadLine(); }
public void TwoImageTwoTablesFromOfficialGuide() { var lines = new List <string> { "test", "![photo1](link)", "![photo2](link)", "", "| Tables | Are | Cool |", "| ------------- |:-------------:| -----:|", "| col 3 is | right - aligned | $1600 |", "| col 2 is | centered | $12 |", "| zebra stripes | are neat | $1 |", "", "", "Markdown | Less | Pretty", "-- - | --- | ---", "*Still * | `renders` | **nicely * *", "1 | 2 | 3" }; var file = new MarkdownFile() { FilePath = "testFile", Lines = lines }; var result = _checker.Check(file); Assert.AreEqual(2, result.ImageCount); Assert.AreEqual(2, result.TableCount); }
/// <summary> /// The warning applies to a specific section in a file /// </summary> internal WarningLocation(MarkdownFile file, SourceSpan span) : this(file.FullPath, file.RelativePath, span) { if (!RefersToEntireFile) { List <int> lineIndexes = file.ParsingResult.LineStartIndexes; int index = lineIndexes.BinarySearch(span.Start); if (index < 0) { index = ~index - 1; } StartLine = index; StartLineColumn = span.Start - lineIndexes[index]; if (++index == lineIndexes.Count || lineIndexes[index] > span.End) { EndLine = index - 1; EndLineColumn = StartLineColumn + span.Length; return; } index = lineIndexes.BinarySearch(index, lineIndexes.Count - index, span.End, Comparer <int> .Default); if (index < 0) { index = ~index - 1; } EndLine = index; EndLineColumn = span.End - lineIndexes[index]; } }
private async Task <AutoEnableOptions> GetAutoEnableOptions(MarkdownFile file) { bool useWasmRunner; if (_startupOptions.Package != null) { var package = await _packageRegistry.Get <Package2>(_startupOptions.Package); useWasmRunner = package.CanSupportWasm; } else { var blocks = await file.GetAnnotatedCodeBlocks(); var packageUsesWasm = await Task.WhenAll(blocks .Select(b => b.PackageName()) .Select(async name => (await _packageRegistry.Get <ICanSupportWasm>(name))?.CanSupportWasm ?? false)); useWasmRunner = packageUsesWasm.Any(p => p); } var requestUri = Request.GetUri(); var hostUrl = $"{requestUri.Scheme}://{requestUri.Authority}"; return(new AutoEnableOptions(hostUrl, useWasmRunner)); }
private async Task <IHtmlContent> TwoColumnLayoutScaffold(string hostUrl, MarkdownFile markdownFile) => Layout(hostUrl, markdownFile, $@"{await DocumentationDiv(markdownFile)} <div class=""control-column""> {await SessionControlsHtml(markdownFile, _startupOptions.EnablePreviewFeatures)} </div>".ToHtmlContent(), await GetAutoEnableOptions());
public void SimpleTableEofWithoutDescription() { var lines = new List <string> { "| Tables | Are | Cool |", "| ------------- |:-------------:| -----:|", "| col 3 is | right - aligned | $1600 |", "| col 2 is | centered | $12 |", "| zebra stripes | are neat | $1 |", }; var file = new MarkdownFile() { FilePath = "testFile", Lines = lines }; var result = _checker.Check(file); Assert.AreEqual(0, result.ImageCount); Assert.AreEqual(1, result.TableCount); var errorMessage = Utility.GetMessageTableDescriptionMissingEof(file); Assert.IsTrue(result.Messages.ToList().Contains(errorMessage)); }
private MarkdownFile GenerateTableOfContents(DotNetDocumentationFile xmlDocumentation, DotNetQualifiedClassNameTreeNode node) { List <DotNetType> types = xmlDocumentation.Types.Where(t => t.Name.FullNamespace == node.Value).ToList(); List <DotNetDelegate> _delegates = xmlDocumentation.Delegates.Where(d => d.Name.FullNamespace == node.Value).ToList(); MarkdownFile markdown = new MarkdownFile(); string header = "Contents of " + node.Value.FullName; if (node.Parent != null) { header = String.Format("Contents of [{0}]({1}).{2}", node.Parent.Value.FullName, TableOfContentsFilename(node.Parent.Value), node.Value.LocalName); } MarkdownSection section = markdown.AddSection(header); if (node.Children.Count > 0) { MarkdownSection childNamespacesSection = section.AddSection("Namespaces"); foreach (DotNetQualifiedClassNameTreeNode child in node.Children) { section.AddInLine(new MarkdownInlineLink(MarkdownText.Bold(child.Value.FullName), TableOfContentsFilename(child.Value))); } } AddTableOfContentsSection(section, "Concrete Types", types.Where(t => t.Category == TypeCategory.Normal).ToList()); AddTableOfContentsSection(section, "Static Types", types.Where(t => t.Category == TypeCategory.Static).ToList()); AddTableOfContentsSection(section, "Abstract Types", types.Where(t => t.Category == TypeCategory.Abstract).ToList()); AddTableOfContentsSection(section, "Interfaces", types.Where(t => t.Category == TypeCategory.Interface).ToList()); AddTableOfContentsSection(section, "Enums", types.Where(t => t.Category == TypeCategory.Enum).ToList()); AddTableOfContentsSection(section, "Structs", types.Where(t => t.Category == TypeCategory.Struct).ToList()); AddTableOfContentsSection(section, "Delegates", _delegates); AddTableOfContentsSection(section, "Exceptions", types.Where(t => t.Category == TypeCategory.Exception).ToList()); return(markdown); }
/// Markdown format: /// # Title /// /// ![](picture) /// /// ### Metadata /// /// - Author: Author 1, Author 2 /// - Full Title: Title /// - Category: #book /// /// ### Highlights /// - Some Note or quote /// - Some Note or quote /// - Some Note or quote /// - Some Note or quote public static BookRecord CreateBookRecordFromMarkdown(MarkdownFile markdownFile) { var plainText = Markdown.ToPlainText(markdownFile.Content); return(new BookRecord( MapTitle(plainText), MapAuthors(plainText), MapNotes(plainText))); }
public async Task <MarkdownFile> ConvertFile(StorageFile file) { var md = new MarkdownFile(); md.FileName = file.DisplayName; md.Content = await FileIO.ReadTextAsync(file); return(md); }
private async Task <IHtmlContent> TwoColumnLayoutScaffold(string hostUrl, MarkdownFile markdownFile) => Layout(hostUrl, markdownFile, $@" <div id=""documentation-container"" class=""markdown-body""> {await markdownFile.ToHtmlContentAsync()} </div> <div class=""control-column""> {await SessionControlsHtml(markdownFile, _startupOptions.EnablePreviewFeatures)} </div>".ToHtmlContent());
private static MarkdownDocument ParseMarkdownDocument(MarkdownFile markdownFile) { var pipeline = markdownFile.Project.GetMarkdownPipelineFor(markdownFile.Path); var markdown = markdownFile.ReadAllText(); return(Markdig.Markdown.Parse( markdown, pipeline)); }
private static MarkdownFile AddMessage(MarkdownFile file, string message) { var messages = file.Messages.ToList(); messages.Add(message); file.Messages = messages; return(file); }
public void AddSection(String name, String topic) { current = new MarkdownFile(name); current.AddTitle(name); if (!topics.ContainsKey(topic)) topics.Add(topic, new List<String>()); topics[topic].Add(name); files.Add(current); }
private static (MarkdownDocument, string newLine) ParseMarkdownDocument(MarkdownFile markdownFile) { var pipeline = markdownFile.Project.GetMarkdownPipelineFor(markdownFile.Path); var markdown = markdownFile.ReadAllText(); var document = Markdig.Markdown.Parse( markdown, pipeline); return(document, DetectNewLineByFirstOccurence(markdown)); }
public void AddSection(String name, String topic) { current = new MarkdownFile(name); current.AddTitle(name); if (!topics.ContainsKey(topic)) { topics.Add(topic, new List <String>()); } topics[topic].Add(name); files.Add(current); }
public void TableWithBadFormatOnlyHeader() { var lines = new List <string> { "Markdown | Less | Pretty", "-- - | --- | ---", }; var file = new MarkdownFile() { FilePath = "testFile", Lines = lines }; var result = _checker.Check(file); Assert.AreEqual(0, result.ImageCount); Assert.AreEqual(1, result.TableCount); }
public void Test() { String path = Path.Join(VaultDirectory, "Index.md"); PrepareFile(path , "pre [[a]], [[b#c]], [[d|e]], [[f#g|h]]\r\n[[Index]], [[a.b.c]] [[Index#2]], [[Index|index]], [[Index#3|yea]] suf"); PrepareFile(GetFilePathForName("a.b.c"), "abc"); new PluginListDead().Execute(new[] { VaultDirectory } , VaultDirectory); MarkdownFile file = GetPluginOutputFile(); Assert.IsTrue(file.IsHealthy()); Assert.AreEqual(8, file.Links.Count); }
private void HandleFile(MarkdownFile file) { // normalize text RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase; String text = file.Content; text = Regex.Replace(text, "[^a-zA-Z0-9@äöüÄÖÜ-]+", " ", options); text = Regex.Replace(text, "[ ]+", " ", options); List <String> words = text.Split(" ").ToList(); // filter relevant words List <String> processedWords = new List <String>(); foreach (String word in words) { if (String.IsNullOrEmpty(word) || 3 > word.Length) { continue; } processedWords.Add(word); } words = processedWords; // create map foreach (String word in words) { if (_wordStatistics.ContainsKey(word)) { _wordStatistics[word].Count++; } else { _wordStatistics[word] = new WordStatistic { Count = 1 , FileReferences = new List <String>() , SimilarWords = new List <WordStatistic>() , Word = word }; } } }
public static async Task <IHtmlContent> SessionControlsHtml(MarkdownFile markdownFile, bool enablePreviewFeatures = false) { var sessions = (await markdownFile .GetAnnotatedCodeBlocks()) .GroupBy(b => b.Annotations.Session); var sb = new StringBuilder(); foreach (var session in sessions) { sb.AppendLine($@"<button class=""run"" data-trydotnet-mode=""run"" data-trydotnet-session-id=""{session.Key}"" data-trydotnet-run-args=""{session.First().Annotations.RunArgs.HtmlAttributeEncode()}"">{session.Key}{SvgResources.RunButtonSvg}</button>"); sb.AppendLine(enablePreviewFeatures ? $@"<div class=""output-panel"" data-trydotnet-mode=""runResult"" data-trydotnet-output-type=""terminal"" data-trydotnet-session-id=""{session.Key}""></div>" : $@"<div class=""output-panel"" data-trydotnet-mode=""runResult"" data-trydotnet-session-id=""{session.Key}""></div>"); } return(new HtmlString(sb.ToString())); }
public MarkdownFile Read(MarkdownFile file) { string message; try { file.Lines = File.ReadAllLines(file.FilePath); message = Utility.GetMessageReadFile(file); } catch (Exception exc) { file.Lines = Enumerable.Empty <string>(); file.ErrorStatus = true; message = Utility.GetErrorMessageCantOpenFile(file, exc.Message); } _outputWriter.Send(message); return(file); }
void IDisposable.Dispose() { var index = new MarkdownFile("Home"); files.Add(index); index.AddTitle("Documentation"); foreach (var topic in topics) { index.AddHeading(topic.Key); foreach (var link in topic.Value) index.AddLink(link); } foreach (var file in files) file.WriteTo(outputDirectory); files.Clear(); }
public void PathShouldBeAdjustedToOutputFolder(string outputLocation) { var cliOptions = new CliOptions { OutputLocation = outputLocation }; var converter = new MarkdownConverter(MockFactory.Get().Object, cliOptions); var markdownFile = new MarkdownFile { Name = "test.md" }; var result = converter.Convert(markdownFile); // Since the null string can't be searched for, lets cast it to empty // (all strings contain the empty string, so this should just not throw an exception) Assert.Contains(outputLocation, result.Name); }
public void TableWithBadFormat() { var lines = new List <string> { "Markdown | Less | Pretty", "-- - | --- | ---", "*Still * | `renders` | **nicely * *", "1 | 2 | 3" }; var file = new MarkdownFile() { FilePath = "testFile", Lines = lines }; var result = _checker.Check(file); Assert.AreEqual(0, result.ImageCount); Assert.AreEqual(1, result.TableCount); }
public void Test() { PrepareFile(GetFilePathForName("Index"), "das ist ein [[Index]], find [[SubA#b]], [[SubB|abc]]"); PrepareFile(GetFilePathForName("SubA"), "dead end, back to [[Index]]"); PrepareFile(GetFilePathForName("SubB"), "anther one, might be interested in [[SubA]] ? or [[Hub]]"); PrepareFile(GetFilePathForName("Hub"), "[[SubC]], [[SubD]]"); PrepareFile(GetFilePathForName("SubC"), "nichts, nicht wie HubD"); PrepareFile(GetFilePathForName("SubD"), "go back to [[Hub]], or [[Index]]"); new PluginAnalyze().Execute(new[] { VaultDirectory } , VaultDirectory); MarkdownFile file = GetPluginOutputFile(); Assert.IsTrue(file.IsHealthy()); Assert.AreEqual(28, file.Links.Count); }
public void Test() { PrepareFile(RandomFilePath, "pre this is a sample project aprojekt [[a]], [[ndex]], [[Index#3|yea]] suf"); PrepareFile(RandomFilePath, "hier haben wir ei anderes projekt, inkl. projektmanagement"); PrepareFile(RandomFilePath, "dieser hat nichts als referenz"); new PluginFindReferences().Execute(new[] { VaultDirectory , "--find-references" , "project" , "Projekt" } , VaultDirectory); MarkdownFile file = GetPluginOutputFile(); Assert.IsTrue(file.IsHealthy()); Assert.AreEqual(2, file.Links.Count); }
public void Run(IEnumerable <string> filepaths) { var imageTotalCounter = 0; var tableTotalCounter = 0; foreach (var filepath in filepaths) { var file = new MarkdownFile() { FilePath = filepath }; _inputReader.Read(file); _markdownChecker.Check(file); imageTotalCounter += file.ImageCount; tableTotalCounter += file.TableCount; } _outputWriter.Send(Utility.GetTotalImageCount(imageTotalCounter)); _outputWriter.Send(Utility.GetTotalTableCount(tableTotalCounter)); }