Doxygen
Loading...
Searching...
No Matches
markdown.cpp
Go to the documentation of this file.
1/******************************************************************************
2 *
3 * Copyright (C) 1997-2020 by Dimitri van Heesch.
4 *
5 * Permission to use, copy, modify, and distribute this software and its
6 * documentation under the terms of the GNU General Public License is hereby
7 * granted. No representations are made about the suitability of this software
8 * for any purpose. It is provided "as is" without express or implied warranty.
9 * See the GNU General Public License for more details.
10 *
11 * Documents produced by Doxygen are derivative works derived from the
12 * input used in their production; they are not affected by this license.
13 *
14 */
15
16/* Note: part of the code below is inspired by libupskirt written by
17 * Natacha Porté. Original copyright message follows:
18 *
19 * Copyright (c) 2008, Natacha Porté
20 *
21 * Permission to use, copy, modify, and distribute this software for any
22 * purpose with or without fee is hereby granted, provided that the above
23 * copyright notice and this permission notice appear in all copies.
24 *
25 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
26 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
27 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
28 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
29 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
30 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
31 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
32 */
33
34// own header
35#include "markdown.h"
36
37// standard includes
38#include <memory>
39#include <string>
40#include <string_view>
41#include <unordered_map>
42#include <vector>
43
44// other includes
45#include "anchor.h"
46#include "cmdmapper.h"
47#include "commentscan.h"
48#include "config.h"
49#include "debug.h"
50#include "doxygen.h"
51#include "entry.h"
52#include "filedef.h"
53#include "fileinfo.h"
54#include "filename.h"
55#include "message.h"
56#include "plantuml.h"
57#include "portable.h"
58#include "regex.h"
59#include "section.h"
60#include "stringutil.h"
61#include "trace.h"
62#include "util.h"
63
64#if !ENABLE_MARKDOWN_TRACING
65#undef AUTO_TRACE
66#undef AUTO_TRACE_ADD
67#undef AUTO_TRACE_EXIT
68#define AUTO_TRACE(...) (void)0
69#define AUTO_TRACE_ADD(...) (void)0
70#define AUTO_TRACE_EXIT(...) (void)0
71#endif
72
74{
75 explicitPage, /**< docs start with a page command */
76 explicitMainPage, /**< docs start with a mainpage command */
77 explicitOtherPage, /**< docs start with a dir / defgroup / addtogroup command */
78 notExplicit /**< docs doesn't start with either page or mainpage */
79};
80
81//-----------
82
83// is character c part of an identifier?
84static constexpr bool isIdChar(char c)
85{
86 return (c>='a' && c<='z') ||
87 (c>='A' && c<='Z') ||
88 (c>='0' && c<='9') ||
89 (static_cast<unsigned char>(c)>=0x80); // unicode characters
90}
91
92// is character allowed right at the beginning of an emphasis section
93static constexpr bool extraChar(char c)
94{
95 return c=='-' || c=='+' || c=='!' || c=='?' || c=='$' || c=='@' ||
96 c=='&' || c=='*' || c=='_' || c=='%' || c=='[' || c=='(' ||
97 c=='.' || c=='>' || c==':' || c==',' || c==';' || c=='\'' ||
98 c=='"' || c=='`' || c=='\\';
99}
100
101// is character c allowed before an emphasis section
102static constexpr bool isOpenEmphChar(char c)
103{
104 return c=='\n' || c==' ' || c=='\'' || c=='<' ||
105 c=='>' || c=='{' || c=='(' || c=='[' ||
106 c==',' || c==':' || c==';';
107}
108
109// test for non breakable space (UTF-8)
110static constexpr bool isUtf8Nbsp(char c1,char c2)
111{
112 return c1==static_cast<char>(0xc2) && c2==static_cast<char>(0xa0);
113}
114
115static constexpr bool isAllowedEmphStr(const std::string_view &data,size_t offset)
116{
117 return ((offset>0 && !isOpenEmphChar(data.data()[-1])) &&
118 (offset>1 && !isUtf8Nbsp(data.data()[-2],data.data()[-1])));
119}
120
121// is character c an escape that prevents ending an emphasis section
122// so for example *bla (*.txt) is cool*, the c=='(' prevents '*' from ending the emphasis section.
123static constexpr bool ignoreCloseEmphChar(char c,char cn)
124{
125 return c=='(' || c=='{' || c=='[' || (c=='<' && cn!='/') || c=='\\' || c=='@';
126}
127
128//----------
129
131{
132 TableCell() : colSpan(false) {}
135};
136
138{
139 Private(const DString &fn,int line,int indent) : fileName(fn), lineNr(line), indentLevel(indent) { }
140
141 DString processQuotations(std::string_view data,size_t refIndent);
142 DString processBlocks(std::string_view data,size_t indent);
143 DString isBlockCommand(std::string_view data,size_t offset);
144 size_t isSpecialCommand(std::string_view data,size_t offset);
145 size_t findEndOfLine(std::string_view data,size_t offset);
146 int processHtmlTagWrite(std::string_view data,size_t offset,bool doWrite);
147 int processHtmlTag(std::string_view data,size_t offset);
148 int processEmphasis(std::string_view data,size_t offset);
149 int processEmphasis1(std::string_view data,char c);
150 int processEmphasis2(std::string_view data,char c);
151 int processEmphasis3(std::string_view data,char c);
152 int processNmdash(std::string_view data,size_t offset);
153 int processQuoted(std::string_view data,size_t offset);
154 int processCodeSpan(std::string_view data,size_t offset);
155 int processSpecialCommand(std::string_view data,size_t offset);
156 int processLink(std::string_view data,size_t offset);
157 size_t findEmphasisChar(std::string_view, char c, size_t c_size);
158 void addStrEscapeUtf8Nbsp(std::string_view data);
159 void processInline(std::string_view data);
160 void writeMarkdownImage(std::string_view fmt, bool inline_img, bool explicitTitle,
161 const DString &title, const DString &content,
162 const DString &link, const DString &attributes,
163 const FileDef *fd);
164 int isHeaderline(std::string_view data, bool allowAdjustLevel);
165 int isAtxHeader(std::string_view data, DString &header,DString &id,bool allowAdjustLevel,
166 bool *pIsIdGenerated=nullptr);
167 void writeOneLineHeaderOrRuler(std::string_view data);
168 void writeFencedCodeBlock(std::string_view data, std::string_view lang,
169 size_t blockStart,size_t blockEnd);
170 size_t writeBlockQuote(std::string_view data);
171 size_t writeCodeBlock(std::string_view,size_t refIndent);
172 size_t writeTableBlock(std::string_view data);
173 DString extractTitleId(DString &title, int level,bool *pIsIdGenerated=nullptr);
174
175 struct LinkRef
176 {
177 LinkRef(const DString &l,const DString &t) : link(l), title(t) {}
180 };
181
182 std::unordered_map<std::string,LinkRef> linkRefs;
184 int lineNr = 0;
185 int indentLevel=0; // 0 is outside markdown, -1=page level
187};
188
190{
192 a[static_cast<unsigned int>('_')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processEmphasis (data,offset); };
193 a[static_cast<unsigned int>('*')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processEmphasis (data,offset); };
194 a[static_cast<unsigned int>('~')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processEmphasis (data,offset); };
195 a[static_cast<unsigned int>('`')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processCodeSpan (data,offset); };
196 a[static_cast<unsigned int>('\\')]= [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processSpecialCommand(data,offset); };
197 a[static_cast<unsigned int>('@')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processSpecialCommand(data,offset); };
198 a[static_cast<unsigned int>('[')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processLink (data,offset); };
199 a[static_cast<unsigned int>('!')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processLink (data,offset); };
200 a[static_cast<unsigned int>('<')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processHtmlTag (data,offset); };
201 a[static_cast<unsigned int>('-')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processNmdash (data,offset); };
202 a[static_cast<unsigned int>('"')] = [](Markdown::Private &obj,std::string_view data,size_t offset) { return obj.processQuoted (data,offset); };
203 return a;
204}
206
207
208Markdown::Markdown(const DString &fileName,int lineNr,int indentLevel)
209 : prv(std::make_unique<Private>(fileName,lineNr,indentLevel))
210{
211 using namespace std::placeholders;
212 (void)lineNr; // not used yet
213}
214
215Markdown::~Markdown() = default;
216
217void Markdown::setIndentLevel(int level) { prv->indentLevel = level; }
218
219enum class Alignment { None, Left, Center, Right };
220
221
222//---------- constants -------
223//
224static const char *g_utf8_nbsp = "\xc2\xa0"; // UTF-8 nbsp
225static const char *g_doxy_nbsp = "&_doxy_nbsp;"; // doxygen escape command for UTF-8 nbsp
226static const size_t codeBlockIndent = 4;
227
228//---------- helpers -------
229
230// test if the next characters in data represent a new line (which can be character \n or string \ilinebr).
231// returns 0 if no newline is found, or the number of characters that make up the newline if found.
232inline size_t isNewline(std::string_view data)
233{
234 // normal newline
235 if (data[0] == '\n') return 1;
236 // artificial new line from ^^ in ALIASES
237 if (literal_at(data,"\\ilinebr"))
238 {
239 return (data.size()>8 && data[8]==' ') ? 9 : 8; // also count space after \ilinebr if present
240 }
241 return 0;
242}
243
244// escape double quotes in string
246{
247 AUTO_TRACE("s={}",Trace::trunc(s));
248 if (s.empty()) return s;
249 DString result;
250 const char *p=s.data();
251 char c=0, pc='\0';
252 while ((c=*p++))
253 {
254 if (c=='"' && pc!='\\') result+='\\';
255 result+=c;
256 pc=c;
257 }
258 AUTO_TRACE_EXIT("result={}",result);
259 return result;
260}
261
262// escape characters that have a special meaning later on.
264{
265 AUTO_TRACE("s={}",Trace::trunc(s));
266 if (s.empty()) return s;
267 bool insideQuote=false;
268 DString result;
269 const char *p=s.data();
270 char c=0, pc='\0';
271 while ((c=*p++))
272 {
273 switch (c)
274 {
275 case '"':
276 if (pc!='\\')
277 {
278 if (Config_getBool(MARKDOWN_STRICT))
279 {
280 result+='\\';
281 }
282 else // For Doxygen's markup style a quoted text is left untouched
283 {
284 insideQuote=!insideQuote;
285 }
286 }
287 result+=c;
288 break;
289 case '<':
290 // fall through
291 case '>':
292 if (!insideQuote)
293 {
294 result+='\\';
295 result+=c;
296 if ((p[0]==':') && (p[1]==':'))
297 {
298 result+='\\';
299 result+=':';
300 p++;
301 }
302 }
303 else
304 {
305 result+=c;
306 }
307 break;
308 case '\\': if (!insideQuote) { result+='\\'; } result+='\\'; break;
309 case '@': if (!insideQuote) { result+='\\'; } result+='@'; break;
310 // commented out next line due to regression when using % to suppress a link
311 //case '%': if (!insideQuote) { result+='\\'; } result+='%'; break;
312 case '#': if (!insideQuote) { result+='\\'; } result+='#'; break;
313 case '$': if (!insideQuote) { result+='\\'; } result+='$'; break;
314 case '&': if (!insideQuote) { result+='\\'; } result+='&'; break;
315 default:
316 result+=c; break;
317 }
318 pc=c;
319 }
320 AUTO_TRACE_EXIT("result={}",result);
321 return result;
322}
323
324/** helper function to convert presence of left and/or right alignment markers
325 * to an alignment value
326 */
327static constexpr Alignment markersToAlignment(bool leftMarker,bool rightMarker)
328{
329 if (leftMarker && rightMarker)
330 {
331 return Alignment::Center;
332 }
333 else if (leftMarker)
334 {
335 return Alignment::Left;
336 }
337 else if (rightMarker)
338 {
339 return Alignment::Right;
340 }
341 else
342 {
343 return Alignment::None;
344 }
345}
346
347/** parse the image attributes and return attributes for given format */
348static DString getFilteredImageAttributes(std::string_view fmt, const DString &attrs)
349{
350 AUTO_TRACE("fmt={} attrs={}",fmt,attrs);
351 StringVector attrList = split(attrs.str(),",");
352 for (const auto &attr_ : attrList)
353 {
354 DString attr = DString(attr_).stripWhiteSpace();
355 if (size_t i = attr.find(':'); i!=DString::npos && i>0) // has format
356 {
357 DString format = attr.left(i).stripWhiteSpace().lower();
358 if (format == fmt) // matching format
359 {
360 AUTO_TRACE_EXIT("result={}",attr.mid(i+1));
361 return attr.mid(i+1); // keep part after :
362 }
363 }
364 else // option that applies to all formats
365 {
366 AUTO_TRACE_EXIT("result={}",attr);
367 return attr;
368 }
369 }
370 return DString();
371}
372
373// Check if data contains a block command. If so returned the command
374// that ends the block. If not an empty string is returned.
375// Note When offset>0 character position -1 will be inspected.
376//
377// Checks for and skip the following block commands:
378// {@code .. { .. } .. }
379// \dot .. \enddot
380// \code .. \endcode
381// \msc .. \endmsc
382// \mermaid .. \endmermaid
383// \f$..\f$
384// \f(..\f)
385// \f[..\f]
386// \f{..\f}
387// \verbatim..\endverbatim
388// \iliteral..\endiliteral
389// \latexonly..\endlatexonly
390// \htmlonly..\endhtmlonly
391// \xmlonly..\endxmlonly
392// \rtfonly..\endrtfonly
393// \manonly..\endmanonly
394// \startuml..\enduml
395DString Markdown::Private::isBlockCommand(std::string_view data,size_t offset)
396{
397 DString result;
398 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
399
400 using EndBlockFunc = DString (*)(const std::string &,bool,char);
401
402 static constexpr auto getEndBlock = [](const std::string &blockName,bool,char) -> DString
403 {
404 return "end"+blockName;
405 };
406 static constexpr auto getEndCode = [](const std::string &blockName,bool openBracket,char) -> DString
407 {
408 return openBracket ? DString("}") : "end"+blockName;
409 };
410 static constexpr auto getEndUml = [](const std::string &/* blockName */,bool,char) -> DString
411 {
412 return "enduml";
413 };
414 static constexpr auto getEndFormula = [](const std::string &/* blockName */,bool,char nextChar) -> DString
415 {
416 switch (nextChar)
417 {
418 case '$': return "f$";
419 case '(': return "f)";
420 case '[': return "f]";
421 case '{': return "f}";
422 }
423 return "";
424 };
425
426 // table mapping a block start command to a function that can return the matching end block string
427 static const std::unordered_map<std::string,EndBlockFunc> blockNames =
428 {
429 { "dot", getEndBlock },
430 { "code", getEndCode },
431 { "icode", getEndBlock },
432 { "msc", getEndBlock },
433 { "verbatim", getEndBlock },
434 { "iverbatim", getEndBlock },
435 { "iliteral", getEndBlock },
436 { "latexonly", getEndBlock },
437 { "htmlonly", getEndBlock },
438 { "xmlonly", getEndBlock },
439 { "rtfonly", getEndBlock },
440 { "manonly", getEndBlock },
441 { "docbookonly", getEndBlock },
442 { "startuml", getEndUml },
443 { "mermaid", getEndBlock },
444 { "f", getEndFormula }
445 };
446
447 const size_t size = data.size();
448 bool openBracket = offset>0 && data.data()[-1]=='{';
449 bool isEscaped = offset>0 && (data.data()[-1]=='\\' || data.data()[-1]=='@');
450 if (isEscaped) return result;
451
452 size_t end=1;
453 while (end<size && (data[end]>='a' && data[end]<='z')) end++;
454 if (end==1) return result;
455 std::string blockName(data.substr(1,end-1));
456 auto it = blockNames.find(blockName);
457 if (it!=blockNames.end()) // there is a function assigned
458 {
459 result = it->second(blockName, openBracket, end<size ? data[end] : 0);
460 }
461 AUTO_TRACE_EXIT("result={}",result);
462 return result;
463}
464
465size_t Markdown::Private::isSpecialCommand(std::string_view data,size_t offset)
466{
467 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
468
469 using EndCmdFunc = size_t (*)(std::string_view,size_t);
470
471 static constexpr auto endOfLine = [](std::string_view data_,size_t offset_) -> size_t
472 {
473 // skip until the end of line (allowing line continuation characters)
474 char lc = 0;
475 char c = 0;
476 while (offset_<data_.size() && ((c=data_[offset_])!='\n' || lc=='\\'))
477 {
478 if (c=='\\') lc='\\'; // last character was a line continuation
479 else if (c!=' ') lc=0; // rest line continuation
480 offset_++;
481 }
482 return offset_;
483 };
484
485 static constexpr auto endOfLabels = [](std::string_view data_,size_t offset_,bool multi_) -> size_t
486 {
487 if (offset_<data_.size() && data_[offset_]==' ') // we expect a space before the label
488 {
489 char c = 0;
490 offset_++;
491 bool done=false;
492 while (!done)
493 {
494 // skip over spaces
495 while (offset_<data_.size() && data_[offset_]==' ')
496 {
497 offset_++;
498 }
499 // skip over label
500 while (offset_<data_.size() && (c=data_[offset_])!=' ' && c!=',' && c!='\\' && c!='@' && c!='\n')
501 {
502 offset_++;
503 }
504 // optionally skip over a comma separated list of labels
505 if (multi_ && offset_<data_.size() && (data_[offset_]==',' || data_[offset_]==' '))
506 {
507 size_t off = offset_;
508 while (off<data_.size() && data_[off]==' ')
509 {
510 off++;
511 }
512 if (off<data_.size() && data_[off]==',')
513 {
514 offset_ = ++off;
515 }
516 else // no next label found
517 {
518 done=true;
519 }
520 }
521 else
522 {
523 done=true;
524 }
525 }
526 return offset_;
527 }
528 return 0;
529 };
530
531 static constexpr auto endOfLabel = [](std::string_view data_,size_t offset_) -> size_t
532 {
533 return endOfLabels(data_,offset_,false);
534 };
535
536 static constexpr auto endOfLabelOpt = [](std::string_view data_,size_t offset_) -> size_t
537 {
538 size_t index=offset_;
539 if (index<data_.size() && data_[index]==' ') // skip over optional spaces
540 {
541 index++;
542 while (index<data_.size() && data_[index]==' ') index++;
543 }
544 if (index<data_.size() && data_[index]=='{') // find matching '}'
545 {
546 index++;
547 char c = 0;
548 while (index<data_.size() && (c=data_[index])!='}' && c!='\\' && c!='@' && c!='\n') index++;
549 if (index==data_.size() || data_[index]!='}') return 0; // invalid option
550 offset_=index+1; // part after {...} is the option
551 }
552 return endOfLabel(data_,offset_);
553 };
554
555 static constexpr auto endOfParam = [](std::string_view data_,size_t offset_) -> size_t
556 {
557 size_t index=offset_;
558 if (index<data_.size() && data_[index]==' ') // skip over optional spaces
559 {
560 index++;
561 while (index<data_.size() && data_[index]==' ') index++;
562 }
563 if (index<data_.size() && data_[index]=='[') // find matching ']'
564 {
565 index++;
566 char c = 0;
567 while (index<data_.size() && (c=data_[index])!=']' && c!='\n') index++;
568 if (index==data_.size() || data_[index]!=']') return 0; // invalid parameter
569 offset_=index+1; // part after [...] is the parameter name
570 }
571 return endOfLabels(data_,offset_,true);
572 };
573
574 static constexpr auto endOfRetVal = [](std::string_view data_,size_t offset_) -> size_t
575 {
576 return endOfLabels(data_,offset_,true);
577 };
578
579 static constexpr auto endOfFuncLike = [](std::string_view data_,size_t offset_,bool allowSpaces) -> size_t
580 {
581 if (offset_<data_.size() && data_[offset_]==' ') // we expect a space before the name
582 {
583 char c=0;
584 offset_++;
585 // skip over spaces
586 while (offset_<data_.size() && data_[offset_]==' ')
587 {
588 offset_++;
589 }
590 // skip over name (and optionally type)
591 while (offset_<data_.size() && (c=data_[offset_])!='\n' && (allowSpaces || c!=' ') && c!='(')
592 {
593 if (literal_at(data_.substr(offset_),"\\ilinebr ")) break;
594 offset_++;
595 }
596 if (c=='(') // find the end of the function
597 {
598 int count=1;
599 offset_++;
600 while (offset_<data_.size() && (c=data_[offset_++]))
601 {
602 if (c=='(') count++;
603 else if (c==')') count--;
604 if (count==0) return offset_;
605 }
606 }
607 return offset_;
608 }
609 return 0;
610 };
611
612 static constexpr auto endOfFunc = [](std::string_view data_,size_t offset_) -> size_t
613 {
614 return endOfFuncLike(data_,offset_,true);
615 };
616
617 static constexpr auto endOfGuard = [](std::string_view data_,size_t offset_) -> size_t
618 {
619 return endOfFuncLike(data_,offset_,false);
620 };
621
622 static const std::unordered_map<std::string,EndCmdFunc> cmdNames =
623 {
624 { "a", endOfLabel },
625 { "addindex", endOfLine },
626 { "addtogroup", endOfLabel },
627 { "anchor", endOfLabel },
628 { "b", endOfLabel },
629 { "c", endOfLabel },
630 { "category", endOfLine },
631 { "cite", endOfLabelOpt },
632 { "class", endOfLine },
633 { "concept", endOfLine },
634 { "copybrief", endOfFunc },
635 { "copydetails", endOfFunc },
636 { "copydoc", endOfFunc },
637 { "def", endOfFunc },
638 { "defgroup", endOfLabel },
639 { "diafile", endOfLine },
640 { "dir", endOfLine },
641 { "dockbookinclude",endOfLine },
642 { "dontinclude", endOfLine },
643 { "dotfile", endOfLine },
644 { "e", endOfLabel },
645 { "elseif", endOfGuard },
646 { "em", endOfLabel },
647 { "emoji", endOfLabel },
648 { "enum", endOfLabel },
649 { "example", endOfLine },
650 { "exception", endOfLabel },
651 { "extends", endOfLabel },
652 { "file", endOfLine },
653 { "fn", endOfFunc },
654 { "headerfile", endOfLine },
655 { "htmlinclude", endOfLine },
656 { "ianchor", endOfLabelOpt },
657 { "idlexcept", endOfLine },
658 { "if", endOfGuard },
659 { "ifnot", endOfGuard },
660 { "image", endOfLine },
661 { "implements", endOfLine },
662 { "include", endOfLine },
663 { "includedoc", endOfLine },
664 { "includelineno", endOfLine },
665 { "ingroup", endOfLabel },
666 { "interface", endOfLine },
667 { "latexinclude", endOfLine },
668 { "maninclude", endOfLine },
669 { "field", endOfLabel },
670 { "memberof", endOfLabel },
671 { "mermaidfile", endOfLine },
672 { "mscfile", endOfLine },
673 { "namespace", endOfLabel },
674 { "noop", endOfLine },
675 { "overload", endOfLine },
676 { "p", endOfLabel },
677 { "package", endOfLabel },
678 { "page", endOfLabel },
679 { "paragraph", endOfLabel },
680 { "param", endOfParam },
681 { "property", endOfLine },
682 { "protocol", endOfLine },
683 { "qualifier", endOfLine },
684 { "record", endOfLine },
685 { "ref", endOfLabel },
686 { "refitem", endOfLine },
687 { "related", endOfLabel },
688 { "relatedalso", endOfLabel },
689 { "relates", endOfLabel },
690 { "relatesalso", endOfLabel },
691 { "requirement", endOfLabel },
692 { "retval", endOfRetVal},
693 { "rtfinclude", endOfLine },
694 { "section", endOfLabel },
695 { "skip", endOfLine },
696 { "skipline", endOfLine },
697 { "snippet", endOfLine },
698 { "snippetdoc", endOfLine },
699 { "snippetlineno", endOfLine },
700 { "struct", endOfLine },
701 { "satisfies", endOfLabel },
702 { "subpage", endOfLabel },
703 { "subparagraph", endOfLabel },
704 { "subsubparagraph",endOfLabel },
705 { "subsection", endOfLabel },
706 { "subsubsection", endOfLabel },
707 { "throw", endOfLabel },
708 { "throws", endOfLabel },
709 { "tparam", endOfLabel },
710 { "typedef", endOfLine },
711 { "plantumlfile", endOfLine },
712 { "union", endOfLine },
713 { "until", endOfLine },
714 { "var", endOfLine },
715 { "verbinclude", endOfLine },
716 { "verifies", endOfLabel },
717 { "weakgroup", endOfLabel },
718 { "xmlinclude", endOfLine },
719 { "xrefitem", endOfLabel }
720 };
721
722 bool isEscaped = offset>0 && (data.data()[-1]=='\\' || data.data()[-1]=='@');
723 if (isEscaped) return 0;
724
725 const size_t size = data.size();
726 size_t end=1;
727 while (end<size && (data[end]>='a' && data[end]<='z')) end++;
728 if (end==1) return 0;
729 std::string cmdName(data.substr(1,end-1));
730 size_t result=0;
731 auto it = cmdNames.find(cmdName);
732 if (it!=cmdNames.end()) // command with parameters that should be ignored by markdown
733 {
734 // find the end of the parameters
735 result = it->second(data,end);
736 }
737 AUTO_TRACE_EXIT("result={}",result);
738 return result;
739}
740
741/** looks for the next emph char, skipping other constructs, and
742 * stopping when either it is found, or we are at the end of a paragraph.
743 */
744size_t Markdown::Private::findEmphasisChar(std::string_view data, char c, size_t c_size)
745{
746 AUTO_TRACE("data='{}' c={} c_size={}",Trace::trunc(data),c,c_size);
747 size_t i = 1;
748 const size_t size = data.size();
749
750 while (i<size)
751 {
752 while (i<size && data[i]!=c &&
753 data[i]!='\\' && data[i]!='@' &&
754 !(data[i]=='/' && data[i-1]=='<') && // html end tag also ends emphasis
755 data[i]!='\n') i++;
756 // avoid overflow (unclosed emph token)
757 if (i==size)
758 {
759 return 0;
760 }
761 //printf("findEmphasisChar: data=[%s] i=%d c=%c\n",data,i,data[i]);
762
763 // not counting escaped chars or characters that are unlikely
764 // to appear as the end of the emphasis char
765 if (ignoreCloseEmphChar(data[i-1],data[i]))
766 {
767 i++;
768 continue;
769 }
770 else
771 {
772 // get length of emphasis token
773 size_t len = 0;
774 while (i+len<size && data[i+len]==c)
775 {
776 len++;
777 }
778
779 if (len>0)
780 {
781 if (len!=c_size || (i+len<size && isIdChar(data[i+len]))) // to prevent touching some_underscore_identifier
782 {
783 i+=len;
784 continue;
785 }
786 AUTO_TRACE_EXIT("result={}",i);
787 return static_cast<int>(i); // found it
788 }
789 }
790
791 // skipping a code span
792 if (data[i]=='`')
793 {
794 int snb=0;
795 while (i < size && data[i] == '`')
796 {
797 snb++;
798 i++;
799 }
800
801 // find same pattern to end the span
802 int enb=0;
803 while (i<size && enb<snb)
804 {
805 if (data[i]=='`') enb++;
806 if (snb==1 && data[i]=='\'') break; // ` ended by '
807 i++;
808 }
809 }
810 else if (data[i]=='@' || data[i]=='\\')
811 { // skip over blocks that should not be processed
812 DString endBlockName = isBlockCommand(data.substr(i),i);
813 if (!endBlockName.empty())
814 {
815 i++;
816 size_t l = endBlockName.length();
817 while (i+l<size)
818 {
819 if ((data[i]=='\\' || data[i]=='@') && // command
820 data[i-1]!='\\' && data[i-1]!='@') // not escaped
821 {
822 if (dstrncmp(&data[i+1],endBlockName.data(),l)==0)
823 {
824 break;
825 }
826 }
827 i++;
828 }
829 }
830 else if (i+1<size && isIdChar(data[i+1])) // @cmd, stop processing, see bug 690385
831 {
832 return 0;
833 }
834 else
835 {
836 i++;
837 }
838 }
839 else if (data[i-1]=='<' && data[i]=='/') // html end tag invalidates emphasis
840 {
841 return 0;
842 }
843 else if (data[i]=='\n') // end * or _ at paragraph boundary
844 {
845 i++;
846 while (i<size && data[i]==' ') i++;
847 if (i>=size || data[i]=='\n')
848 {
849 return 0;
850 } // empty line -> paragraph
851 }
852 else // should not get here!
853 {
854 i++;
855 }
856 }
857 return 0;
858}
859
860/** process single emphasis */
861int Markdown::Private::processEmphasis1(std::string_view data, char c)
862{
863 AUTO_TRACE("data='{}' c={}",Trace::trunc(data),c);
864 size_t i = 0;
865 const size_t size = data.size();
866
867 /* skipping one symbol if coming from emph3 */
868 if (size>1 && data[0]==c && data[1]==c) { i=1; }
869
870 while (i<size)
871 {
872 size_t len = findEmphasisChar(data.substr(i), c, 1);
873 if (len==0) { return 0; }
874 i+=len;
875 if (i>=size) { return 0; }
876
877 if (i+1<size && data[i+1]==c)
878 {
879 i++;
880 continue;
881 }
882 if (data[i]==c && data[i-1]!=' ' && data[i-1]!='\n')
883 {
884 out+="<em>";
885 processInline(data.substr(0,i));
886 out+="</em>";
887 AUTO_TRACE_EXIT("result={}",i+1);
888 return static_cast<int>(i+1);
889 }
890 }
891 return 0;
892}
893
894/** process double emphasis */
895int Markdown::Private::processEmphasis2(std::string_view data, char c)
896{
897 AUTO_TRACE("data='{}' c={}",Trace::trunc(data),c);
898 size_t i = 0;
899 const size_t size = data.size();
900
901 while (i<size)
902 {
903 size_t len = findEmphasisChar(data.substr(i), c, 2);
904 if (len==0)
905 {
906 return 0;
907 }
908 i += len;
909 if (i+1<size && data[i]==c && data[i+1]==c && i && data[i-1]!=' ' && data[i-1]!='\n')
910 {
911 if (c == '~') out+="<strike>";
912 else out+="<strong>";
913 processInline(data.substr(0,i));
914 if (c == '~') out+="</strike>";
915 else out+="</strong>";
916 AUTO_TRACE_EXIT("result={}",i+2);
917 return static_cast<int>(i+2);
918 }
919 i++;
920 }
921 return 0;
922}
923
924/** Parsing triple emphasis.
925 * Finds the first closing tag, and delegates to the other emph
926 */
927int Markdown::Private::processEmphasis3(std::string_view data,char c)
928{
929 AUTO_TRACE("data='{}' c={}",Trace::trunc(data),c);
930 size_t i = 0;
931 const size_t size = data.size();
932
933 while (i<size)
934 {
935 size_t len = findEmphasisChar(data.substr(i), c, 3);
936 if (len==0)
937 {
938 return 0;
939 }
940 i+=len;
941
942 /* skip whitespace preceded symbols */
943 if (data[i]!=c || data[i-1]==' ' || data[i-1]=='\n')
944 {
945 continue;
946 }
947
948 if (i+2<size && data[i+1]==c && data[i+2]==c)
949 {
950 out+="<em><strong>";
951 processInline(data.substr(0,i));
952 out+="</strong></em>";
953 AUTO_TRACE_EXIT("result={}",i+3);
954 return static_cast<int>(i+3);
955 }
956 else if (i+1<size && data[i+1]==c)
957 {
958 // double symbol found, handing over to emph1
959 len = processEmphasis1(std::string_view(data.data()-2, size+2), c);
960 if (len==0)
961 {
962 return 0;
963 }
964 else
965 {
966 AUTO_TRACE_EXIT("result={}",len-2);
967 return static_cast<int>(len - 2);
968 }
969 }
970 else
971 {
972 // single symbol found, handing over to emph2
973 len = processEmphasis2(std::string_view(data.data()-1, size+1), c);
974 if (len==0)
975 {
976 return 0;
977 }
978 else
979 {
980 AUTO_TRACE_EXIT("result={}",len-1);
981 return static_cast<int>(len - 1);
982 }
983 }
984 }
985 return 0;
986}
987
988/** Process ndash and mdashes */
989int Markdown::Private::processNmdash(std::string_view data,size_t offset)
990{
991 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
992 const size_t size = data.size();
993 // precondition: data[0]=='-'
994 size_t i=1;
995 int count=1;
996 if (i<size && data[i]=='-') // found --
997 {
998 count++;
999 i++;
1000 }
1001 if (i<size && data[i]=='-') // found ---
1002 {
1003 count++;
1004 i++;
1005 }
1006 if (i<size && data[i]=='-') // found ----
1007 {
1008 count++;
1009 }
1010 if (count>=2 && offset>=2 && literal_at(data.data()-2,"<!"))
1011 { AUTO_TRACE_EXIT("result={}",1-count); return 1-count; } // start HTML comment
1012 if (count==2 && size > 2 && data[2]=='>')
1013 { return 0; } // end HTML comment
1014 if (count==3 && size > 3 && data[3]=='>')
1015 { return 0; } // end HTML comment
1016 if (count==2 && (offset<8 || !literal_at(data.data()-8,"operator"))) // -- => ndash
1017 {
1018 out+="&ndash;";
1019 AUTO_TRACE_EXIT("result=2");
1020 return 2;
1021 }
1022 else if (count==3) // --- => ndash
1023 {
1024 out+="&mdash;";
1025 AUTO_TRACE_EXIT("result=3");
1026 return 3;
1027 }
1028 // not an ndash or mdash
1029 return 0;
1030}
1031
1032/** Process quoted section "...", can contain one embedded newline */
1033int Markdown::Private::processQuoted(std::string_view data,size_t)
1034{
1035 AUTO_TRACE("data='{}'",Trace::trunc(data));
1036 const size_t size = data.size();
1037 size_t i=1;
1038 int nl=0;
1039 while (i<size && data[i]!='"' && nl<2)
1040 {
1041 if (data[i]=='\n') nl++;
1042 i++;
1043 }
1044 if (i<size && data[i]=='"' && nl<2)
1045 {
1046 out+=data.substr(0,i+1);
1047 AUTO_TRACE_EXIT("result={}",i+2);
1048 return static_cast<int>(i+1);
1049 }
1050 // not a quoted section
1051 return 0;
1052}
1053
1054/** Process a HTML tag. Note that <pre>..</pre> are treated specially, in
1055 * the sense that all code inside is written unprocessed
1056 */
1057int Markdown::Private::processHtmlTagWrite(std::string_view data,size_t offset,bool doWrite)
1058{
1059 AUTO_TRACE("data='{}' offset={} doWrite={}",Trace::trunc(data),offset,doWrite);
1060 if (offset>0 && data.data()[-1]=='\\') { return 0; } // escaped <
1061
1062 const size_t size = data.size();
1063
1064 // find the end of the html tag
1065 size_t i=1;
1066 size_t l=0;
1067 // compute length of the tag name
1068 while (i < size && isIdChar(data[i]))
1069 {
1070 i++;
1071 l++;
1072 }
1073 DString tagName(data.substr(1,i-1));
1074 if (tagName.lower()=="pre") // found <pre> tag
1075 {
1076 bool insideStr=false;
1077 while (i+6<size)
1078 {
1079 char c=data[i];
1080 if (!insideStr && c=='<') // potential start of html tag
1081 {
1082 if (data[i+1]=='/' &&
1083 tolower(data[i+2])=='p' && tolower(data[i+3])=='r' &&
1084 tolower(data[i+4])=='e' && tolower(data[i+5])=='>')
1085 { // found </pre> tag, copy from start to end of tag
1086 if (doWrite) out+=data.substr(0,i+6);
1087 //printf("found <pre>..</pre> [%d..%d]\n",0,i+6);
1088 AUTO_TRACE_EXIT("result={}",i+6);
1089 return static_cast<int>(i+6);
1090 }
1091 }
1092 else if (insideStr && c=='"')
1093 {
1094 if (data[i-1]!='\\') insideStr=false;
1095 }
1096 else if (c=='"')
1097 {
1098 insideStr=true;
1099 }
1100 i++;
1101 }
1102 }
1103 else // some other html tag
1104 {
1105 if (l>0 && i<size)
1106 {
1107 if (data[i]=='/' && i+1<size && data[i+1]=='>') // <bla/>
1108 {
1109 //printf("Found htmlTag={%s}\n",qPrint(DString(data).left(i+2)));
1110 if (doWrite) out+=data.substr(0,i+2);
1111 AUTO_TRACE_EXIT("result={}",i+2);
1112 return static_cast<int>(i+2);
1113 }
1114 else if (data[i]=='>') // <bla>
1115 {
1116 //printf("Found htmlTag={%s}\n",qPrint(DString(data).left(i+1)));
1117 if (doWrite) out+=data.substr(0,i+1);
1118 AUTO_TRACE_EXIT("result={}",i+1);
1119 return static_cast<int>(i+1);
1120 }
1121 else if (data[i]==' ') // <bla attr=...
1122 {
1123 i++;
1124 bool insideAttr=false;
1125 while (i<size)
1126 {
1127 if (!insideAttr && data[i]=='"')
1128 {
1129 insideAttr=true;
1130 }
1131 else if (data[i]=='"' && data[i-1]!='\\')
1132 {
1133 insideAttr=false;
1134 }
1135 else if (!insideAttr && data[i]=='>') // found end of tag
1136 {
1137 //printf("Found htmlTag={%s}\n",qPrint(DString(data).left(i+1)));
1138 if (doWrite) out+=data.substr(0,i+1);
1139 AUTO_TRACE_EXIT("result={}",i+1);
1140 return static_cast<int>(i+1);
1141 }
1142 i++;
1143 }
1144 }
1145 }
1146 }
1147 AUTO_TRACE_EXIT("not a valid html tag");
1148 return 0;
1149}
1150
1151int Markdown::Private::processHtmlTag(std::string_view data,size_t offset)
1152{
1153 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
1154 return processHtmlTagWrite(data,offset,true);
1155}
1156
1157int Markdown::Private::processEmphasis(std::string_view data,size_t offset)
1158{
1159 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
1160 const size_t size = data.size();
1161
1162 if (isAllowedEmphStr(data,offset) || // invalid char before * or _
1163 (size>1 && data[0]!=data[1] && !(isIdChar(data[1]) || extraChar(data[1]))) || // invalid char after * or _
1164 (size>2 && data[0]==data[1] && !(isIdChar(data[2]) || extraChar(data[2])))) // invalid char after ** or __
1165 {
1166 AUTO_TRACE_EXIT("invalid surrounding characters");
1167 return 0;
1168 }
1169
1170 char c = data[0];
1171 int ret = 0;
1172 if (size>2 && c!='~' && data[1]!=c) // _bla or *bla
1173 {
1174 // whitespace cannot follow an opening emphasis
1175 if (data[1]==' ' || data[1]=='\n' ||
1176 (ret = processEmphasis1(data.substr(1), c)) == 0)
1177 {
1178 return 0;
1179 }
1180 AUTO_TRACE_EXIT("result={}",ret+1);
1181 return ret+1;
1182 }
1183 if (size>3 && data[1]==c && data[2]!=c) // __bla or **bla
1184 {
1185 if (data[2]==' ' || data[2]=='\n' ||
1186 (ret = processEmphasis2(data.substr(2), c)) == 0)
1187 {
1188 return 0;
1189 }
1190 AUTO_TRACE_EXIT("result={}",ret+2);
1191 return ret+2;
1192 }
1193 if (size>4 && c!='~' && data[1]==c && data[2]==c && data[3]!=c) // ___bla or ***bla
1194 {
1195 if (data[3]==' ' || data[3]=='\n' ||
1196 (ret = processEmphasis3(data.substr(3), c)) == 0)
1197 {
1198 return 0;
1199 }
1200 AUTO_TRACE_EXIT("result={}",ret+3);
1201 return ret+3;
1202 }
1203 return 0;
1204}
1205
1207 std::string_view fmt, bool inline_img, bool explicitTitle,
1208 const DString &title, const DString &content,
1209 const DString &link, const DString &attrs,
1210 const FileDef *fd)
1211{
1212 AUTO_TRACE("fmt={} inline_img={} explicitTitle={} title={} content={} link={} attrs={}",
1213 fmt,inline_img,explicitTitle,Trace::trunc(title),Trace::trunc(content),link,attrs);
1214 DString attributes = getFilteredImageAttributes(fmt, attrs);
1215 out+="@image";
1216 if (inline_img)
1217 {
1218 out+="{inline}";
1219 }
1220 out+=" ";
1221 out+=fmt;
1222 out+=" ";
1223 out+=link.mid(fd ? 0 : 5);
1224 if (!explicitTitle && !content.empty())
1225 {
1226 out+=" \"";
1227 out+=escapeDoubleQuotes(content);
1228 out+="\"";
1229 }
1230 else if ((content.empty() || explicitTitle) && !title.empty())
1231 {
1232 out+=" \"";
1233 out+=escapeDoubleQuotes(title);
1234 out+="\"";
1235 }
1236 else
1237 {
1238 out+=" ";// so the line break will not be part of the image name
1239 }
1240 if (!attributes.empty())
1241 {
1242 out+=" ";
1243 out+=attributes;
1244 out+=" ";
1245 }
1246 out+="\\ilinebr ";
1247}
1248
1249int Markdown::Private::processLink(const std::string_view data,size_t offset)
1250{
1251 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
1252 const size_t size = data.size();
1253
1254 DString content;
1255 DString link;
1256 DString title;
1257 bool isImageLink = false;
1258 bool isImageInline = false;
1259 bool isToc = false;
1260 size_t i=1;
1261 if (data[0]=='!')
1262 {
1263 isImageLink = true;
1264 if (size<2 || data[1]!='[')
1265 {
1266 return 0;
1267 }
1268
1269 // if there is non-whitespace before the ![ within the scope of two new lines, the image
1270 // is considered inlined, i.e. the image is not preceded by an empty line
1271 int numNLsNeeded=2;
1272 int pos = -1;
1273 while (pos>=-static_cast<int>(offset) && numNLsNeeded>0)
1274 {
1275 if (data.data()[pos]=='\n') numNLsNeeded--;
1276 else if (data.data()[pos]!=' ') // found non-whitespace, stop searching
1277 {
1278 isImageInline=true;
1279 break;
1280 }
1281 pos--;
1282 }
1283 // skip '!['
1284 i++;
1285 }
1286 size_t contentStart=i;
1287 int level=1;
1288 int nlTotal=0;
1289 int nl=0;
1290 // find the matching ]
1291 while (i<size)
1292 {
1293 if (data[i-1]=='\\') // skip escaped characters
1294 {
1295 }
1296 else if (data[i]=='[')
1297 {
1298 level++;
1299 }
1300 else if (data[i]==']')
1301 {
1302 level--;
1303 if (level<=0) break;
1304 }
1305 else if (data[i]=='\n')
1306 {
1307 nl++;
1308 if (nl>1) { return 0; } // only allow one newline in the content
1309 }
1310 i++;
1311 }
1312 nlTotal += nl;
1313 nl = 0;
1314 if (i>=size) return 0; // premature end of comment -> no link
1315 size_t contentEnd=i;
1316 content = data.substr(contentStart,contentEnd-contentStart);
1317 //printf("processLink: content={%s}\n",qPrint(content));
1318 if (!isImageLink && content.empty()) { return 0; } // no link text
1319 i++; // skip over ]
1320
1321 bool whiteSpace = false;
1322 // skip whitespace
1323 while (i<size && data[i]==' ') { whiteSpace = true; i++; }
1324 if (i<size && data[i]=='\n') // one newline allowed here
1325 {
1326 whiteSpace = true;
1327 i++;
1328 // skip more whitespace
1329 while (i<size && data[i]==' ') i++;
1330 }
1331 if (whiteSpace && i<size && (data[i]=='(' || data[i]=='[')) return 0;
1332
1333 bool explicitTitle=false;
1334 if (i<size && data[i]=='(') // inline link
1335 {
1336 i++;
1337 while (i<size && data[i]==' ') i++;
1338 bool uriFormat=false;
1339 if (i<size && data[i]=='<') { i++; uriFormat=true; }
1340 size_t linkStart=i;
1341 int braceCount=1;
1342 int nlConsec = 0;
1343 while (i<size && data[i]!='\'' && data[i]!='"' && braceCount>0)
1344 {
1345 if (data[i]=='\n') // unexpected EOL
1346 {
1347 nl++;
1348 nlConsec++;
1349 if (nlConsec>1) { return 0; }
1350 }
1351 else if (data[i]=='(')
1352 {
1353 braceCount++;
1354 nlConsec = 0;
1355 }
1356 else if (data[i]==')')
1357 {
1358 braceCount--;
1359 nlConsec = 0;
1360 }
1361 else if (data[i]!=' ')
1362 {
1363 nlConsec = 0;
1364 }
1365 if (braceCount>0)
1366 {
1367 i++;
1368 }
1369 }
1370 nlTotal += nl;
1371 nl = 0;
1372 if (i>=size || data[i]=='\n') { return 0; }
1373 link = data.substr(linkStart,i-linkStart);
1374 link = link.stripWhiteSpace();
1375 //printf("processLink: link={%s}\n",qPrint(link));
1376 if (link.empty()) { return 0; }
1377 if (uriFormat && link.at(link.length()-1)=='>') link=link.left(link.length()-1);
1378
1379 // optional title
1380 if (data[i]=='\'' || data[i]=='"')
1381 {
1382 char c = data[i];
1383 i++;
1384 size_t titleStart=i;
1385 nl=0;
1386 while (i<size)
1387 {
1388 if (data[i]=='\n')
1389 {
1390 if (nl>1) { return 0; }
1391 nl++;
1392 }
1393 else if (data[i]=='\\') // escaped char in string
1394 {
1395 i++;
1396 }
1397 else if (data[i]==c)
1398 {
1399 i++;
1400 break;
1401 }
1402 i++;
1403 }
1404 if (i>=size)
1405 {
1406 return 0;
1407 }
1408 size_t titleEnd = i-1;
1409 // search back for closing marker
1410 while (titleEnd>titleStart && data[titleEnd]==' ') titleEnd--;
1411 if (data[titleEnd]==c) // found it
1412 {
1413 title = data.substr(titleStart,titleEnd-titleStart);
1414 explicitTitle=true;
1415 while (i<size)
1416 {
1417 if (data[i]==' ')i++; // remove space after the closing quote and the closing bracket
1418 else if (data[i] == ')') break; // the end bracket
1419 else // illegal
1420 {
1421 return 0;
1422 }
1423 }
1424 }
1425 else
1426 {
1427 return 0;
1428 }
1429 }
1430 i++;
1431 }
1432 else if (i<size && data[i]=='[') // reference link
1433 {
1434 i++;
1435 size_t linkStart=i;
1436 nl=0;
1437 // find matching ]
1438 while (i<size && data[i]!=']')
1439 {
1440 if (data[i]=='\n')
1441 {
1442 nl++;
1443 if (nl>1) { return 0; }
1444 }
1445 i++;
1446 }
1447 if (i>=size) { return 0; }
1448 // extract link
1449 link = data.substr(linkStart,i-linkStart);
1450 //printf("processLink: link={%s}\n",qPrint(link));
1451 link = link.stripWhiteSpace();
1452 if (link.empty()) // shortcut link
1453 {
1454 link=content;
1455 }
1456 // lookup reference
1457 DString link_lower = link.lower();
1458 auto lr_it=linkRefs.find(link_lower.str());
1459 if (lr_it!=linkRefs.end()) // found it
1460 {
1461 link = lr_it->second.link;
1462 title = lr_it->second.title;
1463 //printf("processLink: ref: link={%s} title={%s}\n",qPrint(link),qPrint(title));
1464 }
1465 else // reference not found!
1466 {
1467 //printf("processLink: ref {%s} do not exist\n",link.qPrint(lower()));
1468 return 0;
1469 }
1470 i++;
1471 }
1472 else if (i<size && data[i]!=':' && !content.empty()) // minimal link ref notation [some id]
1473 {
1474 DString content_lower = content.lower();
1475 auto lr_it = linkRefs.find(content_lower.str());
1476 //printf("processLink: minimal link {%s} lr=%p",qPrint(content),lr);
1477 if (lr_it!=linkRefs.end()) // found it
1478 {
1479 link = lr_it->second.link;
1480 title = lr_it->second.title;
1481 explicitTitle=true;
1482 i=contentEnd;
1483 }
1484 else if (content=="TOC")
1485 {
1486 isToc=true;
1487 i=contentEnd;
1488 }
1489 else
1490 {
1491 return 0;
1492 }
1493 i++;
1494 }
1495 else
1496 {
1497 return 0;
1498 }
1499 nlTotal += nl;
1500
1501 // search for optional image attributes
1502 DString attributes;
1503 if (isImageLink)
1504 {
1505 size_t j = i;
1506 // skip over whitespace
1507 while (j<size && data[j]==' ') { j++; }
1508 if (j<size && data[j]=='{') // we have attributes
1509 {
1510 i = j;
1511 // skip over '{'
1512 i++;
1513 size_t attributesStart=i;
1514 nl=0;
1515 // find the matching '}'
1516 while (i<size)
1517 {
1518 if (data[i-1]=='\\') // skip escaped characters
1519 {
1520 }
1521 else if (data[i]=='{')
1522 {
1523 level++;
1524 }
1525 else if (data[i]=='}')
1526 {
1527 level--;
1528 if (level<=0) break;
1529 }
1530 else if (data[i]=='\n')
1531 {
1532 nl++;
1533 if (nl>1) { return 0; } // only allow one newline in the content
1534 }
1535 i++;
1536 }
1537 nlTotal += nl;
1538 if (i>=size) return 0; // premature end of comment -> no attributes
1539 size_t attributesEnd=i;
1540 attributes = data.substr(attributesStart,attributesEnd-attributesStart);
1541 i++; // skip over '}'
1542 }
1543 if (!isImageInline)
1544 {
1545 // if there is non-whitespace after the image within the scope of two new lines, the image
1546 // is considered inlined, i.e. the image is not followed by an empty line
1547 int numNLsNeeded=2;
1548 size_t pos = i;
1549 while (pos<size && numNLsNeeded>0)
1550 {
1551 if (data[pos]=='\n') numNLsNeeded--;
1552 else if (data[pos]!=' ') // found non-whitespace, stop searching
1553 {
1554 isImageInline=true;
1555 break;
1556 }
1557 pos++;
1558 }
1559 }
1560 }
1561
1562 if (isToc) // special case for [TOC]
1563 {
1564 int toc_level = Config_getInt(TOC_INCLUDE_HEADINGS);
1565 if (toc_level>=SectionType::MinLevel && toc_level<=SectionType::MaxLevel)
1566 {
1567 out+="@tableofcontents{html:";
1568 out+=DString().setNum(toc_level);
1569 out+="}";
1570 }
1571 }
1572 else if (isImageLink)
1573 {
1574 bool ambig = false;
1575 FileDef *fd=nullptr;
1576 if (link.find("@ref ")!=DString::npos || link.find("\\ref ")!=DString::npos ||
1577 (fd=Doxygen::imageNameLinkedMap->findFileDef(link,ambig)))
1578 // assume doxygen symbol link or local image link
1579 {
1580 // check if different handling is needed per format
1581 writeMarkdownImage("html", isImageInline, explicitTitle, title, content, link, attributes, fd);
1582 writeMarkdownImage("latex", isImageInline, explicitTitle, title, content, link, attributes, fd);
1583 writeMarkdownImage("rtf", isImageInline, explicitTitle, title, content, link, attributes, fd);
1584 writeMarkdownImage("docbook", isImageInline, explicitTitle, title, content, link, attributes, fd);
1585 writeMarkdownImage("xml", isImageInline, explicitTitle, title, content, link, attributes, fd);
1586 }
1587 else
1588 {
1589 out+="<img src=\"";
1590 out+=link;
1591 out+="\" alt=\"";
1592 out+=content;
1593 out+="\"";
1594 if (!title.empty())
1595 {
1596 out+=" title=\"";
1597 out+=substitute(title.simplifyWhiteSpace(),"\"","&quot;");
1598 out+="\"";
1599 }
1600 out+="/>";
1601 }
1602 }
1603 else
1604 {
1606 size_t lp=DString::npos;
1607 if ((lp = link.find("@ref "))!=DString::npos ||
1608 (lp = link.find("\\ref "))!=DString::npos ||
1609 (lang==SrcLangExt::Markdown && !isURL(link)))
1610 // assume doxygen symbol link
1611 {
1612 if (lp==DString::npos) // link to markdown page
1613 {
1614 out+="@ref \"";
1615 if (!(Portable::isAbsolutePath(link) || isURL(link)))
1616 {
1617 FileInfo forg(link.str());
1618 if (forg.exists() && forg.isReadable())
1619 {
1620 link = forg.absFilePath();
1621 }
1622 else if (!(forg.exists() && forg.isReadable()))
1623 {
1624 FileInfo fi(fileName.str());
1625 DString mdFile = fileName.left(fileName.length()-fi.fileName().length()) + link;
1626 FileInfo fmd(mdFile.str());
1627 if (fmd.exists() && fmd.isReadable())
1628 {
1629 link = fmd.absFilePath().data();
1630 }
1631 }
1632 }
1633 out+=link;
1634 out+="\"";
1635 }
1636 else
1637 {
1638 out+=link;
1639 }
1640 out+=" \"";
1641 if (explicitTitle && !title.empty())
1642 {
1643 out+=substitute(title,"\"","&quot;");
1644 }
1645 else
1646 {
1647 processInline(std::string_view(substitute(content,"\"","&quot;").str()));
1648 }
1649 out+="\"";
1650 }
1651 else if ((lp = link.find('#'))!=DString::npos ||
1652 (link.find('/'))!=DString::npos ||
1653 (link.find('.'))!=DString::npos)
1654 { // file/url link
1655 bool isRef = false;
1656 if (lp==0 || (lp!=DString::npos && lp>0 && !isURL(link) && Config_getEnum(MARKDOWN_ID_STYLE)==MARKDOWN_ID_STYLE_t::GITHUB))
1657 {
1658 out+="@ref \"";
1660 out+="\" \"";
1661 out+=substitute(content.simplifyWhiteSpace(),"\"","&quot;");
1662 out+="\"";
1663 isRef = true;
1664 }
1665 else
1666 {
1667 out+="<a href=\"";
1668 out+=link;
1669 out+="\"";
1670 for (int ii = 0; ii < nlTotal; ii++) out+="\n";
1671 if (!title.empty())
1672 {
1673 out+=" title=\"";
1674 out+=substitute(title.simplifyWhiteSpace(),"\"","&quot;");
1675 out+="\"";
1676 }
1677 out+=" ";
1679 out+=">";
1680 }
1681
1682 content = content.simplifyWhiteSpace();
1683 bool foundNameRef = false;
1684 if (!content.empty() && (content.at(0)=='#' || content.at(0)=='@'))
1685 {
1686 size_t endOfId=1;
1687 while (endOfId<content.length() && isId(content.at(endOfId))) endOfId++;
1688 DString user = content.mid(1,endOfId-1);
1689 if (!user.empty() && (content.at(0)=='#' || (!CommentScanner::isCommand(user) && Mappers::cmdMapper->map(user)==CommandType::UNKNOWN)))
1690 {
1691 // assume @name or #name instead of command
1692 out+='@';
1693 out+=content;
1694 foundNameRef = true;
1695 }
1696 }
1697 if (!isRef)
1698 {
1699 if (!foundNameRef)
1700 {
1701 processInline(std::string_view(content.str()));
1702 }
1703 out+="</a>";
1704 }
1705 }
1706 else // avoid link to e.g. F[x](y)
1707 {
1708 //printf("no link for '%s'\n",qPrint(link));
1709 return 0;
1710 }
1711 }
1712 AUTO_TRACE_EXIT("result={}",i);
1713 return static_cast<int>(i);
1714}
1715
1716/** `` ` `` parsing a code span (assuming codespan != 0) */
1717int Markdown::Private::processCodeSpan(std::string_view data,size_t offset)
1718{
1719 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
1720 const size_t size = data.size();
1721
1722 /* counting the number of backticks in the delimiter */
1723 size_t nb=0, end=0;
1724 while (nb<size && data[nb]=='`')
1725 {
1726 nb++;
1727 }
1728
1729 /* finding the next delimiter with the same amount of backticks */
1730 size_t i = 0;
1731 char pc = '`';
1732 bool markdownStrict = Config_getBool(MARKDOWN_STRICT);
1733 for (end=nb; end<size; end++)
1734 {
1735 //AUTO_TRACE_ADD("c={} nb={} i={} size={}",data[end],nb,i,size);
1736 if (data[end]=='`')
1737 {
1738 i++;
1739 if (nb==1) // `...`
1740 {
1741 if (end+1<size && data[end+1]=='`') // skip over `` inside `...`
1742 {
1743 AUTO_TRACE_ADD("case1.1");
1744 // skip
1745 end++;
1746 i=0;
1747 }
1748 else // normal end of `...`
1749 {
1750 AUTO_TRACE_ADD("case1.2");
1751 break;
1752 }
1753 }
1754 else if (i==nb) // ``...``
1755 {
1756 if (end+1<size && data[end+1]=='`') // do greedy match
1757 {
1758 // skip this quote and use the next one to terminate the sequence, e.g. ``X`Y```
1759 i--;
1760 AUTO_TRACE_ADD("case2.1");
1761 }
1762 else // normal end of ``...``
1763 {
1764 AUTO_TRACE_ADD("case2.2");
1765 break;
1766 }
1767 }
1768 }
1769 else if (data[end]=='\n')
1770 {
1771 // consecutive newlines
1772 if (pc == '\n')
1773 {
1774 AUTO_TRACE_EXIT("new paragraph");
1775 return 0;
1776 }
1777 pc = '\n';
1778 i = 0;
1779 }
1780 else if (!markdownStrict && data[end]=='\'' && nb==1 && (end+1==size || (end+1<size && data[end+1]!='\'' && !isIdChar(data[end+1]))))
1781 { // look for quoted strings like 'some word', but skip strings like `it's cool`
1782 out+="&lsquo;";
1783 out+=data.substr(nb,end-nb);
1784 out+="&rsquo;";
1785 AUTO_TRACE_EXIT("quoted end={}",end+1);
1786 return static_cast<int>(end+1);
1787 }
1788 else if (!markdownStrict && data[end]=='\'' && nb==2 && end+1<size && data[end+1]=='\'')
1789 { // look for '' to match a ``
1790 out+="&ldquo;";
1791 out+=data.substr(nb,end-nb);
1792 out+="&rdquo;";
1793 AUTO_TRACE_EXIT("double quoted end={}",end+1);
1794 return static_cast<int>(end+2);
1795 }
1796 else
1797 {
1798 if (data[end]!=' ') pc = data[end];
1799 i=0;
1800 }
1801 }
1802 if (i < nb && end >= size)
1803 {
1804 AUTO_TRACE_EXIT("no matching delimiter nb={} i={}",nb,i);
1805 if (nb>=3) // found ``` that is not at the start of the line, keep it as-is.
1806 {
1807 out+=data.substr(0,nb);
1808 return static_cast<int>(nb);
1809 }
1810 return 0; // no matching delimiter
1811 }
1812 while (end<size && data[end]=='`') // do greedy match in case we have more end backticks.
1813 {
1814 end++;
1815 }
1816
1817 //printf("found code span '%s'\n",qPrint(DString(data+f_begin).left(f_end-f_begin)));
1818
1819 /* real code span */
1820 if (nb+nb < end)
1821 {
1822 DString codeFragment = data.substr(nb, end-nb-nb);
1823 out+="<tt>";
1824 out+=escapeSpecialChars(codeFragment);
1825 out+="</tt>";
1826 }
1827 AUTO_TRACE_EXIT("result={} nb={}",end,nb);
1828 return static_cast<int>(end);
1829}
1830
1832{
1833 AUTO_TRACE("{}",Trace::trunc(data));
1834 if (Portable::strnstr(data.data(),g_doxy_nbsp,data.size())==nullptr) // no escape needed -> fast
1835 {
1836 out+=data;
1837 }
1838 else // escape needed -> slow
1839 {
1841 }
1842}
1843
1844int Markdown::Private::processSpecialCommand(std::string_view data, size_t offset)
1845{
1846 AUTO_TRACE("{}",Trace::trunc(data));
1847 const size_t size = data.size();
1848 size_t i=1;
1849 DString endBlockName = isBlockCommand(data,offset);
1850 if (!endBlockName.empty())
1851 {
1852 AUTO_TRACE_ADD("endBlockName={}",endBlockName);
1853 size_t l = endBlockName.length();
1854 while (i+l<size)
1855 {
1856 if ((data[i]=='\\' || data[i]=='@') && // command
1857 data[i-1]!='\\' && data[i-1]!='@') // not escaped
1858 {
1859 if (dstrncmp(&data[i+1],endBlockName.data(),l)==0)
1860 {
1861 //printf("found end at %d\n",i);
1862 addStrEscapeUtf8Nbsp(data.substr(0,i+1+l));
1863 AUTO_TRACE_EXIT("result={}",i+1+l);
1864 return static_cast<int>(i+1+l);
1865 }
1866 }
1867 i++;
1868 }
1869 }
1870 size_t endPos = isSpecialCommand(data,offset);
1871 if (endPos>0)
1872 {
1873 out+=data.substr(0,endPos);
1874 return static_cast<int>(endPos);
1875 }
1876 if (size>1 && (data[0]=='\\' || data[0]=='@')) // escaped characters
1877 {
1878 char c=data[1];
1879 if (c=='[' || c==']' || c=='*' || c=='(' || c==')' || c=='`' || c=='_')
1880 {
1881 out+=data[1];
1882 AUTO_TRACE_EXIT("2");
1883 return 2;
1884 }
1885 else if (c=='\\' || c=='@')
1886 {
1887 out+=data.substr(0,2);
1888 AUTO_TRACE_EXIT("2");
1889 return 2;
1890 }
1891 else if (c=='-' && size>3 && data[2]=='-' && data[3]=='-') // \---
1892 {
1893 out+=data.substr(1,3);
1894 AUTO_TRACE_EXIT("2");
1895 return 4;
1896 }
1897 else if (c=='-' && size>2 && data[2]=='-') // \--
1898 {
1899 out+=data.substr(1,2);
1900 AUTO_TRACE_EXIT("3");
1901 return 3;
1902 }
1903 }
1904 return 0;
1905}
1906
1907void Markdown::Private::processInline(std::string_view data)
1908{
1909 AUTO_TRACE("data='{}'",Trace::trunc(data));
1910 size_t i=0;
1911 size_t end=0;
1912 Action_t action;
1913 const size_t size = data.size();
1914 while (i<size)
1915 {
1916 // skip over characters that do not trigger a specific action
1917 while (end<size && ((action=Markdown::actions[static_cast<uint8_t>(data[end])])==nullptr)) end++;
1918 // and add them to the output
1919 out+=data.substr(i,end-i);
1920 if (end>=size) break;
1921 i=end;
1922 // do the action matching a special character at i
1923 int iend = action(*this,data.substr(i),i);
1924 if (iend<=0) // update end
1925 {
1926 end=i+1-iend;
1927 }
1928 else // skip until end
1929 {
1930 i+=iend;
1931 end=i;
1932 }
1933 }
1934}
1935
1936/** returns whether the line is a setext-style hdr underline */
1937int Markdown::Private::isHeaderline(std::string_view data, bool allowAdjustLevel)
1938{
1939 AUTO_TRACE("data='{}' allowAdjustLevel",Trace::trunc(data),allowAdjustLevel);
1940 size_t i=0, c=0;
1941 const size_t size = data.size();
1942 while (i<size && data[i]==' ') i++;
1943 if (i==size) return 0;
1944
1945 // test of level 1 header
1946 if (data[i]=='=')
1947 {
1948 while (i < size && data[i] == '=')
1949 {
1950 i++;
1951 c++;
1952 }
1953 while (i<size && data[i]==' ') i++;
1954 int level = (c>1 && (i>=size || data[i]=='\n')) ? 1 : 0;
1955 if (allowAdjustLevel && level==1 && indentLevel==-1)
1956 {
1957 // In case a page starts with a header line we use it as title, promoting it to @page.
1958 // We set g_indentLevel to -1 to promoting the other sections if they have a deeper
1959 // nesting level than the page header, i.e. @section..@subsection becomes @page..@section.
1960 // In case a section at the same level is found (@section..@section) however we need
1961 // to undo this (and the result will be @page..@section).
1962 indentLevel=0;
1963 }
1964 AUTO_TRACE_EXIT("result={}",indentLevel+level);
1965 return indentLevel+level;
1966 }
1967 // test of level 2 header
1968 if (data[i]=='-')
1969 {
1970 while (i < size && data[i] == '-')
1971 {
1972 i++;
1973 c++;
1974 }
1975 while (i<size && data[i]==' ') i++;
1976 return (c>1 && (i>=size || data[i]=='\n')) ? indentLevel+2 : 0;
1977 }
1978 return 0;
1979}
1980
1981/** returns true if this line starts a block quote */
1982static bool isBlockQuote(std::string_view data,size_t indent)
1983{
1984 AUTO_TRACE("data='{}' indent={}",Trace::trunc(data),indent);
1985 size_t i = 0;
1986 const size_t size = data.size();
1987 while (i<size && data[i]==' ') i++;
1988 if (i<indent+codeBlockIndent) // could be a quotation
1989 {
1990 // count >'s and skip spaces
1991 int level=0;
1992 while (i<size && (data[i]=='>' || data[i]==' '))
1993 {
1994 if (data[i]=='>') level++;
1995 i++;
1996 }
1997 // last characters should be a space or newline,
1998 // so a line starting with >= does not match, but only when level equals 1
1999 bool res = (level>0 && i<size && ((data[i-1]==' ') || data[i]=='\n')) || (level > 1);
2000 AUTO_TRACE_EXIT("result={}",res);
2001 return res;
2002 }
2003 else // too much indentation -> code block
2004 {
2005 AUTO_TRACE_EXIT("result=false: too much indentation");
2006 return false;
2007 }
2008}
2009
2010/** returns end of the link ref if this is indeed a link reference. */
2011static size_t isLinkRef(std::string_view data, DString &refid, DString &link, DString &title)
2012{
2013 AUTO_TRACE("data='{}'",Trace::trunc(data));
2014 const size_t size = data.size();
2015 // format: start with [some text]:
2016 size_t i = 0;
2017 while (i<size && data[i]==' ') i++;
2018 if (i>=size || data[i]!='[') { return 0; }
2019 i++;
2020 size_t refIdStart=i;
2021 while (i<size && data[i]!='\n' && data[i]!=']') i++;
2022 if (i>=size || data[i]!=']') { return 0; }
2023 refid = data.substr(refIdStart,i-refIdStart);
2024 if (refid.empty()) { return 0; }
2025 AUTO_TRACE_ADD("refid found {}",refid);
2026 //printf(" isLinkRef: found refid='%s'\n",qPrint(refid));
2027 i++;
2028 if (i>=size || data[i]!=':') { return 0; }
2029 i++;
2030
2031 // format: whitespace* \n? whitespace* (<url> | url)
2032 while (i<size && data[i]==' ') i++;
2033 if (i<size && data[i]=='\n')
2034 {
2035 i++;
2036 while (i<size && data[i]==' ') i++;
2037 }
2038 if (i>=size) { return 0; }
2039
2040 if (i<size && data[i]=='<') i++;
2041 size_t linkStart=i;
2042 while (i<size && data[i]!=' ' && data[i]!='\n') i++;
2043 size_t linkEnd=i;
2044 if (i<size && data[i]=='>') i++;
2045 if (linkStart==linkEnd) { return 0; } // empty link
2046 link = data.substr(linkStart,linkEnd-linkStart);
2047 AUTO_TRACE_ADD("link found {}",Trace::trunc(link));
2048 if (link=="@ref" || link=="\\ref")
2049 {
2050 size_t argStart=i;
2051 while (i<size && data[i]!='\n' && data[i]!='"') i++;
2052 link+=data.substr(argStart,i-argStart);
2053 }
2054
2055 title.clear();
2056
2057 // format: (whitespace* \n? whitespace* ( 'title' | "title" | (title) ))?
2058 size_t eol=0;
2059 while (i<size && data[i]==' ') i++;
2060 if (i<size && data[i]=='\n')
2061 {
2062 eol=i;
2063 i++;
2064 while (i<size && data[i]==' ') i++;
2065 }
2066 if (i>=size)
2067 {
2068 AUTO_TRACE_EXIT("result={}: end of isLinkRef while looking for title",i);
2069 return i; // end of buffer while looking for the optional title
2070 }
2071
2072 char c = data[i];
2073 if (c=='\'' || c=='"' || c=='(') // optional title present?
2074 {
2075 //printf(" start of title found! char='%c'\n",c);
2076 i++;
2077 if (c=='(') c=')'; // replace c by end character
2078 size_t titleStart=i;
2079 // search for end of the line
2080 while (i<size && data[i]!='\n') i++;
2081 eol = i;
2082
2083 // search back to matching character
2084 size_t end=i-1;
2085 while (end>titleStart && data[end]!=c) end--;
2086 if (end>titleStart)
2087 {
2088 title = data.substr(titleStart,end-titleStart);
2089 }
2090 AUTO_TRACE_ADD("title found {}",Trace::trunc(title));
2091 }
2092 while (i<size && data[i]==' ') i++;
2093 //printf("end of isLinkRef: i=%d size=%d data[i]='%c' eol=%d\n",
2094 // i,size,data[i],eol);
2095 if (i>=size) { AUTO_TRACE_EXIT("result={}",i); return i; } // end of buffer while ref id was found
2096 else if (eol>0) { AUTO_TRACE_EXIT("result={}",eol); return eol; } // end of line while ref id was found
2097 return 0; // invalid link ref
2098}
2099
2100static bool isHRuler(std::string_view data)
2101{
2102 AUTO_TRACE("data='{}'",Trace::trunc(data));
2103 size_t i=0;
2104 size_t size = data.size();
2105 if (size>0 && data[size-1]=='\n') size--; // ignore newline character
2106 while (i<size && data[i]==' ') i++;
2107 if (i>=size) { AUTO_TRACE_EXIT("result=false: empty line"); return false; } // empty line
2108 char c=data[i];
2109 if (c!='*' && c!='-' && c!='_')
2110 {
2111 AUTO_TRACE_EXIT("result=false: {} is not a hrule character",c);
2112 return false; // not a hrule character
2113 }
2114 int n=0;
2115 while (i<size)
2116 {
2117 if (data[i]==c)
2118 {
2119 n++; // count rule character
2120 }
2121 else if (data[i]!=' ')
2122 {
2123 AUTO_TRACE_EXIT("result=false: line contains non hruler characters");
2124 return false; // line contains non hruler characters
2125 }
2126 i++;
2127 }
2128 AUTO_TRACE_EXIT("result={}",n>=3);
2129 return n>=3; // at least 3 characters needed for a hruler
2130}
2131
2132DString Markdown::Private::extractTitleId(DString &title, int level, bool *pIsIdGenerated)
2133{
2134 AUTO_TRACE("title={} level={}",Trace::trunc(title),level);
2135 // match e.g. '{#id-b11} ' and capture 'id-b11'
2136 static const reg::Ex r2(R"({#(\a[\w-]*)}\s*$)");
2137 reg::Match match;
2138 std::string ti = title.str();
2139 if (reg::search(ti,match,r2))
2140 {
2141 std::string id = match[1].str();
2142 title = title.left(match.position());
2143 if (AnchorGenerator::instance().reserve(id)>0)
2144 {
2145 warn(fileName, lineNr, "An automatically generated id already has the name '{}'!", id);
2146 }
2147 //printf("found match id='%s' title=%s\n",qPrint(id),qPrint(title));
2148 AUTO_TRACE_EXIT("id={}",id);
2149 return id;
2150 }
2151 if (((level>0) && (level<=Config_getInt(TOC_INCLUDE_HEADINGS))) || (Config_getEnum(MARKDOWN_ID_STYLE)==MARKDOWN_ID_STYLE_t::GITHUB))
2152 {
2154 if (pIsIdGenerated) *pIsIdGenerated=true;
2155 //printf("auto-generated id='%s' title='%s'\n",qPrint(id),qPrint(title));
2156 AUTO_TRACE_EXIT("id={}",id);
2157 return id;
2158 }
2159 //printf("no id found in title '%s'\n",qPrint(title));
2160 return "";
2161}
2162
2163
2164int Markdown::Private::isAtxHeader(std::string_view data,
2165 DString &header,DString &id,bool allowAdjustLevel,bool *pIsIdGenerated)
2166{
2167 AUTO_TRACE("data='{}' header={} id={} allowAdjustLevel={}",Trace::trunc(data),Trace::trunc(header),id,allowAdjustLevel);
2168 size_t i = 0;
2169 int level = 0, blanks=0;
2170 const size_t size = data.size();
2171
2172 // find start of header text and determine heading level
2173 while (i<size && data[i]==' ') i++;
2174 if (i>=size || data[i]!='#')
2175 {
2176 return 0;
2177 }
2178 while (i < size && data[i] == '#')
2179 {
2180 i++;
2181 level++;
2182 }
2183 if (level>SectionType::MaxLevel) // too many #'s -> no section
2184 {
2185 return 0;
2186 }
2187 while (i < size && data[i] == ' ')
2188 {
2189 i++;
2190 blanks++;
2191 }
2192 if (level==1 && blanks==0)
2193 {
2194 return 0; // special case to prevent #someid seen as a header (see bug 671395)
2195 }
2196
2197 // find end of header text
2198 size_t end=i;
2199 while (end<size && data[end]!='\n') end++;
2200 while (end>i && (data[end-1]=='#' || data[end-1]==' ')) end--;
2201
2202 // store result
2203 header = data.substr(i,end-i);
2204 id = extractTitleId(header, level, pIsIdGenerated);
2205 if (!id.empty()) // strip #'s between title and id
2206 {
2207 int idx=static_cast<int>(header.length())-1;
2208 while (idx>=0 && (header.at(idx)=='#' || header.at(idx)==' ')) idx--;
2209 header=header.left(idx+1);
2210 }
2211
2212 if (allowAdjustLevel && level==1 && indentLevel==-1)
2213 {
2214 // in case we find a `# Section` on a markdown page that started with the same level
2215 // header, we no longer need to artificially decrease the paragraph level.
2216 // So both
2217 // -------------------
2218 // # heading 1 <-- here we set g_indentLevel to -1
2219 // # heading 2 <-- here we set g_indentLevel back to 0 such that this will be a @section
2220 // -------------------
2221 // and
2222 // -------------------
2223 // # heading 1 <-- here we set g_indentLevel to -1
2224 // ## heading 2 <-- here we keep g_indentLevel at -1 such that @subsection will be @section
2225 // -------------------
2226 // will convert to
2227 // -------------------
2228 // @page md_page Heading 1
2229 // @section autotoc_md1 Heading 2
2230 // -------------------
2231
2232 indentLevel=0;
2233 }
2234 int res = level+indentLevel;
2235 AUTO_TRACE_EXIT("result={}",res);
2236 return res;
2237}
2238
2239static bool isEmptyLine(std::string_view data)
2240{
2241 AUTO_TRACE("data='{}'",Trace::trunc(data));
2242 size_t i=0;
2243 while (i<data.size())
2244 {
2245 if (data[i]=='\n') { AUTO_TRACE_EXIT("true"); return true; }
2246 if (data[i]!=' ') { AUTO_TRACE_EXIT("false"); return false; }
2247 i++;
2248 }
2249 AUTO_TRACE_EXIT("true");
2250 return true;
2251}
2252
2253#define isLiTag(i) \
2254 (data[(i)]=='<' && \
2255 (data[(i)+1]=='l' || data[(i)+1]=='L') && \
2256 (data[(i)+2]=='i' || data[(i)+2]=='I') && \
2257 (data[(i)+3]=='>'))
2258
2259// compute the indent from the start of the input, excluding list markers
2260// such as -, -#, *, +, 1., and <li>
2261static size_t computeIndentExcludingListMarkers(std::string_view data)
2262{
2263 AUTO_TRACE("data='{}'",Trace::trunc(data));
2264 size_t i=0;
2265 const size_t size=data.size();
2266 size_t indent=0;
2267 bool isDigit=false;
2268 bool isLi=false;
2269 bool listMarkerSkipped=false;
2270 while (i<size &&
2271 (data[i]==' ' || // space
2272 (!listMarkerSkipped && // first list marker
2273 (data[i]=='+' || data[i]=='-' || data[i]=='*' || // unordered list char
2274 (data[i]=='#' && i>0 && data[i-1]=='-') || // -# item
2275 (isDigit=(data[i]>='1' && data[i]<='9')) || // ordered list marker?
2276 (isLi=(size>=3 && i+3<size && isLiTag(i))) // <li> tag
2277 )
2278 )
2279 )
2280 )
2281 {
2282 if (isDigit) // skip over ordered list marker '10. '
2283 {
2284 size_t j=i+1;
2285 while (j<size && ((data[j]>='0' && data[j]<='9') || data[j]=='.'))
2286 {
2287 if (data[j]=='.') // should be end of the list marker
2288 {
2289 if (j+1<size && data[j+1]==' ') // valid list marker
2290 {
2291 listMarkerSkipped=true;
2292 indent+=j+1-i;
2293 i=j+1;
2294 break;
2295 }
2296 else // not a list marker
2297 {
2298 break;
2299 }
2300 }
2301 j++;
2302 }
2303 }
2304 else if (isLi)
2305 {
2306 i+=3; // skip over <li>
2307 indent+=3;
2308 listMarkerSkipped=true;
2309 }
2310 else if (data[i]=='-' && size>=2 && i+2<size && data[i+1]=='#' && data[i+2]==' ')
2311 { // case "-# "
2312 listMarkerSkipped=true; // only a single list marker is accepted
2313 i++; // skip over #
2314 indent++;
2315 }
2316 else if (data[i]!=' ' && i+1<size && data[i+1]==' ')
2317 { // case "- " or "+ " or "* "
2318 listMarkerSkipped=true; // only a single list marker is accepted
2319 }
2320 if (data[i]!=' ' && !listMarkerSkipped)
2321 { // end of indent
2322 break;
2323 }
2324 indent++;
2325 i++;
2326 }
2327 AUTO_TRACE_EXIT("result={}",indent);
2328 return indent;
2329}
2330
2331static size_t isListMarker(std::string_view data)
2332{
2333 AUTO_TRACE("data='{}'",Trace::trunc(data));
2334 size_t normalIndent = 0;
2335 while (normalIndent<data.size() && data[normalIndent]==' ') normalIndent++;
2336 size_t listIndent = computeIndentExcludingListMarkers(data);
2337 size_t result = listIndent>normalIndent ? listIndent : 0;
2338 AUTO_TRACE_EXIT("result={}",result);
2339 return result;
2340}
2341
2342static bool isEndOfList(std::string_view data)
2343{
2344 AUTO_TRACE("data='{}'",Trace::trunc(data));
2345 int dots=0;
2346 size_t i=0;
2347 // end of list marker is an otherwise empty line with a dot.
2348 while (i<data.size())
2349 {
2350 if (data[i]=='.')
2351 {
2352 dots++;
2353 }
2354 else if (data[i]=='\n')
2355 {
2356 break;
2357 }
2358 else if (data[i]!=' ' && data[i]!='\t') // bail out if the line is not empty
2359 {
2360 AUTO_TRACE_EXIT("result=false");
2361 return false;
2362 }
2363 i++;
2364 }
2365 AUTO_TRACE_EXIT("result={}",dots==1);
2366 return dots==1;
2367}
2368
2369static bool isFencedCodeBlock(std::string_view data,size_t refIndent,
2370 DString &lang,size_t &start,size_t &end,size_t &offset,
2371 DString &fileName,int lineNr)
2372{
2373 AUTO_TRACE("data='{}' refIndent={}",Trace::trunc(data),refIndent);
2374 const char dot = '.';
2375 auto isAlphaChar = [ ](char c) { return (c>='A' && c<='Z') || (c>='a' && c<='z'); };
2376 auto isAlphaNChar = [ ](char c) { return (c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9') || (c=='+'); };
2377 auto isLangChar = [&](char c) { return c==dot || isAlphaChar(c); };
2378 // rules: at least 3 ~~~, end of the block same amount of ~~~'s, otherwise
2379 // return false
2380 size_t i=0;
2381 size_t indent=0;
2382 int startTildes=0;
2383 const size_t size = data.size();
2384 while (i < size && data[i] == ' ')
2385 {
2386 indent++;
2387 i++;
2388 }
2389 if (indent>=refIndent+4)
2390 {
2391 AUTO_TRACE_EXIT("result=false: content is part of code block indent={} refIndent={}",indent,refIndent);
2392 return false;
2393 } // part of code block
2394 char tildaChar='~';
2395 if (i<size && data[i]=='`') tildaChar='`';
2396 while (i < size && data[i] == tildaChar)
2397 {
2398 startTildes++;
2399 i++;
2400 }
2401 if (startTildes<3)
2402 {
2403 AUTO_TRACE_EXIT("result=false: no fence marker found #tildes={}",startTildes);
2404 return false;
2405 } // not enough tildes
2406 // skip whitespace
2407 while (i<size && data[i]==' ') { i++; }
2408 if (i<size && data[i]=='{') // extract .py from ```{.py} ... ```
2409 {
2410 i++; // skip over {
2411 if (data[i] == dot) i++; // skip over initial dot
2412 size_t startLang=i;
2413 while (i<size && (data[i]!='\n' && data[i]!='}')) i++; // find matching }
2414 if (i<size && data[i]=='}')
2415 {
2416 lang = data.substr(startLang,i-startLang);
2417 i++;
2418 }
2419 else // missing closing bracket, treat `{` as part of the content
2420 {
2421 i=startLang-1;
2422 lang="";
2423 }
2424 }
2425 else if (i<size && isLangChar(data[i])) /// extract python or .py from ```python...``` or ```.py...```
2426 {
2427 if (data[i] == dot) i++; // skip over initial dot
2428 size_t startLang=i;
2429 if (i<size && isAlphaChar(data[i])) //check first character of language specifier
2430 {
2431 i++;
2432 while (i<size && isAlphaNChar(data[i])) i++; // find end of language specifier
2433 }
2434 lang = data.substr(startLang,i-startLang);
2435 }
2436 else // no language specified
2437 {
2438 lang="";
2439 }
2440
2441 start=i;
2442 while (i<size)
2443 {
2444 if (data[i]==tildaChar)
2445 {
2446 end=i;
2447 int endTildes=0;
2448 while (i < size && data[i] == tildaChar)
2449 {
2450 endTildes++;
2451 i++;
2452 }
2453 while (i<size && data[i]==' ') i++;
2454 {
2455 if (endTildes==startTildes)
2456 {
2457 offset=i;
2458 AUTO_TRACE_EXIT("result=true: found end marker at offset {} lang='{}'",offset,lang);
2459 return true;
2460 }
2461 }
2462 }
2463 i++;
2464 }
2465 warn(fileName, lineNr, "Ending Inside a fenced code block. Maybe the end marker for the block is missing?");
2466 AUTO_TRACE_EXIT("result=false: no end marker found lang={}'",lang);
2467 return false;
2468}
2469
2470static bool isCodeBlock(std::string_view data, size_t offset,size_t &indent)
2471{
2472 AUTO_TRACE("data='{}' offset={}",Trace::trunc(data),offset);
2473 //printf("<isCodeBlock(offset=%d,size=%d,indent=%d)\n",offset,size,indent);
2474 // determine the indent of this line
2475 size_t i=0;
2476 size_t indent0=0;
2477 const size_t size = data.size();
2478 while (i < size && data[i] == ' ')
2479 {
2480 indent0++;
2481 i++;
2482 }
2483
2484 if (indent0<codeBlockIndent)
2485 {
2486 AUTO_TRACE_EXIT("result={}: line is not indented enough {}<4",false,indent0);
2487 return false;
2488 }
2489 if (indent0>=size || data[indent0]=='\n') // empty line does not start a code block
2490 {
2491 AUTO_TRACE_EXIT("result={}: only spaces at the end of a comment block",false);
2492 return false;
2493 }
2494
2495 i=offset;
2496 int nl=0;
2497 int nl_pos[3];
2498 int offset_i = static_cast<int>(offset);
2499 // search back 3 lines and remember the start of lines -1 and -2
2500 while (i>0 && nl<3) // i counts down from offset to 1
2501 {
2502 int j = static_cast<int>(i)-offset_i-1; // j counts from -1 to -offset
2503 // since j can be negative we need to rewrap data in a std::string_view
2504 size_t nl_size = isNewline(std::string_view(data.data()+j,data.size()-j));
2505 if (nl_size>0)
2506 {
2507 nl_pos[nl++]=j+static_cast<int>(nl_size);
2508 }
2509 i--;
2510 }
2511
2512 // if there are only 2 preceding lines, then line -2 starts at -offset
2513 if (i==0 && nl==2) nl_pos[nl++]=-offset_i;
2514
2515 if (nl==3) // we have at least 2 preceding lines
2516 {
2517 //printf(" positions: nl_pos=[%d,%d,%d] line[-2]='%s' line[-1]='%s'\n",
2518 // nl_pos[0],nl_pos[1],nl_pos[2],
2519 // qPrint(DString(data+nl_pos[1]).left(nl_pos[0]-nl_pos[1]-1)),
2520 // qPrint(DString(data+nl_pos[2]).left(nl_pos[1]-nl_pos[2]-1)));
2521
2522 // check that line -1 is empty
2523 // Note that the offset is negative so we need to rewrap the string view
2524 if (!isEmptyLine(std::string_view(data.data()+nl_pos[1],nl_pos[0]-nl_pos[1]-1)))
2525 {
2526 AUTO_TRACE_EXIT("result={}",false);
2527 return false;
2528 }
2529
2530 // determine the indent of line -2
2531 // Note that the offset is negative so we need to rewrap the string view
2532 indent=std::max(indent,computeIndentExcludingListMarkers(
2533 std::string_view(data.data()+nl_pos[2],nl_pos[1]-nl_pos[2])));
2534
2535 //printf(">isCodeBlock local_indent %d>=%d+%d=%d\n",
2536 // indent0,indent,codeBlockIndent,indent0>=indent+codeBlockIndent);
2537 // if the difference is >4 spaces -> code block
2538 bool res = indent0>=indent+codeBlockIndent;
2539 AUTO_TRACE_EXIT("result={}: code block if indent difference >4 spaces",res);
2540 return res;
2541 }
2542 else // not enough lines to determine the relative indent, use global indent
2543 {
2544 // check that line -1 is empty
2545 // Note that the offset is negative so we need to rewrap the string view
2546 if (nl==1 && !isEmptyLine(std::string_view(data.data()-offset,offset-1)))
2547 {
2548 AUTO_TRACE_EXIT("result=false");
2549 return false;
2550 }
2551 //printf(">isCodeBlock global indent %d>=%d+4=%d nl=%d\n",
2552 // indent0,indent,indent0>=indent+4,nl);
2553 bool res = indent0>=indent+codeBlockIndent;
2554 AUTO_TRACE_EXIT("result={}: code block if indent difference >4 spaces",res);
2555 return res;
2556 }
2557}
2558
2559/** Finds the location of the table's contains in the string \a data.
2560 * Only one line will be inspected.
2561 * @param[in] data pointer to the string buffer.
2562 * @param[out] start offset of the first character of the table content
2563 * @param[out] end offset of the last character of the table content
2564 * @param[out] columns number of table columns found
2565 * @returns The offset until the next line in the buffer.
2566 */
2567static size_t findTableColumns(std::string_view data,size_t &start,size_t &end,size_t &columns)
2568{
2569 AUTO_TRACE("data='{}'",Trace::trunc(data));
2570 const size_t size = data.size();
2571 size_t i=0,n=0;
2572 // find start character of the table line
2573 while (i<size && data[i]==' ') i++;
2574 if (i < size && data[i] == '|' && data[i] != '\n')
2575 {
2576 i++;
2577 n++; // leading | does not count
2578 }
2579 start = i;
2580
2581 // find end character of the table line
2582 size_t j = 0;
2583 while (i<size && (j = isNewline(data.substr(i)))==0) i++;
2584 size_t eol=i+j;
2585
2586 if (j>0 && i>0) i--; // move i to point before newline
2587 while (i>0 && data[i]==' ') i--;
2588 if (i > 0 && data[i - 1] != '\\' && data[i] == '|')
2589 {
2590 i--;
2591 n++; // trailing or escaped | does not count
2592 }
2593 end = i;
2594
2595 // count columns between start and end
2596 columns=0;
2597 if (end>start)
2598 {
2599 i=start;
2600 while (i<=end) // look for more column markers
2601 {
2602 if (data[i]=='|' && (i==0 || data[i-1]!='\\')) columns++;
2603 if (columns==1) columns++; // first | make a non-table into a two column table
2604 i++;
2605 }
2606 }
2607 if (n==2 && columns==0) // table row has | ... |
2608 {
2609 columns++;
2610 }
2611 AUTO_TRACE_EXIT("eol={} start={} end={} columns={}",eol,start,end,columns);
2612 return eol;
2613}
2614
2615/** Returns true iff data points to the start of a table block */
2616static bool isTableBlock(std::string_view data)
2617{
2618 AUTO_TRACE("data='{}'",Trace::trunc(data));
2619 size_t cc0=0, start=0, end=0;
2620
2621 // the first line should have at least two columns separated by '|'
2622 size_t i = findTableColumns(data,start,end,cc0);
2623 if (i>=data.size() || cc0<1)
2624 {
2625 AUTO_TRACE_EXIT("result=false: no |'s in the header");
2626 return false;
2627 }
2628
2629 size_t cc1 = 0;
2630 size_t ret = findTableColumns(data.substr(i),start,end,cc1);
2631 size_t j=i+start;
2632 // separator line should consist of |, - and : and spaces only
2633 while (j<=end+i)
2634 {
2635 if (data[j]!=':' && data[j]!='-' && data[j]!='|' && data[j]!=' ')
2636 {
2637 AUTO_TRACE_EXIT("result=false: invalid character '{}'",data[j]);
2638 return false; // invalid characters in table separator
2639 }
2640 j++;
2641 }
2642 if (cc1!=cc0) // number of columns should be same as previous line
2643 {
2644 AUTO_TRACE_EXIT("result=false: different number of columns as previous line {}!={}",cc1,cc0);
2645 return false;
2646 }
2647
2648 i+=ret; // goto next line
2649 size_t cc2 = 0;
2650 findTableColumns(data.substr(i),start,end,cc2);
2651
2652 AUTO_TRACE_EXIT("result={}",cc1==cc2);
2653 return cc1==cc2;
2654}
2655
2656size_t Markdown::Private::writeTableBlock(std::string_view data)
2657{
2658 AUTO_TRACE("data='{}'",Trace::trunc(data));
2659 const size_t size = data.size();
2660
2661 size_t columns=0, start=0, end=0;
2662 size_t i = findTableColumns(data,start,end,columns);
2663 size_t headerStart = start;
2664 size_t headerEnd = end;
2665
2666 // read cell alignments
2667 size_t cc = 0;
2668 size_t ret = findTableColumns(data.substr(i),start,end,cc);
2669 size_t k=0;
2670 std::vector<Alignment> columnAlignment(columns);
2671
2672 bool leftMarker=false, rightMarker=false, startFound=false;
2673 size_t j=start+i;
2674 while (j<=end+i)
2675 {
2676 if (!startFound)
2677 {
2678 if (data[j]==':') { leftMarker=true; startFound=true; }
2679 if (data[j]=='-') startFound=true;
2680 //printf(" data[%d]=%c startFound=%d\n",j,data[j],startFound);
2681 }
2682 if (data[j]=='-') rightMarker=false;
2683 else if (data[j]==':') rightMarker=true;
2684 if (j<=end+i && (data[j]=='|' && (j==0 || data[j-1]!='\\')))
2685 {
2686 if (k<columns)
2687 {
2688 columnAlignment[k] = markersToAlignment(leftMarker,rightMarker);
2689 //printf("column[%d] alignment=%d\n",k,columnAlignment[k]);
2690 leftMarker=false;
2691 rightMarker=false;
2692 startFound=false;
2693 }
2694 k++;
2695 }
2696 j++;
2697 }
2698 if (k<columns)
2699 {
2700 columnAlignment[k] = markersToAlignment(leftMarker,rightMarker);
2701 //printf("column[%d] alignment=%d\n",k,columnAlignment[k]);
2702 }
2703 // proceed to next line
2704 i+=ret;
2705
2706 // Store the table cell information by row then column. This
2707 // allows us to handle row spanning.
2708 std::vector<std::vector<TableCell> > tableContents;
2709
2710 size_t m = headerStart;
2711 std::vector<TableCell> headerContents(columns);
2712 for (k=0;k<columns;k++)
2713 {
2714 while (m<=headerEnd && (data[m]!='|' || (m>0 && data[m-1]=='\\')))
2715 {
2716 headerContents[k].cellText += data[m++];
2717 }
2718 m++;
2719 // do the column span test before stripping white space
2720 // || is spanning columns, | | is not
2721 headerContents[k].colSpan = headerContents[k].cellText.empty();
2722 headerContents[k].cellText = headerContents[k].cellText.stripWhiteSpace();
2723 }
2724 tableContents.push_back(headerContents);
2725
2726 // write table cells
2727 while (i<size)
2728 {
2729 ret = findTableColumns(data.substr(i),start,end,cc);
2730 if (cc!=columns) break; // end of table
2731
2732 j=start+i;
2733 k=0;
2734 std::vector<TableCell> rowContents(columns);
2735 while (j<=end+i)
2736 {
2737 if (j<=end+i && (data[j]=='|' && (j==0 || data[j-1]!='\\')))
2738 {
2739 // do the column span test before stripping white space
2740 // || is spanning columns, | | is not
2741 rowContents[k].colSpan = rowContents[k].cellText.empty();
2742 rowContents[k].cellText = rowContents[k].cellText.stripWhiteSpace();
2743 k++;
2744 } // if (j<=end+i && (data[j]=='|' && (j==0 || data[j-1]!='\\')))
2745 else
2746 {
2747 rowContents[k].cellText += data[j];
2748 } // else { if (j<=end+i && (data[j]=='|' && (j==0 || data[j-1]!='\\'))) }
2749 j++;
2750 } // while (j<=end+i)
2751 // do the column span test before stripping white space
2752 // || is spanning columns, | | is not
2753 rowContents[k].colSpan = rowContents[k].cellText.empty();
2754 rowContents[k].cellText = rowContents[k].cellText.stripWhiteSpace();
2755 tableContents.push_back(rowContents);
2756
2757 // proceed to next line
2758 i+=ret;
2759 }
2760
2761 out+="<table class=\"markdownTable\">";
2762 DString cellTag("th"), cellClass("class=\"markdownTableHead");
2763 for (size_t row = 0; row < tableContents.size(); row++)
2764 {
2765 if (row)
2766 {
2767 if (row % 2)
2768 {
2769 out+="\n<tr class=\"markdownTableRowOdd\">";
2770 }
2771 else
2772 {
2773 out+="\n<tr class=\"markdownTableRowEven\">";
2774 }
2775 }
2776 else
2777 {
2778 out+="\n <tr class=\"markdownTableHead\">";
2779 }
2780 for (size_t c = 0; c < columns; c++)
2781 {
2782 // save the cell text for use after column span computation
2783 DString cellText(tableContents[row][c].cellText);
2784
2785 // Row span handling. Spanning rows will contain a caret ('^').
2786 // If the current cell contains just a caret, this is part of an
2787 // earlier row's span and the cell should not be added to the
2788 // output.
2789 if (tableContents[row][c].cellText == "^")
2790 {
2791 continue;
2792 }
2793 if (tableContents[row][c].colSpan)
2794 {
2795 int cr = static_cast<int>(c);
2796 while ( cr >= 0 && tableContents[row][cr].colSpan)
2797 {
2798 cr--;
2799 };
2800 if (cr >= 0 && tableContents[row][cr].cellText == "^") continue;
2801 }
2802 size_t rowSpan = 1, spanRow = row+1;
2803 while ((spanRow < tableContents.size()) &&
2804 (tableContents[spanRow][c].cellText == "^"))
2805 {
2806 spanRow++;
2807 rowSpan++;
2808 }
2809
2810 out+=" <" + cellTag + " " + cellClass;
2811 // use appropriate alignment style
2812 switch (columnAlignment[c])
2813 {
2814 case Alignment::Left: out+="Left\""; break;
2815 case Alignment::Right: out+="Right\""; break;
2816 case Alignment::Center: out+="Center\""; break;
2817 case Alignment::None: out+="None\""; break;
2818 }
2819
2820 if (rowSpan > 1)
2821 {
2822 DString spanStr;
2823 spanStr.setNum(rowSpan);
2824 out+=" rowspan=\"" + spanStr + "\"";
2825 }
2826 // Column span handling, assumes that column spans will have
2827 // empty strings, which would indicate the sequence "||", used
2828 // to signify spanning columns.
2829 size_t colSpan = 1;
2830 while ((c+1 < columns) && tableContents[row][c+1].colSpan)
2831 {
2832 c++;
2833 colSpan++;
2834 }
2835 if (colSpan > 1)
2836 {
2837 DString spanStr;
2838 spanStr.setNum(colSpan);
2839 out+=" colspan=\"" + spanStr + "\"";
2840 }
2841 // need at least one space on either side of the cell text in
2842 // order for doxygen to do other formatting
2843 out+="> " + cellText + " \\ilinebr </" + cellTag + ">";
2844 }
2845 cellTag = "td";
2846 cellClass = "class=\"markdownTableBody";
2847 out+=" </tr>";
2848 }
2849 out+="</table>\n";
2850
2851 AUTO_TRACE_EXIT("i={}",i);
2852 return i;
2853}
2854
2855
2856static bool hasLineBreak(std::string_view data)
2857{
2858 AUTO_TRACE("data='{}'",Trace::trunc(data));
2859 size_t i=0;
2860 size_t j=0;
2861 // search for end of line and also check if it is not a completely blank
2862 while (i<data.size() && data[i]!='\n')
2863 {
2864 if (data[i]!=' ' && data[i]!='\t') j++; // some non whitespace
2865 i++;
2866 }
2867 if (i>=data.size()) { return 0; } // empty line
2868 if (i<2) { return 0; } // not long enough
2869 bool res = (j>0 && data[i-1]==' ' && data[i-2]==' '); // non blank line with at two spaces at the end
2870 AUTO_TRACE_EXIT("result={}",res);
2871 return res;
2872}
2873
2874
2876{
2877 AUTO_TRACE("data='{}'",Trace::trunc(data));
2878 int level=0;
2879 DString header;
2880 DString id;
2881 if (isHRuler(data))
2882 {
2883 out+="<hr>\n";
2884 }
2885 else if ((level=isAtxHeader(data,header,id,true)))
2886 {
2887 DString hTag;
2888 if (!id.empty())
2889 {
2890 switch (level)
2891 {
2892 case SectionType::Section: out+="@section "; break;
2893 case SectionType::Subsection: out+="@subsection "; break;
2894 case SectionType::Subsubsection: out+="@subsubsection "; break;
2895 case SectionType::Paragraph: out+="@paragraph "; break;
2896 case SectionType::Subparagraph: out+="@subparagraph "; break;
2897 case SectionType::Subsubparagraph: out+="@subsubparagraph "; break;
2898 }
2899 out+=id;
2900 out+=" ";
2901 out+=header;
2902 out+="\n";
2903 }
2904 else
2905 {
2906 hTag.sprintf("h%d",level);
2907 out+="<"+hTag+">";
2908 out+=header;
2909 out+="</"+hTag+">\n";
2910 }
2911 }
2912 else if (data.size()>0) // nothing interesting -> just output the line
2913 {
2914 size_t tmpSize = data.size();
2915 if (data[data.size()-1] == '\n') tmpSize--;
2916 out+=data.substr(0,tmpSize);
2917
2918 if (hasLineBreak(data))
2919 {
2920 out+="\\ilinebr<br>";
2921 }
2922 if (tmpSize != data.size()) out+='\n';
2923 }
2924}
2925
2926static const std::unordered_map<std::string,std::string> g_quotationHeaderMap = {
2927 // GitHub style Doxygen command
2928 { "[!note]", "\\note" },
2929 { "[!warning]", "\\warning" },
2930 { "[!tip]", "\\remark" },
2931 { "[!caution]", "\\attention" },
2932 { "[!important]", "\\important" }
2933};
2934
2935size_t Markdown::Private::writeBlockQuote(std::string_view data)
2936{
2937 AUTO_TRACE("data='{}'",Trace::trunc(data));
2938 size_t i=0;
2939 int curLevel=0;
2940 size_t end=0;
2941 const size_t size = data.size();
2942 std::string startCmd;
2943 int isGitHubAlert = false;
2944 int isGitHubFirst = false;
2945 while (i<size)
2946 {
2947 // find end of this line
2948 end=i+1;
2949 while (end<=size && data[end-1]!='\n') end++;
2950 size_t j=i;
2951 int level=0;
2952 size_t indent=i;
2953 // compute the quoting level
2954 while (j<end && (data[j]==' ' || data[j]=='>'))
2955 {
2956 if (data[j]=='>') { level++; indent=j+1; }
2957 else if (j>0 && data[j-1]=='>') indent=j+1;
2958 j++;
2959 }
2960 if (indent>0 && j>0 && data[j-1]=='>' &&
2961 !(j==size || data[j]=='\n')) // disqualify last > if not followed by space
2962 {
2963 indent--;
2964 level--;
2965 j--;
2966 }
2967 AUTO_TRACE_ADD("indent={} i={} j={} end={} level={} line={}",indent,i,j,end,level,Trace::trunc(&data[i]));
2968 if (level==0 && j<end-1 && !isListMarker(data.substr(j)) && !isHRuler(data.substr(j)))
2969 {
2970 level = curLevel; // lazy
2971 }
2972 if (level==1)
2973 {
2974 DString txt = stripWhiteSpace(data.substr(indent,end-indent));
2975 auto it = g_quotationHeaderMap.find(txt.lower().str()); // TODO: in C++20 the std::string can be dropped
2976 if (it != g_quotationHeaderMap.end())
2977 {
2978 isGitHubAlert = true;
2979 isGitHubFirst = true;
2980 startCmd = it->second;
2981 }
2982 }
2983 if (level>curLevel) // quote level increased => add start markers
2984 {
2985 if (level!=1 || !isGitHubAlert) // normal block quote
2986 {
2987 for (int l=curLevel;l<level-1;l++)
2988 {
2989 out+="<blockquote>";
2990 }
2991 out += "<blockquote>&zwj;"; // empty blockquotes are also shown
2992 }
2993 else if (!startCmd.empty()) // GitHub style alert
2994 {
2995 out += startCmd + " ";
2996 }
2997 }
2998 else if (level<curLevel) // quote level decreased => add end markers
2999 {
3000 int decrLevel = curLevel;
3001 if (level==0 && isGitHubAlert)
3002 {
3003 decrLevel--;
3004 }
3005 for (int l=level;l<decrLevel;l++)
3006 {
3007 out += "</blockquote>\\ilinebr ";
3008 }
3009 }
3010 if (level==0)
3011 {
3012 curLevel=0;
3013 break; // end of quote block
3014 }
3015 // copy line without quotation marks
3016 if (curLevel!=0 || !isGitHubAlert)
3017 {
3018 std::string_view txt = data.substr(indent,end-indent);
3019 if (stripWhiteSpace(txt).empty() && !startCmd.empty())
3020 {
3021 if (!isGitHubFirst) out += "<br>";
3022 out += "<br>\n";
3023 }
3024 else
3025 {
3026 out += txt;
3027 }
3028 isGitHubFirst = false;
3029 }
3030 else // GitHub alert section
3031 {
3032 out+= "\n";
3033 }
3034 curLevel=level;
3035 // proceed with next line
3036 i=end;
3037 }
3038 // end of comment within blockquote => add end markers
3039 if (isGitHubAlert) // GitHub alert doesn't have a blockquote
3040 {
3041 curLevel--;
3042 }
3043 for (int l=0;l<curLevel;l++)
3044 {
3045 out+="</blockquote>";
3046 }
3047 AUTO_TRACE_EXIT("i={}",i);
3048 return i;
3049}
3050
3051// For code blocks that are outputted as part of an indented include or snippet command, we need to filter out
3052// the location string, i.e. '\ifile "..." \iline \ilinebr'.
3053bool skipOverFileAndLineCommands(std::string_view data,size_t indent,size_t &offset,std::string &location)
3054{
3055 size_t i = offset;
3056 size_t size = data.size();
3057 while (i<data.size() && data[i]==' ') i++;
3058 if (literal_at(data.substr(i),"\\ifile \""))
3059 {
3060 size_t locStart = i;
3061 if (i>offset) locStart--; // include the space before \ifile
3062 i+=8;
3063 bool found=false;
3064 while (i+9<size && data[i]!='\n')
3065 {
3066 if (literal_at(data.substr(i),"\\ilinebr "))
3067 {
3068 found=true;
3069 break;
3070 }
3071 i++;
3072 }
3073 if (found)
3074 {
3075 i+=9;
3076 location=data.substr(locStart,i-locStart);
3077 location+='\n';
3078 while (indent > 0 && i < size && data[i] == ' ')
3079 {
3080 i++;
3081 indent--;
3082 }
3083 if (i<size && data[i]=='\n') i++;
3084 offset = i;
3085 return true;
3086 }
3087 }
3088 return false;
3089}
3090
3091size_t Markdown::Private::writeCodeBlock(std::string_view data,size_t refIndent)
3092{
3093 AUTO_TRACE("data='{}' refIndent={}",Trace::trunc(data),refIndent);
3094 const size_t size = data.size();
3095 size_t i=0;
3096 // no need for \ilinebr here as the previous line was empty and was skipped
3097 out+="@iverbatim\n";
3098 int emptyLines=0;
3099 std::string location;
3100 while (i<size)
3101 {
3102 // find end of this line
3103 size_t end=i+1;
3104 while (end<=size && data[end-1]!='\n') end++;
3105 size_t j=i;
3106 size_t indent=0;
3107 while (j < end && data[j] == ' ')
3108 {
3109 j++;
3110 indent++;
3111 }
3112 //printf("j=%d end=%d indent=%d refIndent=%d tabSize=%d data={%s}\n",
3113 // j,end,indent,refIndent,Config_getInt(TAB_SIZE),qPrint(DString(data+i).left(end-i-1)));
3114 if (j==end-1) // empty line
3115 {
3116 emptyLines++;
3117 i=end;
3118 }
3119 else if (indent>=refIndent+codeBlockIndent) // enough indent to continue the code block
3120 {
3121 while (emptyLines>0) // write skipped empty lines
3122 {
3123 // add empty line
3124 out+="\n";
3125 emptyLines--;
3126 }
3127 // add code line minus the indent
3128 size_t offset = i+refIndent+codeBlockIndent;
3129 std::string lineLoc;
3130 if (skipOverFileAndLineCommands(data,codeBlockIndent,offset,lineLoc))
3131 {
3132 location = lineLoc;
3133 }
3134 out+=data.substr(offset,end-offset);
3135 i=end;
3136 }
3137 else // end of code block
3138 {
3139 break;
3140 }
3141 }
3142 out+="@endiverbatim";
3143 if (!location.empty())
3144 {
3145 out+=location;
3146 }
3147 else
3148 {
3149 out+="\\ilinebr ";
3150 }
3151 while (emptyLines>0) // write skipped empty lines
3152 {
3153 // add empty line
3154 out+="\n";
3155 emptyLines--;
3156 }
3157 AUTO_TRACE_EXIT("i={}",i);
3158 return i;
3159}
3160
3161// start searching for the end of the line start at offset \a i
3162// keeping track of possible blocks that need to be skipped.
3163size_t Markdown::Private::findEndOfLine(std::string_view data,size_t offset)
3164{
3165 AUTO_TRACE("data='{}'",Trace::trunc(data));
3166 // find end of the line
3167 const size_t size = data.size();
3168 size_t nb=0, end=offset+1, j=0;
3169 while (end<=size && (j=isNewline(data.substr(end-1)))==0)
3170 {
3171 // while looking for the end of the line we might encounter a block
3172 // that needs to be passed unprocessed.
3173 if ((data[end-1]=='\\' || data[end-1]=='@') && // command
3174 (end<=1 || (data[end-2]!='\\' && data[end-2]!='@')) // not escaped
3175 )
3176 {
3177 DString endBlockName = isBlockCommand(data.substr(end-1),end-1);
3178 end++;
3179 if (!endBlockName.empty())
3180 {
3181 size_t l = endBlockName.length();
3182 for (;end+l+1<size;end++) // search for end of block marker
3183 {
3184 if ((data[end]=='\\' || data[end]=='@') &&
3185 data[end-1]!='\\' && data[end-1]!='@'
3186 )
3187 {
3188 if (dstrncmp(&data[end+1],endBlockName.data(),l)==0)
3189 {
3190 // found end marker, skip over this block
3191 //printf("feol.block out={%s}\n",qPrint(DString(data+i).left(end+l+1-i)));
3192 end = end + l + 2;
3193 break;
3194 }
3195 }
3196 }
3197 }
3198 }
3199 else if (nb==0 && data[end-1]=='<' && size>=6 && end+6<size &&
3200 (end<=1 || (data[end-2]!='\\' && data[end-2]!='@'))
3201 )
3202 {
3203 if (tolower(data[end])=='p' && tolower(data[end+1])=='r' &&
3204 tolower(data[end+2])=='e' && (data[end+3]=='>' || data[end+3]==' ')) // <pre> tag
3205 {
3206 // skip part until including </pre>
3207 end = end + processHtmlTagWrite(data.substr(end-1),end-1,false);
3208 break;
3209 }
3210 else
3211 {
3212 end++;
3213 }
3214 }
3215 else if (nb==0 && data[end-1]=='`')
3216 {
3217 while (end <= size && data[end - 1] == '`')
3218 {
3219 end++;
3220 nb++;
3221 }
3222 }
3223 else if (nb>0 && data[end-1]=='`')
3224 {
3225 size_t enb=0;
3226 while (end <= size && data[end - 1] == '`')
3227 {
3228 end++;
3229 enb++;
3230 }
3231 if (enb==nb) nb=0;
3232 }
3233 else
3234 {
3235 end++;
3236 }
3237 }
3238 if (j>0) end+=j-1;
3239 AUTO_TRACE_EXIT("offset={} end={}",offset,end);
3240 return end;
3241}
3242
3243void Markdown::Private::writeFencedCodeBlock(std::string_view data,std::string_view lang,
3244 size_t blockStart,size_t blockEnd)
3245{
3246 AUTO_TRACE("data='{}' lang={} blockStart={} blockEnd={}",Trace::trunc(data),lang,blockStart,blockEnd);
3247 if (!lang.empty() && lang[0]=='.') lang=lang.substr(1);
3248 const size_t size=data.size();
3249 size_t i=0;
3250 while (i<size && (data[i]==' ' || data[i]=='\t'))
3251 {
3252 out+=data[i++];
3253 blockStart--;
3254 blockEnd--;
3255 }
3256 out+="@icode";
3257 if (!lang.empty())
3258 {
3259 out+="{"+lang+"}";
3260 }
3261 out+=" ";
3262 addStrEscapeUtf8Nbsp(data.substr(blockStart+i,blockEnd-blockStart));
3263 out+="@endicode ";
3264}
3265
3266DString Markdown::Private::processQuotations(std::string_view data,size_t refIndent)
3267{
3268 AUTO_TRACE("data='{}' refIndex='{}'",Trace::trunc(data),refIndent);
3269 out.clear();
3270 size_t i=0,end=0;
3271 size_t pi=std::string::npos;
3272 bool newBlock = false;
3273 bool insideList = false;
3274 size_t currentIndent = refIndent;
3275 size_t listIndent = refIndent;
3276 const size_t size = data.size();
3277 DString lang;
3278 while (i<size)
3279 {
3280 end = findEndOfLine(data,i);
3281 // line is now found at [i..end)
3282
3283 size_t lineIndent=0;
3284 while (lineIndent<end && data[i+lineIndent]==' ') lineIndent++;
3285 //printf("** lineIndent=%d line=(%s)\n",lineIndent,qPrint(DString(data+i).left(end-i)));
3286
3287 if (newBlock)
3288 {
3289 //printf("** end of block\n");
3290 if (insideList && lineIndent<currentIndent) // end of list
3291 {
3292 //printf("** end of list\n");
3293 currentIndent = refIndent;
3294 insideList = false;
3295 }
3296 newBlock = false;
3297 }
3298
3299 if ((listIndent=isListMarker(data.substr(i,end-i)))) // see if we need to increase the indent level
3300 {
3301 if (lineIndent<currentIndent+4)
3302 {
3303 //printf("** start of list\n");
3304 insideList = true;
3305 currentIndent = listIndent;
3306 }
3307 }
3308 else if (isEndOfList(data.substr(i,end-i)))
3309 {
3310 //printf("** end of list\n");
3311 insideList = false;
3312 currentIndent = listIndent;
3313 }
3314 else if (isEmptyLine(data.substr(i,end-i)))
3315 {
3316 //printf("** new block\n");
3317 newBlock = true;
3318 }
3319 //printf("currentIndent=%d listIndent=%d refIndent=%d\n",currentIndent,listIndent,refIndent);
3320
3321 if (pi!=std::string::npos)
3322 {
3323 size_t blockStart=0, blockEnd=0, blockOffset=0;
3324 if (isFencedCodeBlock(data.substr(pi),currentIndent,lang,blockStart,blockEnd,blockOffset,fileName,lineNr))
3325 {
3326 auto addSpecialCommand = [&](const DString &startCmd,const DString &endCmd)
3327 {
3328 size_t cmdPos = pi+blockStart+1;
3329 DString pl = data.substr(cmdPos,blockEnd-blockStart-1);
3330 size_t ii = 0;
3331 int nl = 1;
3332 // check for absence of start command, either @start<cmd>, or \\start<cmd>
3333 while (ii<pl.length() && disspace(pl[ii]))
3334 {
3335 if (pl[ii]=='\n') nl++;
3336 ii++; // skip leading whitespace
3337 }
3338 bool addNewLines = false;
3339 if (ii+startCmd.length()>=pl.length() || // no room for start command
3340 (pl[ii]!='\\' && pl[ii]!='@') || // no @ or \ after whitespace
3341 dstrncmp(pl.data()+ii+1,startCmd.data(),startCmd.length())!=0) // no start command
3342 {
3343 // input: output:
3344 // ----------------------------------------------------
3345 // ```{plantuml} => @startuml
3346 // A->B A->B
3347 // ``` @enduml
3348 // ----------------------------------------------------
3349 pl = "@"+startCmd+"\n" + pl + "@"+endCmd;
3350 ii=0;
3351 addNewLines = false;
3352 }
3353 else // we have a @start... command inside the code block
3354 {
3355 // input: output:
3356 // ----------------------------------------------------
3357 // ```{plantuml} \n
3358 // \n
3359 // @startuml => @startuml
3360 // A->B A->B
3361 // @enduml @enduml
3362 // ``` \n
3363 // ----------------------------------------------------
3364 addNewLines = true;
3365 }
3366 if (addNewLines) for (int j=0;j<nl;j++) out+='\n';
3367 processSpecialCommand(pl.view().substr(ii),ii);
3368 if (addNewLines) out+='\n';
3369 };
3370
3371 if (PlantumlManager::isEnabled() && lang=="plantuml")
3372 {
3373 addSpecialCommand("startuml","enduml");
3374 }
3375 else if (Config_getBool(HAVE_DOT) && lang=="dot")
3376 {
3377 addSpecialCommand("dot","enddot");
3378 }
3379 else if (lang=="msc") // msc is built-in
3380 {
3381 addSpecialCommand("msc","endmsc");
3382 }
3383 else if (lang=="mermaid")
3384 {
3385 addSpecialCommand("mermaid","endmermaid");
3386 }
3387 else // normal code block
3388 {
3389 writeFencedCodeBlock(data.substr(pi),lang.view(),blockStart,blockEnd);
3390 }
3391 i=pi+blockOffset;
3392 pi=std::string::npos;
3393 end=i+1;
3394 continue;
3395 }
3396 else if (isBlockQuote(data.substr(pi,i-pi),currentIndent))
3397 {
3398 i = pi+writeBlockQuote(data.substr(pi));
3399 pi=std::string::npos;
3400 end=i+1;
3401 continue;
3402 }
3403 else
3404 {
3405 //printf("quote out={%s}\n",DString(data+pi).left(i-pi).data());
3406 out+=data.substr(pi,i-pi);
3407 }
3408 }
3409 pi=i;
3410 i=end;
3411 }
3412 if (pi!=std::string::npos && pi<size) // deal with the last line
3413 {
3414 if (isBlockQuote(data.substr(pi),currentIndent))
3415 {
3416 writeBlockQuote(data.substr(pi));
3417 }
3418 else
3419 {
3420 if (DString(data.substr(pi)).startsWith("```") || DString(data.substr(pi)).startsWith("~~~"))
3421 {
3422 warn(fileName, lineNr, "Ending inside a fenced code block. Maybe the end marker for the block is missing?");
3423 }
3424 out+=data.substr(pi);
3425 }
3426 }
3427
3428 //printf("Process quotations\n---- input ----\n%s\n---- output ----\n%s\n------------\n",
3429 // qPrint(s),prv->out.get());
3430
3431 return out;
3432}
3433
3434DString Markdown::Private::processBlocks(std::string_view data,const size_t indent)
3435{
3436 AUTO_TRACE("data='{}' indent={}",Trace::trunc(data),indent);
3437 out.clear();
3438 size_t pi = std::string::npos;
3439 DString id,link,title;
3440
3441#if 0 // commented out, since starting with a comment block is probably a usage error
3442 // see also http://stackoverflow.com/q/20478611/784672
3443
3444 // special case when the documentation starts with a code block
3445 // since the first line is skipped when looking for a code block later on.
3446 if (end>codeBlockIndent && isCodeBlock(data,0,end,blockIndent))
3447 {
3448 i=writeCodeBlock(out,data,size,blockIndent);
3449 end=i+1;
3450 pi=-1;
3451 }
3452#endif
3453
3454 size_t currentIndent = indent;
3455 size_t listIndent = indent;
3456 bool insideList = false;
3457 bool newBlock = false;
3458 // process each line
3459 size_t i=0;
3460 while (i<data.size())
3461 {
3462 size_t end = findEndOfLine(data,i);
3463 // line is now found at [i..end)
3464
3465 size_t lineIndent=0;
3466 int level = 0;
3467 while (lineIndent<end && data[i+lineIndent]==' ') lineIndent++;
3468 //printf("** lineIndent=%d line=(%s)\n",lineIndent,qPrint(DString(data+i).left(end-i)));
3469
3470 if (newBlock)
3471 {
3472 //printf("** end of block\n");
3473 if (insideList && lineIndent<currentIndent) // end of list
3474 {
3475 //printf("** end of list\n");
3476 currentIndent = indent;
3477 insideList = false;
3478 }
3479 newBlock = false;
3480 }
3481
3482 if ((listIndent=isListMarker(data.substr(i,end-i)))) // see if we need to increase the indent level
3483 {
3484 if (lineIndent<currentIndent+4)
3485 {
3486 //printf("** start of list\n");
3487 insideList = true;
3488 currentIndent = listIndent;
3489 }
3490 }
3491 else if (isEndOfList(data.substr(i,end-i)))
3492 {
3493 //printf("** end of list\n");
3494 insideList = false;
3495 currentIndent = listIndent;
3496 }
3497 else if (isEmptyLine(data.substr(i,end-i)))
3498 {
3499 //printf("** new block\n");
3500 newBlock = true;
3501 }
3502
3503 //printf("indent=%d listIndent=%d blockIndent=%d\n",indent,listIndent,blockIndent);
3504
3505 //printf("findEndOfLine: pi=%d i=%d end=%d\n",pi,i,end);
3506
3507 if (pi!=std::string::npos)
3508 {
3509 size_t blockStart=0, blockEnd=0, blockOffset=0;
3510 DString lang;
3511 size_t blockIndent = currentIndent;
3512 size_t ref = 0;
3513 //printf("isHeaderLine(%s)=%d\n",DString(data+i).left(size-i).data(),level);
3514 DString endBlockName;
3515 if (data[i]=='@' || data[i]=='\\') endBlockName = isBlockCommand(data.substr(i),i);
3516 if (!endBlockName.empty())
3517 {
3518 // handle previous line
3519 if (isLinkRef(data.substr(pi,i-pi),id,link,title))
3520 {
3521 linkRefs.emplace(id.lower().str(),LinkRef(link,title));
3522 }
3523 else
3524 {
3525 writeOneLineHeaderOrRuler(data.substr(pi,i-pi));
3526 }
3527 out+=data[i];
3528 i++;
3529 size_t l = endBlockName.length();
3530 while (i+l<data.size())
3531 {
3532 if ((data[i]=='\\' || data[i]=='@') && // command
3533 data[i-1]!='\\' && data[i-1]!='@') // not escaped
3534 {
3535 if (dstrncmp(&data[i+1],endBlockName.data(),l)==0)
3536 {
3537 out+=data[i];
3538 out+=endBlockName;
3539 i+=l+1;
3540 break;
3541 }
3542 }
3543 out+=data[i];
3544 i++;
3545 }
3546 }
3547 else if ((level=isHeaderline(data.substr(i),true))>0)
3548 {
3549 //printf("Found header at %d-%d\n",i,end);
3550 while (pi<data.size() && data[pi]==' ') pi++;
3551 DString header = data.substr(pi,i-pi-1);
3552 id = extractTitleId(header, level);
3553 //printf("header='%s' is='%s'\n",qPrint(header),qPrint(id));
3554 if (!header.empty())
3555 {
3556 if (!id.empty())
3557 {
3558 out+=level==1?"@section ":"@subsection ";
3559 out+=id;
3560 out+=" ";
3561 out+=header;
3562 out+="\n\n";
3563 }
3564 else
3565 {
3566 out+=level==1?"<h1>":"<h2>";
3567 out+=header;
3568 out+=level==1?"\n</h1>\n":"\n</h2>\n";
3569 }
3570 }
3571 else
3572 {
3573 out+="\n<hr>\n";
3574 }
3575 pi=std::string::npos;
3576 i=end;
3577 end=i+1;
3578 continue;
3579 }
3580 else if ((ref=isLinkRef(data.substr(pi),id,link,title)))
3581 {
3582 //printf("found link ref: id='%s' link='%s' title='%s'\n",
3583 // qPrint(id),qPrint(link),qPrint(title));
3584 linkRefs.emplace(id.lower().str(),LinkRef(link,title));
3585 i=ref+pi;
3586 end=i+1;
3587 }
3588 else if (isFencedCodeBlock(data.substr(pi),currentIndent,lang,blockStart,blockEnd,blockOffset,fileName,lineNr))
3589 {
3590 //printf("Found FencedCodeBlock lang='%s' start=%d end=%d code={%s}\n",
3591 // qPrint(lang),blockStart,blockEnd,DString(data+pi+blockStart).left(blockEnd-blockStart).data());
3592 writeFencedCodeBlock(data.substr(pi),lang.view(),blockStart,blockEnd);
3593 i=pi+blockOffset;
3594 pi=std::string::npos;
3595 end=i+1;
3596 continue;
3597 }
3598 else if (isCodeBlock(data.substr(i,end-i),i,blockIndent))
3599 {
3600 // skip previous line (it is empty anyway)
3601 i+=writeCodeBlock(data.substr(i),blockIndent);
3602 pi=std::string::npos;
3603 end=i+1;
3604 continue;
3605 }
3606 else if (isTableBlock(data.substr(pi)))
3607 {
3608 i=pi+writeTableBlock(data.substr(pi));
3609 pi=std::string::npos;
3610 end=i+1;
3611 continue;
3612 }
3613 else
3614 {
3615 writeOneLineHeaderOrRuler(data.substr(pi,i-pi));
3616 }
3617 }
3618 pi=i;
3619 i=end;
3620 }
3621 //printf("last line %d size=%d\n",i,size);
3622 if (pi!=std::string::npos && pi<data.size()) // deal with the last line
3623 {
3624 if (isLinkRef(data.substr(pi),id,link,title))
3625 {
3626 //printf("found link ref: id='%s' link='%s' title='%s'\n",
3627 // qPrint(id),qPrint(link),qPrint(title));
3628 linkRefs.emplace(id.lower().str(),LinkRef(link,title));
3629 }
3630 else
3631 {
3632 writeOneLineHeaderOrRuler(data.substr(pi));
3633 }
3634 }
3635
3636 return out;
3637}
3638
3639static bool isOtherPage(std::string_view data)
3640{
3641#define OPC(x) if (literal_at(data,#x " ") || literal_at(data,#x "\n")) return true
3642 OPC(dir); OPC(defgroup); OPC(addtogroup); OPC(weakgroup); OPC(ingroup);
3643 OPC(fn); OPC(property); OPC(typedef); OPC(var); OPC(def);
3644 OPC(enum); OPC(namespace); OPC(class); OPC(concept); OPC(module);
3645 OPC(protocol); OPC(category); OPC(union); OPC(struct); OPC(interface);
3646 OPC(idlexcept); OPC(file); OPC(record);
3647#undef OPC
3648
3649 return false;
3650}
3651
3653{
3654 AUTO_TRACE("docs={}",Trace::trunc(docs));
3655 size_t i=0;
3656 std::string_view data(docs.str());
3657 const size_t size = data.size();
3658 if (!data.empty())
3659 {
3660 while (i<size && (data[i]==' ' || data[i]=='\n'))
3661 {
3662 i++;
3663 }
3664 if (literal_at(data.substr(i),"<!--!")) // skip over <!--! marker
3665 {
3666 i+=5;
3667 while (i<size && (data[i]==' ' || data[i]=='\n')) // skip over spaces after the <!--! marker
3668 {
3669 i++;
3670 }
3671 }
3672 if (i+1<size &&
3673 (data[i]=='\\' || data[i]=='@') &&
3674 (literal_at(data.substr(i+1),"page ") || literal_at(data.substr(i+1),"mainpage"))
3675 )
3676 {
3677 if (literal_at(data.substr(i+1),"page "))
3678 {
3679 AUTO_TRACE_EXIT("result=ExplicitPageResult::explicitPage");
3681 }
3682 else
3683 {
3684 AUTO_TRACE_EXIT("result=ExplicitPageResult::explicitMainPage");
3686 }
3687 }
3688 else if (i+1<size && (data[i]=='\\' || data[i]=='@') && isOtherPage(data.substr(i+1)))
3689 {
3690 AUTO_TRACE_EXIT("result=ExplicitPageResult::explicitOtherPage");
3692 }
3693 }
3694 AUTO_TRACE_EXIT("result=ExplicitPageResult::notExplicit");
3696}
3697
3698DString Markdown::extractPageTitle(DString &docs, DString &id, int &prepend, bool &isIdGenerated)
3699{
3700 AUTO_TRACE("docs={} prepend={}",Trace::trunc(docs),id,prepend);
3701 // first first non-empty line
3702 prepend = 0;
3703 DString title;
3704 size_t i=0;
3705 DString docs_org(docs);
3706 std::string_view data(docs_org.str());
3707 const size_t size = data.size();
3708 docs.clear();
3709 while (i<size && (data[i]==' ' || data[i]=='\n'))
3710 {
3711 if (data[i]=='\n') prepend++;
3712 i++;
3713 }
3714 if (i>=size) { return DString(); }
3715 size_t end1=i+1;
3716 while (end1<size && data[end1-1]!='\n') end1++;
3717 //printf("i=%d end1=%d size=%d line='%s'\n",i,end1,size,docs.mid(i,end1-i).data());
3718 // first line from i..end1
3719 if (end1<size)
3720 {
3721 // second line form end1..end2
3722 size_t end2=end1+1;
3723 while (end2<size && data[end2-1]!='\n') end2++;
3724 if (prv->isHeaderline(data.substr(end1),false))
3725 {
3726 title = data.substr(i,end1-i-1);
3727 docs+="\n\n"+docs_org.mid(end2);
3728 id = prv->extractTitleId(title, 0, &isIdGenerated);
3729 //printf("extractPageTitle(title='%s' docs='%s' id='%s')\n",title.data(),docs.data(),id.data());
3730 AUTO_TRACE_EXIT("result={} id={} isIdGenerated={}",Trace::trunc(title),id,isIdGenerated);
3731 return title;
3732 }
3733 }
3734 if (i<end1 && prv->isAtxHeader(data.substr(i,end1-i),title,id,false,&isIdGenerated)>0)
3735 {
3736 docs+="\n";
3737 docs+=docs_org.mid(end1);
3738 }
3739 else
3740 {
3741 docs=docs_org;
3742 id = prv->extractTitleId(title, 0, &isIdGenerated);
3743 }
3744 AUTO_TRACE_EXIT("result={} id={} isIdGenerated={}",Trace::trunc(title),id,isIdGenerated);
3745 return title;
3746}
3747
3748
3749//---------------------------------------------------------------------------
3750
3751DString Markdown::process(const DString &input, int &startNewlines, bool fromParseInput)
3752{
3753 if (input.empty()) return input;
3754 size_t refIndent=0;
3755
3756 // for replace tabs by spaces
3757 DString s = input;
3758 if (s.at(s.length()-1)!='\n') s += "\n"; // see PR #6766
3759 s = detab(s,refIndent);
3760 //printf("======== DeTab =========\n---- output -----\n%s\n---------\n",qPrint(s));
3761
3762 // then process quotation blocks (as these may contain other blocks)
3763 s = prv->processQuotations(s.view(),refIndent);
3764 //printf("======== Quotations =========\n---- output -----\n%s\n---------\n",qPrint(s));
3765
3766 // then process block items (headers, rules, and code blocks, references)
3767 s = prv->processBlocks(s.view(),refIndent);
3768 //printf("======== Blocks =========\n---- output -----\n%s\n---------\n",qPrint(s));
3769
3770 // finally process the inline markup (links, emphasis and code spans)
3771 prv->out.clear();
3772 prv->out.reserve(s.length());
3773 prv->processInline(s.view());
3774 if (fromParseInput)
3775 {
3776 Debug::print(Debug::Markdown,0,"---- output -----\n{}\n=========\n",qPrint(prv->out));
3777 }
3778 else
3779 {
3780 Debug::print(Debug::Markdown,0,"======== Markdown =========\n---- input ------- \n{}\n---- output -----\n{}\n=========\n",input,prv->out);
3781 }
3782
3783 // post processing
3784 DString result = substitute(prv->out,g_doxy_nbsp,"&nbsp;");
3785 const char *p = result.data();
3786 if (p)
3787 {
3788 while (*p==' ') p++; // skip over spaces
3789 while (*p=='\n') {startNewlines++;p++;}; // skip over newlines
3790 if (literal_at(p,"<br>")) p+=4; // skip over <br>
3791 }
3792 if (p>result.data())
3793 {
3794 // strip part of the input
3795 result = result.mid(static_cast<int>(p-result.data()));
3796 }
3797 return result;
3798}
3799
3800//---------------------------------------------------------------------------
3801
3803{
3804 AUTO_TRACE("fileName={}",fileName);
3805 DString absFileName = FileInfo(fileName.str()).absFilePath();
3806 DString baseFn = stripFromPath(absFileName);
3807 if (size_t i = baseFn.rfind('.'); i!=DString::npos) baseFn = baseFn.left(i);
3808 DString baseName = escapeCharsInString(baseFn,false,false);
3809 //printf("markdownFileNameToId(%s)=md_%s\n",qPrint(fileName),qPrint(baseName));
3810 DString res = "md_"+baseName;
3811 AUTO_TRACE_EXIT("result={}",res);
3812 return res;
3813}
3814
3815//---------------------------------------------------------------------------
3816
3821
3825
3829
3831 const char *fileBuf,
3832 const std::shared_ptr<Entry> &root,
3833 ClangTUParser* /*clangParser*/)
3834{
3835 std::shared_ptr<Entry> current = std::make_shared<Entry>();
3836 int prepend = 0; // number of empty lines in front
3837 current->lang = SrcLangExt::Markdown;
3838 current->fileName = fileName;
3839 current->docFile = fileName;
3840 current->docLine = 1;
3841 DString docs = stripIndentation(fileBuf);
3842 if (!docs.stripWhiteSpace().size()) return;
3843 Debug::print(Debug::Markdown,0,"======== Markdown =========\n---- input ------- \n{}\n",fileBuf);
3844 DString id;
3845 Markdown markdown(fileName,1,0);
3846 bool isIdGenerated = false;
3847 DString title = markdown.extractPageTitle(docs, id, prepend, isIdGenerated).stripWhiteSpace();
3848 DString generatedId;
3849 if (isIdGenerated)
3850 {
3851 generatedId = id;
3852 id = "";
3853 }
3854 int indentLevel=title.empty() ? 0 : -1;
3855 markdown.setIndentLevel(indentLevel);
3856 FileInfo fi(fileName.str());
3857 DString fn = fi.fileName();
3859 DString mdfileAsMainPage = Config_getString(USE_MDFILE_AS_MAINPAGE);
3860 DString mdFileNameId = markdownFileNameToId(fileName);
3861 bool wasEmpty = id.empty();
3862 if (wasEmpty) id = mdFileNameId;
3863 DString relFileName = stripFromPath(fileName);
3864 bool isSubdirDocs = Config_getBool(IMPLICIT_DIR_DOCS) && relFileName.lower().endsWith("/readme.md");
3865 switch (isExplicitPage(docs))
3866 {
3868 if (!mdfileAsMainPage.empty() &&
3869 (fi.absFilePath()==FileInfo(mdfileAsMainPage.str()).absFilePath()) // file reference with path
3870 )
3871 {
3872 docs.prepend("@ianchor{" + title + "} " + id + "\\ilinebr ");
3873 docs.prepend("@mainpage "+title+"\\ilinebr ");
3874 }
3875 else if (id=="mainpage" || id=="index")
3876 {
3877 if (title.empty()) title = titleFn;
3878 docs.prepend("@ianchor{" + title + "} " + id + "\\ilinebr ");
3879 docs.prepend("@mainpage "+title+"\\ilinebr ");
3880 }
3881 else if (isSubdirDocs)
3882 {
3883 if (!generatedId.empty() && !title.empty())
3884 {
3885 docs.prepend("@section " + generatedId + " " + title + "\\ilinebr ");
3886 }
3887 docs.prepend("@dir\\ilinebr ");
3888 }
3889 else
3890 {
3891 if (title.empty())
3892 {
3893 title = titleFn;
3894 prepend = 0;
3895 }
3896 if (!wasEmpty)
3897 {
3898 docs.prepend("@ianchor{" + title + "} " + id + "\\ilinebr @ianchor{" + relFileName + "} " + mdFileNameId + "\\ilinebr ");
3899 }
3900 else if (!generatedId.empty())
3901 {
3902 docs.prepend("@ianchor " + generatedId + "\\ilinebr ");
3903 }
3904 else if (Config_getEnum(MARKDOWN_ID_STYLE)==MARKDOWN_ID_STYLE_t::GITHUB)
3905 {
3906 DString autoId = AnchorGenerator::instance().generate(title.str());
3907 docs.prepend("@ianchor{" + title + "} " + autoId + "\\ilinebr ");
3908 }
3909 docs.prepend("@page "+id+" "+title+"\\ilinebr ");
3910 }
3911 for (int i = 0; i < prepend; i++) docs.prepend("\n");
3912 break;
3914 {
3915 // look for `@page label My Title\n` and capture `label` (match[1]) and ` My Title` (match[2])
3916 static const reg::Ex re(R"([ ]*[\\@]page\s+(\a[\w-]*)(\s*[^\n]*)\n)");
3917 reg::Match match;
3918 std::string s = docs.str();
3919 if (reg::search(s,match,re))
3920 {
3921 DString orgLabel = match[1].str();
3922 DString orgTitle = match[2].str();
3923 orgTitle = orgTitle.stripWhiteSpace();
3924 DString newLabel = markdownFileNameToId(fileName);
3925 docs = docs.left(match[1].position())+ // part before label
3926 newLabel+ // new label
3927 match[2].str()+ // part between orgLabel and \n
3928 "\\ilinebr @ianchor{" + orgTitle + "} "+orgLabel+"\n"+ // add original anchor plus \n of above
3929 docs.mid(match.length()); // add remainder of docs
3930 }
3931 }
3932 break;
3934 break;
3936 break;
3937 }
3938 int lineNr=1;
3939
3940 p->commentScanner.enterFile(fileName,lineNr);
3941 Protection prot = Protection::Public;
3942 bool needsEntry = false;
3943 int position=0;
3944 GuardedSectionStack guards;
3945 DString processedDocs = markdown.process(docs,lineNr,true);
3946 while (p->commentScanner.parseCommentBlock(
3947 this,
3948 current.get(),
3949 processedDocs,
3950 fileName,
3951 lineNr,
3952 false, // isBrief
3953 false, // javadoc autobrief
3954 false, // inBodyDocs
3955 prot, // protection
3956 position,
3957 needsEntry,
3958 true,
3959 &guards
3960 ))
3961 {
3962 if (needsEntry)
3963 {
3964 DString docFile = current->docFile;
3965 root->moveToSubEntryAndRefresh(current);
3966 current->lang = SrcLangExt::Markdown;
3967 current->docFile = docFile;
3968 current->docLine = lineNr;
3969 }
3970 }
3971 if (needsEntry)
3972 {
3973 root->moveToSubEntryAndKeep(current);
3974 }
3975 p->commentScanner.leaveFile(fileName,lineNr);
3976}
3977
3979{
3980 Doxygen::parserManager->getOutlineParser("*.cpp")->parsePrototype(text);
3981}
3982
3983//------------------------------------------------------------------------
#define eol
The end of line string for this machine.
static AnchorGenerator & instance()
Returns the singleton instance.
Definition anchor.cpp:41
static std::string addPrefixIfNeeded(const std::string &anchor)
Definition anchor.cpp:49
std::string generate(const std::string &title)
generates an anchor for a section with title.
Definition anchor.cpp:56
Clang parser object for a single translation unit, which consists of a source file and the directly o...
Definition clangparser.h:25
static bool isCommand(const DString &cmdName)
A String class for use with Doxygen wrapping std::string and adding some additional functionality off...
Definition dstring.h:84
void clear()
Definition dstring.h:214
DString & setNum(short n)
Definition dstring.h:552
size_t rfind(char c, size_t pos=npos) const
Definition dstring.h:244
DString mid(size_t index, size_t len=npos) const
Definition dstring.h:318
DString lower() const
Definition dstring.h:326
DString simplifyWhiteSpace() const
return a copy of this string with leading and trailing whitespace removed and multiple internal white...
Definition dstring.cpp:127
bool empty() const
Returns true iff the string is empty (std::string compatible alias for isEmpty()).
Definition dstring.h:148
DString substr(size_t pos=0, size_t count=npos) const
Returns a substring of length count starting at pos.
Definition dstring.h:223
std::string_view view() const
Definition dstring.h:162
static constexpr size_t npos
value used to indicate 'not found' or 'to the end of the string', matching std::string::npos
Definition dstring.h:178
char & at(size_t i)
Returns a reference to the character at index i.
Definition dstring.h:686
size_t size() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:154
DString & prepend(const char *s)
Definition dstring.h:515
size_t find(char c, size_t pos=0) const
Definition dstring.h:239
DString & sprintf(const char *format,...)
Definition dstring.cpp:34
DString stripWhiteSpace() const
returns a copy of this string with leading and trailing whitespace removed
Definition dstring.h:337
DString left(size_t len) const
Definition dstring.h:306
const std::string & str() const
Definition dstring.h:645
const char * data() const
Returns a pointer to the contents of the string in the form of a 0-terminated C string.
Definition dstring.h:157
bool startsWith(const char *s) const
Definition dstring.h:600
bool endsWith(const char *s) const
Definition dstring.h:617
size_t length() const
Returns the length of the string, not counting the 0-terminator.
Definition dstring.h:151
@ Markdown
Definition debug.h:38
static void print(DebugMask mask, int prio, fmt::format_string< Args... > fmt, Args &&... args)
Definition debug.h:78
static ParserManager * parserManager
Definition doxygen.h:122
static FileNameLinkedMap * imageNameLinkedMap
Definition doxygen.h:98
A model of a file symbol.
Definition filedef.h:97
Minimal replacement for QFileInfo.
Definition fileinfo.h:26
bool exists() const
Definition fileinfo.cpp:35
std::string fileName() const
Definition fileinfo.cpp:123
bool isReadable() const
Definition fileinfo.cpp:49
std::string absFilePath() const
Definition fileinfo.cpp:106
FileDef * findFileDef(const DString &n, bool &ambig) const
Returns the file definition in fnMap that matches the file name n.
Definition filename.cpp:38
Helper class to process markdown formatted text.
Definition markdown.h:33
DString process(const DString &input, int &startNewlines, bool fromParseInput=false)
static ActionTable_t fill_table()
Definition markdown.cpp:189
std::array< Action_t, 256 > ActionTable_t
Definition markdown.h:46
std::unique_ptr< Private > prv
Definition markdown.h:44
DString extractPageTitle(DString &docs, DString &id, int &prepend, bool &isIdGenerated)
static ActionTable_t actions
Definition markdown.h:48
void setIndentLevel(int level)
Definition markdown.cpp:217
std::function< int(Private &, std::string_view, size_t)> Action_t
Definition markdown.h:45
Markdown(const DString &fileName, int lineNr, int indentLevel=0)
Definition markdown.cpp:208
void parseInput(const DString &fileName, const char *fileBuf, const std::shared_ptr< Entry > &root, ClangTUParser *clangParser) override
Parses a single input file with the goal to build an Entry tree.
~MarkdownOutlineParser() override
void parsePrototype(const DString &text) override
Callback function called by the comment block scanner.
std::unique_ptr< Private > p
Definition markdown.h:65
std::unique_ptr< OutlineParserInterface > getOutlineParser(const DString &extension)
Gets the interface to the parser associated with a given extension.
Definition parserintf.h:244
static bool isEnabled()
Returns true if doxygen has been configured to run PlantUML, i.e.
Definition plantuml.cpp:246
static constexpr int Section
Definition section.h:33
static constexpr int MaxLevel
Definition section.h:39
static constexpr int Subsection
Definition section.h:34
static constexpr int Subsubsection
Definition section.h:35
static constexpr int MinLevel
Definition section.h:32
static constexpr int Paragraph
Definition section.h:36
static constexpr int Subsubparagraph
Definition section.h:38
static constexpr int Subparagraph
Definition section.h:37
Class representing a regular expression.
Definition regex.h:39
Object representing the matching results.
Definition regex.h:160
Interface for the comment block scanner.
std::stack< GuardedSection > GuardedSectionStack
Definition commentscan.h:48
#define Config_getInt(name)
Definition config.h:34
#define Config_getBool(name)
Definition config.h:33
#define Config_getString(name)
Definition config.h:32
#define Config_getEnum(name)
Definition config.h:35
std::vector< std::string > StringVector
Definition containers.h:33
DirIterator end(const DirIterator &) noexcept
Definition dir.cpp:180
#define AUTO_TRACE_ADD(...)
Definition docnode.cpp:54
#define AUTO_TRACE(...)
Definition docnode.cpp:53
#define AUTO_TRACE_EXIT(...)
Definition docnode.cpp:55
DString substitute(const DString &s, const DString &src, const DString &dst)
substitute all occurrences of src in s by dst
Definition dstring.cpp:485
bool isId(char c)
Returns true if c is a valid character for an identifier.
Definition dstring.h:895
int dstrncmp(const char *str1, const char *str2, size_t len)
Definition dstring.h:56
const char * qPrint(const char *s)
Definition dstring.h:783
bool disspace(char c)
Definition dstring.h:62
static DString escapeSpecialChars(const DString &s)
Definition markdown.cpp:263
static bool isOtherPage(std::string_view data)
#define AUTO_TRACE(...)
Definition markdown.cpp:68
static constexpr bool isAllowedEmphStr(const std::string_view &data, size_t offset)
Definition markdown.cpp:115
static bool hasLineBreak(std::string_view data)
ExplicitPageResult
Definition markdown.cpp:74
@ explicitMainPage
docs start with a mainpage command
Definition markdown.cpp:76
@ explicitPage
docs start with a page command
Definition markdown.cpp:75
@ notExplicit
docs doesn't start with either page or mainpage
Definition markdown.cpp:78
@ explicitOtherPage
docs start with a dir / defgroup / addtogroup command
Definition markdown.cpp:77
static bool isBlockQuote(std::string_view data, size_t indent)
returns true if this line starts a block quote
static constexpr Alignment markersToAlignment(bool leftMarker, bool rightMarker)
helper function to convert presence of left and/or right alignment markers to an alignment value
Definition markdown.cpp:327
static bool isEndOfList(std::string_view data)
static bool isFencedCodeBlock(std::string_view data, size_t refIndent, DString &lang, size_t &start, size_t &end, size_t &offset, DString &fileName, int lineNr)
static size_t computeIndentExcludingListMarkers(std::string_view data)
static const char * g_doxy_nbsp
Definition markdown.cpp:225
static constexpr bool ignoreCloseEmphChar(char c, char cn)
Definition markdown.cpp:123
#define OPC(x)
static DString getFilteredImageAttributes(std::string_view fmt, const DString &attrs)
parse the image attributes and return attributes for given format
Definition markdown.cpp:348
static constexpr bool isOpenEmphChar(char c)
Definition markdown.cpp:102
static bool isCodeBlock(std::string_view data, size_t offset, size_t &indent)
static bool isEmptyLine(std::string_view data)
#define AUTO_TRACE_EXIT(...)
Definition markdown.cpp:70
#define isLiTag(i)
static size_t findTableColumns(std::string_view data, size_t &start, size_t &end, size_t &columns)
Finds the location of the table's contains in the string data.
static const size_t codeBlockIndent
Definition markdown.cpp:226
static constexpr bool isIdChar(char c)
Definition markdown.cpp:84
static ExplicitPageResult isExplicitPage(const DString &docs)
static const char * g_utf8_nbsp
Definition markdown.cpp:224
static const std::unordered_map< std::string, std::string > g_quotationHeaderMap
Alignment
Definition markdown.cpp:219
static size_t isListMarker(std::string_view data)
static bool isHRuler(std::string_view data)
bool skipOverFileAndLineCommands(std::string_view data, size_t indent, size_t &offset, std::string &location)
static size_t isLinkRef(std::string_view data, DString &refid, DString &link, DString &title)
returns end of the link ref if this is indeed a link reference.
static constexpr bool extraChar(char c)
Definition markdown.cpp:93
static DString escapeDoubleQuotes(const DString &s)
Definition markdown.cpp:245
static bool isTableBlock(std::string_view data)
Returns true iff data points to the start of a table block.
static constexpr bool isUtf8Nbsp(char c1, char c2)
Definition markdown.cpp:110
size_t isNewline(std::string_view data)
Definition markdown.cpp:232
DString markdownFileNameToId(const DString &fileName)
processes string s and converts markdown into doxygen/html commands.
#define warn(file, line, fmt,...)
Definition message.h:97
const Mapper< CommandType > * cmdMapper
bool isAbsolutePath(const DString &fileName)
Definition portable.cpp:513
const char * strnstr(const char *haystack, const char *needle, size_t haystack_len)
Definition portable.cpp:616
DString trunc(const DString &s, size_t numChars=15)
Definition trace.h:56
Definition message.h:146
bool search(std::string_view str, Match &match, const Ex &re, size_t pos)
Search in a given string str starting at position pos for a match against regular expression re.
Definition regex.cpp:850
Definition dstring.h:913
Portable versions of functions that are platform dependent.
Some helper functions for std::string.
bool literal_at(const char *data, const char(&str)[N])
returns true iff data points to a substring that matches string literal str
Definition stringutil.h:101
std::string_view stripWhiteSpace(std::string_view s)
Given a string view s, returns a new, narrower view on that string, skipping over any leading or trai...
Definition stringutil.h:75
StringVector split(const std::string &s, const std::string &delimiter, bool retainEmpty=false)
split input string s by string delimiter delimiter.
Definition stringutil.h:119
DString isBlockCommand(std::string_view data, size_t offset)
Definition markdown.cpp:395
DString extractTitleId(DString &title, int level, bool *pIsIdGenerated=nullptr)
int processEmphasis1(std::string_view data, char c)
process single emphasis
Definition markdown.cpp:861
int processQuoted(std::string_view data, size_t offset)
Process quoted section "...", can contain one embedded newline.
size_t writeTableBlock(std::string_view data)
size_t writeBlockQuote(std::string_view data)
Private(const DString &fn, int line, int indent)
Definition markdown.cpp:139
void writeMarkdownImage(std::string_view fmt, bool inline_img, bool explicitTitle, const DString &title, const DString &content, const DString &link, const DString &attributes, const FileDef *fd)
size_t isSpecialCommand(std::string_view data, size_t offset)
Definition markdown.cpp:465
int processEmphasis3(std::string_view data, char c)
Parsing triple emphasis.
Definition markdown.cpp:927
int processCodeSpan(std::string_view data, size_t offset)
` parsing a code span (assuming codespan != 0)
int processSpecialCommand(std::string_view data, size_t offset)
void writeFencedCodeBlock(std::string_view data, std::string_view lang, size_t blockStart, size_t blockEnd)
int isHeaderline(std::string_view data, bool allowAdjustLevel)
returns whether the line is a setext-style hdr underline
size_t findEmphasisChar(std::string_view, char c, size_t c_size)
looks for the next emph char, skipping other constructs, and stopping when either it is found,...
Definition markdown.cpp:744
std::unordered_map< std::string, LinkRef > linkRefs
Definition markdown.cpp:182
void addStrEscapeUtf8Nbsp(std::string_view data)
size_t writeCodeBlock(std::string_view, size_t refIndent)
int processHtmlTag(std::string_view data, size_t offset)
int processEmphasis(std::string_view data, size_t offset)
int processLink(std::string_view data, size_t offset)
int isAtxHeader(std::string_view data, DString &header, DString &id, bool allowAdjustLevel, bool *pIsIdGenerated=nullptr)
int processHtmlTagWrite(std::string_view data, size_t offset, bool doWrite)
Process a HTML tag.
size_t findEndOfLine(std::string_view data, size_t offset)
int processEmphasis2(std::string_view data, char c)
process double emphasis
Definition markdown.cpp:895
DString processQuotations(std::string_view data, size_t refIndent)
void processInline(std::string_view data)
int processNmdash(std::string_view data, size_t offset)
Process ndash and mdashes.
Definition markdown.cpp:989
DString processBlocks(std::string_view data, size_t indent)
void writeOneLineHeaderOrRuler(std::string_view data)
bool colSpan
Definition markdown.cpp:134
DString cellText
Definition markdown.cpp:133
Protection
Definition types.h:32
SrcLangExt
Definition types.h:207
bool isURL(const DString &url)
Checks whether the given url starts with a supported protocol.
Definition util.cpp:4782
DString detab(const DString &s, size_t &refIndent)
Definition util.cpp:5330
DString externalLinkTarget(const bool parent)
Definition util.cpp:4627
DString stripExtensionGeneral(const DString &fName, const DString &ext)
Definition util.cpp:4077
DString getFileNameExtension(const DString &fn)
Definition util.cpp:4342
SrcLangExt getLanguageFromFileName(const DString &fileName, SrcLangExt defLang)
Definition util.cpp:4300
DString escapeCharsInString(const DString &name, bool allowDots, bool allowUnderscore)
Definition util.cpp:2820
DString stripIndentation(const DString &s, bool skipFirstLine)
Definition util.cpp:4819
DString stripFromPath(const DString &path)
Definition util.cpp:219
A bunch of utility functions.