forked from milos-p-lab/MarkdownGuideHtmlConverter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvGuideHtml.cs
More file actions
603 lines (529 loc) · 22.6 KB
/
ConvGuideHtml.cs
File metadata and controls
603 lines (529 loc) · 22.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace m.format.conv
{
/// <summary>
/// Converts AmigaGuide to HTML.
/// </summary>
/// <version>2.3.0</version>
/// <date>2025-08-07</date>
/// <author>Miloš Perunović</author>
public class ConvGuideHtml
{
#region Main methods for converting Markdown to HTML
/// <summary>
/// Converts AmigaGuide document to HTML.
/// </summary>
/// <param name="guide">The AmigaGuide document as a string.</param>
/// <param name="lang">Language code (e.g. "en", "cnr")</param>
/// <param name="head">Additional head elements (e.g. CSS links)</param>
/// <param name="ignoreWarnings">Whether to ignore warnings during conversion</param>
/// <returns>HTML representation of the AmigaGuide document</returns>
public static string Convert(string guide, string lang = "en", string head = null, bool ignoreWarnings = false)
{
Stopwatch sw = Stopwatch.StartNew();
// Convert AmigaGuide to HTML body
// This method will also extract metadata from the document, such as title.
string body = new ConvGuideHtml().ToHtmlBody(guide, out Dictionary<string, string> metadata, ignoreWarnings);
// Generate html meta tags from metadata
StringBuilder meta = new StringBuilder();
if (!metadata.ContainsKey("title")) { metadata["title"] = "Untitled Document"; }
foreach (KeyValuePair<string, string> pair in metadata)
{
if (pair.Key == "title")
{
meta.Append($" <title>{EscapeHtml(pair.Value)}</title>\n");
}
else
{
meta.Append($" <meta name=\"{EscapeHtml(pair.Key)}\" content=\"{EscapeHtml(pair.Value)}\">\n");
}
}
sw.Stop();
double seconds = (double)sw.ElapsedTicks / Stopwatch.Frequency;
Console.WriteLine($"AmigaGuide -> HTML conv.: {seconds} sec.");
return
"<!DOCTYPE html>\n" +
$"<html lang=\"{lang}\">\n" +
"<head>\n" +
" <meta charset=\"utf-8\">\n" +
(meta.Length > 0 ? meta.ToString() : "") +
(head ??
" <style>\n" +
" .btn {\n" +
" display: inline-block;\n" +
" padding: 3px 7px;\n" +
" background: #eee;\n" +
" border: 1px solid #ccc;\n" +
" text-decoration: none;\n" +
" color: #333;\n" +
" }\n" +
" .btn:hover {\n" +
" background: #2f8bc1;\n" +
" }\n" +
" </style>\n"
) +
"</head>\n" +
"<body>\n" +
$"{body}" +
"</body>\n" +
"</html>\n";
}
/// <summary>
/// StringBuilder for accumulating the HTML output.
/// This is used to build the final HTML string efficiently.
/// </summary>
private StringBuilder Out;
private StringBuilder TextBuffer;
/// <summary>
/// Current line number.
/// </summary>
private int LineNum = 1;
/// <summary>
/// Dictionary to hold metadata extracted from the AmigaGuide document.
/// </summary>
private readonly Dictionary<string, string> Metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Converts an AmigaGuide document to HTML.
/// </summary>
/// <param name="doc">AmigaGuide document</param>
/// <param name="metadata">Metadata extracted from the document</param>
/// <param name="ignoreWarnings">Whether to ignore warnings during conversion</param>
/// <returns>HTML representation of the AmigaGuide document</returns>
private string ToHtmlBody(string doc, out Dictionary<string, string> metadata, bool ignoreWarnings)
{
int len = doc.Length;
Out = new StringBuilder(len * 2); // Pre-allocate space for the HTML output
TextBuffer = new StringBuilder();
Out.Append("<pre>\n");
for (int pos = 0; pos < len; pos++)
{
char c = doc[pos];
// Count new lines
if (c == '\n') { LineNum++; }
switch (c)
{
case '\r':
break;
case '<':
Out.Append("<");
break;
case '>':
Out.Append(">");
break;
case '&':
Out.Append("&");
break;
case '\\':
if (pos < len - 1)
{
if (doc[pos + 1] == '\\')
{
Out.Append("\\");
pos++;
}
else if (doc[pos + 1] == '@')
{
Out.Append("@");
pos++;
}
}
break;
case '@':
ProcessCommand(doc, len, ref pos);
break;
default:
if (inNode)
{
Out.Append(c);
}
else
{
TextBuffer.Append(c);
}
break;
}
}
Out.Append("</pre>\n");
CloseUnclosedTags(Out);
// Write any buffered text to the output.
// This is necessary to ensure that any text accumulated in the TextBuffer is written to the output.
WriteBufferedText();
if (!ignoreWarnings)
{
GenerateWarningsReport();
}
metadata = Metadata;
return Out.ToString();
}
/// <summary>
/// Creates an HTML link with a button style.
/// The link will point to an anchor with the specified href.
/// </summary>
/// <param name="linkType">Type of the link (e.g. "link", "alink", "system")</param>
/// <param name="href">The href attribute for the link</param>
/// <param name="text">The text to display for the link</param>
/// <returns>An HTML anchor element with the specified href and text</returns>
private string CreateLink(string linkType, string href, string text)
{
string link = linkType.Trim().ToLower();
switch (link)
{
// Link to another node in the same document or another document
case "link":
case "alink":
{
try
{
string path = href;
string node = "";
string ext = Path.GetExtension(path).ToLower();
int i = path.LastIndexOf('/');
if (i > -1)
{
// Link to a node in another document
node = path.Substring(i + 1).ToLower().Replace(' ', '_');
path = path.Substring(0, i);
path = Path.ChangeExtension(path, "html");
node = "#" + href.Substring(i + 1).ToLower().Replace(' ', '_');
}
else if (ext == ".guide")
{
// If the path is a .guide file, change it to .html
path = Path.ChangeExtension(path, "html");
}
else
{
// If the path does not contain a '/', and is not a .guide file,
// treat it as a node in the current document
node = "#" + path.ToLower().Replace(' ', '_');
path = "";
}
return $"<a href=\"{path}{EscapeHtml(node)}\" class=\"btn\">{EscapeHtml(text)}</a>";
}
catch (Exception ex)
{
ReportWarning(ex.Message);
return $"<a href=\"#{href.ToLower().Replace(' ', '_')}\" class=\"btn\">{EscapeHtml(text)}</a>";
}
}
// Execute system command
case "system":
{
string path = href;
string[] a = path.Split(' ');
if (a.Length > 1)
{
path = path.Substring(a[0].Length).Trim();
}
return $"<a href=\"{path}\" class=\"btn\">{EscapeHtml(text)}</a>";
}
// Unknown link type
default:
ReportWarning("Unknown link type: " + link);
return $"<a href=\"#{href.ToLower().Replace(' ', '_')}\" class=\"btn\">{EscapeHtml(text)}</a>";
}
}
#endregion
#region Helper methods
/// <summary>
/// Escapes HTML special characters in the input string.
/// This method replaces characters like '&', '<', and '>' with their corresponding HTML entities.
/// </summary>
private static string EscapeHtml(string input)
{
return input.Replace("&", "&").Replace("<", "<").Replace(">", ">");
}
/// <summary>
/// Parses the arguments from a string input.
/// Arguments are separated by spaces, and can be enclosed in quotes.
/// </summary>
/// <param name="input">The input string containing arguments.</param>
/// <returns>An array of parsed arguments.</returns>
private static string[] ParseArguments(string input)
{
List<string> result = new List<string>();
int i = 0;
while (i < input.Length)
{
// Skip all whitespace characters
while (i < input.Length && Char.IsWhiteSpace(input[i])) { i++; }
if (i >= input.Length) { break; }
string arg;
if (input[i] == '\"')
{
// Starts quoted argument
i++; // Skip first quote
int start = i;
while (i < input.Length && input[i] != '\"') { i++; }
arg = input.Substring(start, i - start);
if (i < input.Length && input[i] == '\"')
{
i++; // Skip closing quote
}
}
else
{
int start = i;
while (i < input.Length && !char.IsWhiteSpace(input[i])) { i++; }
arg = input.Substring(start, i - start);
}
result.Add(arg);
}
return result.ToArray();
}
/// <summary>
/// Writes the buffered text to the output.
/// This method is called to flush the accumulated text buffer into the HTML output.
/// </summary>
private void WriteBufferedText()
{
if (TextBuffer.Length > 1)
{
string buff = TextBuffer.ToString().Trim(' ', '\n', '\r');
if (buff.Length > 0)
{
Out.Append($"<!-- pre/post-node text (guide preamble): {buff} -->");
}
TextBuffer.Clear();
}
}
#endregion
#region Command processing methods
/// <summary>
/// Flag to indicate if we are currently inside a node.
/// </summary>
private bool inNode;
/// <summary>
/// Counters for the number of open tags.
/// </summary>
private int CntBld, CntItl, CntUnd;
/// <summary>
/// Processes a command in the AmigaGuide document.
/// This method handles commands like `@node`, `@toc`, `@title`, etc
/// </summary>
/// <param name="doc">The AmigaGuide document</param>
/// <param name="len">The length of the document</param>
/// <param name="pos">The current position in the document</param>
/// <returns>The processed command as a string</returns>
private void ProcessCommand(string doc, int len, ref int pos)
{
string res = "";
int start = pos;
if (++pos < len && doc[pos] == '{')
{
// ======== Attributes command ========
string atr = "";
while (++pos < len && doc[pos] != '}')
{
atr += doc[pos];
}
switch (atr.ToLower())
{
case "b":
if (CntBld <= 0) { CntBld++; res = "<strong>"; }
else { ReportWarning("Repeated bold tag"); }
break;
case "ub":
if (CntBld > 0) { CntBld--; res = "</strong>"; }
else { ReportWarning("Closing bold tag without opening"); }
break;
case "i":
if (CntItl <= 0) { CntItl++; res = "<em>"; }
else { ReportWarning("Repeated italic tag"); }
break;
case "ui":
if (CntItl > 0) { CntItl--; res = "</em>"; }
else { ReportWarning("Closing italic tag without opening"); }
break;
case "u":
if (CntUnd <= 0) { CntUnd++; res = "<u>"; }
else { ReportWarning("Repeated underline tag"); }
break;
case "uu":
if (CntUnd > 0) { CntUnd--; res = "</u>"; }
else { ReportWarning("Closing underline tag without opening"); }
break;
case "plain":
CloseUnclosedTags(Out, false);
break;
default:
if (atr.Length > 0 && atr[0] == '"')
{
string[] args = ParseArguments(atr);
if (args.Length > 2)
{
res = CreateLink(linkType: args[1], href: args[2], text: args[0]);
}
else
{
ReportWarning($"Unknown Attribute command: @{{{atr}}}");
if (pos == len) { pos = start; return; }
}
}
else
{
ReportWarning($"Unknown Attribute command: @{{{atr}}}");
if (pos == len) { pos = start; return; }
}
break;
}
}
else
{
// ===== Global and node commands =====
pos--;
string cmdA = "";
while (++pos < len && doc[pos] != '\n' && doc[pos] != '\r')
{
cmdA += doc[pos];
}
// Count new lines
if (pos < len && doc[pos] == '\n') { LineNum++; }
string argLine = "";
int i = cmdA.IndexOf(' ');
if (i != -1)
{
argLine = cmdA.Substring(i + 1);
cmdA = cmdA.Substring(0, i);
}
string cmd = cmdA.ToLower();
string[] args = ParseArguments(argLine);
string arg = args.Length > 0 ? args[0] : "";
bool closeUnclosedTags = true;
switch (cmd)
{
// ======== Node commands ========
case "node":
WriteBufferedText();
if (args.Length > 0)
{
inNode = true;
res = "<a id=\"" + arg.ToLower().Replace(' ', '_') + "\"></a>";
if (args.Length > 1)
{
string s = args[1] ?? arg;
res += $"</pre>\n<h2>{EscapeHtml(s)}</h2>\n<pre>";
}
}
break;
case "endnode":
inNode = false;
res = "</pre>\n<hr>\n<pre>\n";
break;
case "toc":
case "prev":
case "next":
string text = cmd.Replace("toc", "Contents").Replace("prev", "Browse <").Replace("next", "Browse >");
res = CreateLink(linkType: "Link", href: arg, text: text);
break;
// ======== Global commands ========
case "database":
Metadata["title"] = arg;
break;
case "master":
case "help":
case "index":
case "width":
case "wordwrap":
case "smartwrap":
case "font":
res = $"<!-- ignored-command: @{cmdA} {EscapeHtml(argLine)} -->";
break;
case "title":
Metadata["title"] = arg.Trim('"', ' ');
res = $"</pre>\n<h1>{EscapeHtml(arg)}</h1>\n<pre>\n";
break;
case "$ver:":
Metadata["version"] = arg.Trim('"', ' ');
break;
case "author":
Metadata["author"] = arg.Trim('"', ' ');
break;
case "(c)":
Metadata["copyright"] = arg.Trim('"', ' ');
break;
case "rem":
case "remark":
res = $"<!--{EscapeHtml(argLine)}-->\n";
break;
default:
res = $"@{$"{cmdA} {EscapeHtml(argLine)}".Trim()}\n";
closeUnclosedTags = false;
break;
}
if (closeUnclosedTags)
{
CloseUnclosedTags(Out);
}
}
Out.Append(res);
}
/// <summary>
/// Closes any unclosed tags in the HTML output, and reports warnings for each unclosed tag.
/// This method ensures that all opened tags are properly closed before the end of the document.
/// </summary>
private void CloseUnclosedTags(StringBuilder sb, bool report = true)
{
while (CntUnd > 0)
{
sb.Append("</u>");
if (report) { ReportWarning("Unclosed underline tag", before: true); }
CntUnd--;
}
while (CntItl > 0)
{
sb.Append("</em>");
if (report) { ReportWarning("Unclosed italic tag", before: true); }
CntItl--;
}
while (CntBld > 0)
{
sb.Append("</strong>");
if (report)
{ ReportWarning("Unclosed bold tag", before: true); }
CntBld--;
}
}
#endregion
#region Warnings processing
/// <summary>
/// List of warnings encountered during Markdown parsing.
/// This list is used to collect warnings about potential issues in the Markdown text,
/// such as unclosed tags or incorrect formatting.
/// </summary>
private readonly List<string> Warnings = new List<string>();
/// <summary>
/// Reports a warning encountered during Markdown parsing.
/// </summary>
/// <param name="desc">Description of the warning.</param>
private void ReportWarning(string desc, bool before = false)
{
Warnings.Add((before ? "Line <= " : "Line ") + LineNum + ": " + EscapeHtml(desc));
}
/// <summary>
/// Generates a report of any warnings encountered during Markdown parsing.
/// </summary>
private void GenerateWarningsReport()
{
// Generate a report of any warnings
if (Warnings.Count > 0)
{
Out.Append(
"\n<hr>\n" +
"<div class=\"warnings\" style=\"background: #f5f78a; border:2px solid #c43f0f; padding:0.5em; color: #000333; font-family:monospace; font-size:0.95em;\">\n" +
" <h2>⚠️ WARNINGS</h2>\n" +
" <ul>\n");
foreach (string desc in Warnings)
{
Out.Append($" <li>{desc}</li>\n");
}
Out.Append(" </ul>\n</div>\n");
}
}
#endregion
}
}