Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/_docset.yml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ toc:
- file: code.md
- file: comments.md
- file: conditionals.md
- file: csv-file.md
- hidden: diagrams.md
- file: dropdowns.md
- file: definition-lists.md
Expand Down
6 changes: 6 additions & 0 deletions docs/_snippets/sample-data.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
Name,Age,City,Occupation
John Doe,30,New York,Software Engineer
Jane Smith,25,Los Angeles,Product Manager
Bob Johnson,35,Chicago,Data Scientist
Alice Brown,28,San Francisco,UX Designer
Charlie Wilson,32,Boston,DevOps Engineer
50 changes: 50 additions & 0 deletions docs/syntax/csv-file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# CSV file directive

The `{csv-file}` directive allows you to include and render CSV files as formatted tables in your documentation. The directive automatically parses CSV content and renders it using the standard table styles defined in `table.css`.

## Usage

:::::{tab-set}

::::{tab-item} Output

:::{csv-file} ../_snippets/sample-data.csv
:caption: Sample user data from the database
:::

::::

::::{tab-item} Markdown

```markdown
:::{csv-file} _snippets/sample-data.csv
:::
```

::::

:::::

## Options

The CSV file directive supports several options to customize the table rendering:

### Caption

Add a descriptive caption above the table:

```markdown
:::{csv-file} _snippets/sample-data.csv
:caption: Sample user data from the database
:::
```

### Custom separator

Specify a custom field separator (default is comma):

```markdown
:::{csv-file} _snippets/sample-data.csv
:separator: ;
:::
```
17 changes: 17 additions & 0 deletions docs/syntax/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ V3 fully supports [CommonMark](https://commonmark.org/), a strongly defined, sta
* [Directives](#directives)
* [GitHub-flavored markdown](#github-flavored-markdown)

## Available directives

The following directives are available in Elastic Docs V3:

* [Admonitions](admonitions.md) - Callouts and warnings
* [Code blocks](code.md) - Syntax-highlighted code
* [CSV file](csv-file.md) - Render CSV files as tables
* [Diagrams](diagrams.md) - Visual diagrams and charts
* [Dropdowns](dropdowns.md) - Collapsible content
* [Images](images.md) - Enhanced image handling
* [Include](file_inclusion.md) - Include content from other files
* [Settings](automated_settings.md) - Configuration blocks
* [Stepper](stepper.md) - Step-by-step content
* [Tabs](tabs.md) - Tabbed content organization
* [Tables](tables.md) - Data tables
* [Version blocks](version-variables.md) - API version information

## Directives

Directives extend CommonMark functionality. Directives have the following syntax:
Expand Down
127 changes: 127 additions & 0 deletions src/Elastic.Markdown/Myst/Directives/CsvFile/CsvFileBlock.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Globalization;
using System.IO.Abstractions;
using Elastic.Markdown.Diagnostics;

namespace Elastic.Markdown.Myst.Directives.CsvFile;

public class CsvFileBlock(DirectiveBlockParser parser, ParserContext context) : DirectiveBlock(parser, context)
{
public override string Directive => "csv-file";

public string? CsvFilePath { get; private set; }
public string? CsvFilePathRelativeToSource { get; private set; }
public bool Found { get; private set; }
public string? Caption { get; private set; }
public string Separator { get; private set; } = ",";
public List<string[]> CsvData { get; private set; } = [];

public override void FinalizeAndValidate(ParserContext context)
{
Caption = Prop("caption");

var separator = Prop("separator", "delimiter");
if (!string.IsNullOrEmpty(separator))
Separator = separator;

ExtractCsvPath(context);
if (Found)
ParseCsvFile();
}

private void ExtractCsvPath(ParserContext context)
{
var csvPath = Arguments;
if (string.IsNullOrWhiteSpace(csvPath))
{
this.EmitError("csv-file requires an argument specifying the path to the CSV file.");
return;
}

var csvFrom = context.MarkdownSourcePath.Directory!.FullName;
if (csvPath.StartsWith('/'))
csvFrom = Build.DocumentationSourceDirectory.FullName;

CsvFilePath = Path.Combine(csvFrom, csvPath.TrimStart('/'));
CsvFilePathRelativeToSource = Path.GetRelativePath(Build.DocumentationSourceDirectory.FullName, CsvFilePath);

if (Build.ReadFileSystem.File.Exists(CsvFilePath))
Found = true;
else
this.EmitError($"CSV file `{CsvFilePath}` does not exist.");
}

private void ParseCsvFile()
{
try
{
var file = Build.ReadFileSystem.FileInfo.New(CsvFilePath!);
var content = file.FileSystem.File.ReadAllText(file.FullName);

// Split into lines and parse each line
var lines = content.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries);

foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line.Trim()))
continue;

var fields = ParseCsvLine(line);
CsvData.Add(fields);
}
}
catch (Exception e)
{
this.EmitError($"Failed to parse CSV file: {e.Message}");
}
}

private string[] ParseCsvLine(string line)
{
var fields = new List<string>();
var currentField = "";
var inQuotes = false;
var i = 0;

while (i < line.Length)
{
var c = line[i];

if (c == '"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '"')
{
// Escaped quote
currentField += '"';
i += 2;
}
else
{
// Toggle quote state
inQuotes = !inQuotes;
i++;
}
}
else if (c.ToString() == Separator && !inQuotes)
{
// End of field
fields.Add(currentField.Trim());
currentField = "";
i++;
}
else
{
currentField += c;
i++;
}
}

// Add the last field
fields.Add(currentField.Trim());

return fields.ToArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

using System.Collections.Frozen;
using Elastic.Markdown.Myst.Directives.Admonition;
using Elastic.Markdown.Myst.Directives.CsvFile;
using Elastic.Markdown.Myst.Directives.Diagram;
using Elastic.Markdown.Myst.Directives.Image;
using Elastic.Markdown.Myst.Directives.Include;
Expand Down Expand Up @@ -44,7 +45,6 @@ public DirectiveBlockParser()
{
{ "bibliography", 5 },
{ "blockquote", 6 },
{ "csv-table", 9 },
{ "iframe", 14 },
{ "list-table", 17 },
{ "myst", 22 },
Expand Down Expand Up @@ -122,6 +122,9 @@ protected override DirectiveBlock CreateFencedBlock(BlockProcessor processor)
if (info.IndexOf("{settings}") > 0)
return new SettingsBlock(this, context);

if (info.IndexOf("{csv-file}") > 0)
return new CsvFileBlock(this, context);

foreach (var admonition in _admonitions)
{
if (info.IndexOf($"{{{admonition}}}") > 0)
Expand Down
48 changes: 48 additions & 0 deletions src/Elastic.Markdown/Myst/Directives/DirectiveHtmlRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Elastic.Markdown.Diagnostics;
using Elastic.Markdown.Myst.CodeBlocks;
using Elastic.Markdown.Myst.Directives.Admonition;
using Elastic.Markdown.Myst.Directives.CsvFile;
using Elastic.Markdown.Myst.Directives.Diagram;
using Elastic.Markdown.Myst.Directives.Dropdown;
using Elastic.Markdown.Myst.Directives.Image;
Expand Down Expand Up @@ -81,6 +82,9 @@ protected override void Write(HtmlRenderer renderer, DirectiveBlock directiveBlo
case SettingsBlock settingsBlock:
WriteSettingsBlock(renderer, settingsBlock);
return;
case CsvFileBlock csvFileBlock:
WriteCsvFileBlock(renderer, csvFileBlock);
return;
case StepperBlock stepperBlock:
WriteStepperBlock(renderer, stepperBlock);
return;
Expand Down Expand Up @@ -407,4 +411,48 @@ void Render(Block o)
_ = renderer.Write($"(Block: {o.GetType().Name}");
}
}

private static void WriteCsvFileBlock(HtmlRenderer renderer, CsvFileBlock block)
{
if (!block.Found || block.CsvData.Count == 0)
return;

// Start table wrapper div with the table-wrapper class from table.css
_ = renderer.Write("<div class=\"table-wrapper\">");

// Write caption if provided
if (!string.IsNullOrEmpty(block.Caption))
{
_ = renderer.Write($"<caption>{block.Caption}</caption>");
}

_ = renderer.Write("<table>");

// Always write header row (first row)
if (block.CsvData.Count > 0)
{
_ = renderer.Write("<thead><tr>");
foreach (var header in block.CsvData[0])
{
_ = renderer.Write($"<th>{header}</th>");
}
_ = renderer.Write("</tr></thead>");
}

// Write body rows (starting from second row)
_ = renderer.Write("<tbody>");
for (var i = 1; i < block.CsvData.Count; i++)
{
_ = renderer.Write("<tr>");
foreach (var cell in block.CsvData[i])
{
_ = renderer.Write($"<td>{cell}</td>");
}
_ = renderer.Write("</tr>");
}
_ = renderer.Write("</tbody>");

_ = renderer.Write("</table>");
_ = renderer.Write("</div>");
}
}
Loading
Loading