imgui_markdown.h 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. #pragma once
  2. // License: zlib
  3. // Copyright (c) 2019 Juliette Foucaut & Doug Binks
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. // 2. Altered source versions must be plainly marked as such, and must not be
  18. // misrepresented as being the original software.
  19. // 3. This notice may not be removed or altered from any source distribution.
  20. /*
  21. API BREAKING CHANGES
  22. ====================
  23. - 2020/04/22 - Added tooltipCallback parameter to ImGui::MarkdownConfig
  24. - 2019/02/01 - Changed LinkCallback parameters, see https://github.com/juliettef/imgui_markdown/issues/2
  25. - 2019/02/05 - Added imageCallback parameter to ImGui::MarkdownConfig
  26. - 2019/02/06 - Added useLinkCallback member variable to MarkdownImageData to configure using images as links
  27. */
  28. /*
  29. imgui_markdown https://github.com/juliettef/imgui_markdown
  30. Markdown for Dear ImGui
  31. A permissively licensed markdown single-header library for https://github.com/ocornut/imgui
  32. Currently requires C++11 or above
  33. imgui_markdown currently supports the following markdown functionality:
  34. - Wrapped text
  35. - Headers H1, H2, H3
  36. - Emphasis
  37. - Indented text, multi levels
  38. - Unordered lists and sub-lists
  39. - Link
  40. - Image
  41. - Horizontal rule
  42. Syntax
  43. Wrapping:
  44. Text wraps automatically. To add a new line, use 'Return'.
  45. Headers:
  46. # H1
  47. ## H2
  48. ### H3
  49. Emphasis:
  50. *emphasis*
  51. _emphasis_
  52. **strong emphasis**
  53. __strong emphasis__
  54. Indents:
  55. On a new line, at the start of the line, add two spaces per indent.
  56. Indent level 1
  57. Indent level 2
  58. Unordered lists:
  59. On a new line, at the start of the line, add two spaces, an asterisks and a space.
  60. For nested lists, add two additional spaces in front of the asterisk per list level increment.
  61. * Unordered List level 1
  62. * Unordered List level 2
  63. Link:
  64. [link description](https://...)
  65. Image:
  66. ![image alt text](image identifier e.g. filename)
  67. Horizontal Rule:
  68. ***
  69. ___
  70. ===============================================================================
  71. // Example use on Windows with links opening in a browser
  72. #include "ImGui.h" // https://github.com/ocornut/imgui
  73. #include "imgui_markdown.h" // https://github.com/juliettef/imgui_markdown
  74. #include "IconsFontAwesome5.h" // https://github.com/juliettef/IconFontCppHeaders
  75. // Following includes for Windows LinkCallback
  76. #define WIN32_LEAN_AND_MEAN
  77. #include <Windows.h>
  78. #include "Shellapi.h"
  79. #include <string>
  80. void LinkCallback( ImGui::MarkdownLinkCallbackData data_ );
  81. inline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ );
  82. static ImFont* H1 = NULL;
  83. static ImFont* H2 = NULL;
  84. static ImFont* H3 = NULL;
  85. static ImGui::MarkdownConfig mdConfig;
  86. void LinkCallback( ImGui::MarkdownLinkCallbackData data_ )
  87. {
  88. std::string url( data_.link, data_.linkLength );
  89. if( !data_.isImage )
  90. {
  91. ShellExecuteA( NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL );
  92. }
  93. }
  94. inline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ )
  95. {
  96. // In your application you would load an image based on data_ input. Here we just use the imgui font texture.
  97. ImTextureID image = ImGui::GetIO().Fonts->TexID;
  98. // > C++14 can use ImGui::MarkdownImageData imageData{ true, false, image, ImVec2( 40.0f, 20.0f ) };
  99. ImGui::MarkdownImageData imageData;
  100. imageData.isValid = true;
  101. imageData.useLinkCallback = false;
  102. imageData.user_texture_id = image;
  103. imageData.size = ImVec2( 40.0f, 20.0f );
  104. // For image resize when available size.x > image width, add
  105. ImVec2 const contentSize = ImGui::GetContentRegionAvail();
  106. if( imageData.size.x > contentSize.x )
  107. {
  108. float const ratio = imageData.size.y/imageData.size.x;
  109. imageData.size.x = contentSize.x;
  110. imageData.size.y = contentSize.x*ratio;
  111. }
  112. return imageData;
  113. }
  114. void LoadFonts( float fontSize_ = 12.0f )
  115. {
  116. ImGuiIO& io = ImGui::GetIO();
  117. io.Fonts->Clear();
  118. // Base font
  119. io.Fonts->AddFontFromFileTTF( "myfont.ttf", fontSize_ );
  120. // Bold headings H2 and H3
  121. H2 = io.Fonts->AddFontFromFileTTF( "myfont-bold.ttf", fontSize_ );
  122. H3 = mdConfig.headingFormats[ 1 ].font;
  123. // bold heading H1
  124. float fontSizeH1 = fontSize_ * 1.1f;
  125. H1 = io.Fonts->AddFontFromFileTTF( "myfont-bold.ttf", fontSizeH1 );
  126. }
  127. void ExampleMarkdownFormatCallback( const ImGui::MarkdownFormatInfo& markdownFormatInfo_, bool start_ )
  128. {
  129. // Call the default first so any settings can be overwritten by our implementation.
  130. // Alternatively could be called or not called in a switch statement on a case by case basis.
  131. // See defaultMarkdownFormatCallback definition for furhter examples of how to use it.
  132. ImGui::defaultMarkdownFormatCallback( markdownFormatInfo_, start_ );
  133. switch( markdownFormatInfo_.type )
  134. {
  135. // example: change the colour of heading level 2
  136. case ImGui::MarkdownFormatType::HEADING:
  137. {
  138. if( markdownFormatInfo_.level == 2 )
  139. {
  140. if( start_ )
  141. {
  142. ImGui::PushStyleColor( ImGuiCol_Text, ImGui::GetStyle().Colors[ ImGuiCol_TextDisabled ] );
  143. }
  144. else
  145. {
  146. ImGui::PopStyleColor();
  147. }
  148. }
  149. break;
  150. }
  151. default:
  152. {
  153. break;
  154. }
  155. }
  156. }
  157. void Markdown( const std::string& markdown_ )
  158. {
  159. // You can make your own Markdown function with your prefered string container and markdown config.
  160. // > C++14 can use ImGui::MarkdownConfig mdConfig{ LinkCallback, NULL, ImageCallback, ICON_FA_LINK, { { H1, true }, { H2, true }, { H3, false } }, NULL };
  161. mdConfig.linkCallback = LinkCallback;
  162. mdConfig.tooltipCallback = NULL;
  163. mdConfig.imageCallback = ImageCallback;
  164. mdConfig.linkIcon = ICON_FA_LINK;
  165. mdConfig.headingFormats[0] = { H1, true };
  166. mdConfig.headingFormats[1] = { H2, true };
  167. mdConfig.headingFormats[2] = { H3, false };
  168. mdConfig.userData = NULL;
  169. mdConfig.formatCallback = ExampleMarkdownFormatCallback;
  170. ImGui::Markdown( markdown_.c_str(), markdown_.length(), mdConfig );
  171. }
  172. void MarkdownExample()
  173. {
  174. const std::string markdownText = u8R"(
  175. # H1 Header: Text and Links
  176. You can add [links like this one to enkisoftware](https://www.enkisoftware.com/) and lines will wrap well.
  177. You can also insert images ![image alt text](image identifier e.g. filename)
  178. Horizontal rules:
  179. ***
  180. ___
  181. *Emphasis* and **strong emphasis** change the appearance of the text.
  182. ## H2 Header: indented text.
  183. This text has an indent (two leading spaces).
  184. This one has two.
  185. ### H3 Header: Lists
  186. * Unordered lists
  187. * Lists can be indented with two extra spaces.
  188. * Lists can have [links like this one to Avoyd](https://www.avoyd.com/) and *emphasized text*
  189. )";
  190. Markdown( markdownText );
  191. }
  192. ===============================================================================
  193. */
  194. #include <stdint.h>
  195. namespace ImGui
  196. {
  197. //-----------------------------------------------------------------------------
  198. // Basic types
  199. //-----------------------------------------------------------------------------
  200. struct Link;
  201. struct MarkdownConfig;
  202. struct MarkdownLinkCallbackData // for both links and images
  203. {
  204. const char* text; // text between square brackets []
  205. int textLength;
  206. const char* link; // text between brackets ()
  207. int linkLength;
  208. void* userData;
  209. bool isImage; // true if '!' is detected in front of the link syntax
  210. };
  211. struct MarkdownTooltipCallbackData // for tooltips
  212. {
  213. MarkdownLinkCallbackData linkData;
  214. const char* linkIcon;
  215. };
  216. struct MarkdownImageData
  217. {
  218. bool isValid = false; // if true, will draw the image
  219. bool useLinkCallback = false; // if true, linkCallback will be called when image is clicked
  220. ImTextureID user_texture_id = 0; // see ImGui::Image
  221. ImVec2 size = ImVec2( 100.0f, 100.0f ); // see ImGui::Image
  222. ImVec2 uv0 = ImVec2( 0, 0 ); // see ImGui::Image
  223. ImVec2 uv1 = ImVec2( 1, 1 ); // see ImGui::Image
  224. ImVec4 tint_col = ImVec4( 1, 1, 1, 1 ); // see ImGui::Image
  225. ImVec4 border_col = ImVec4( 0, 0, 0, 0 ); // see ImGui::Image
  226. };
  227. enum class MarkdownFormatType
  228. {
  229. NORMAL_TEXT,
  230. HEADING,
  231. UNORDERED_LIST,
  232. LINK,
  233. EMPHASIS,
  234. };
  235. struct MarkdownFormatInfo
  236. {
  237. MarkdownFormatType type = MarkdownFormatType::NORMAL_TEXT;
  238. int32_t level = 0; // Set for headings: 1 for H1, 2 for H2 etc.
  239. bool itemHovered = false; // Currently only set for links when mouse hovered, only valid when start_ == false
  240. const MarkdownConfig* config = NULL;
  241. };
  242. typedef void MarkdownLinkCallback( MarkdownLinkCallbackData data );
  243. typedef void MarkdownTooltipCallback( MarkdownTooltipCallbackData data );
  244. inline void defaultMarkdownTooltipCallback( MarkdownTooltipCallbackData data_ )
  245. {
  246. if( data_.linkData.isImage )
  247. {
  248. ImGui::SetTooltip( "%.*s", data_.linkData.linkLength, data_.linkData.link );
  249. }
  250. else
  251. {
  252. ImGui::SetTooltip( "%s Open in browser\n%.*s", data_.linkIcon, data_.linkData.linkLength, data_.linkData.link );
  253. }
  254. }
  255. typedef MarkdownImageData MarkdownImageCallback( MarkdownLinkCallbackData data );
  256. typedef void MarkdownFormalCallback( const MarkdownFormatInfo& markdownFormatInfo_, bool start_ );
  257. inline void defaultMarkdownFormatCallback( const MarkdownFormatInfo& markdownFormatInfo_, bool start_ );
  258. struct MarkdownHeadingFormat
  259. {
  260. ImFont* font; // ImGui font
  261. bool separator; // if true, an underlined separator is drawn after the header
  262. };
  263. // Configuration struct for Markdown
  264. // - linkCallback is called when a link is clicked on
  265. // - linkIcon is a string which encode a "Link" icon, if available in the current font (e.g. linkIcon = ICON_FA_LINK with FontAwesome + IconFontCppHeaders https://github.com/juliettef/IconFontCppHeaders)
  266. // - headingFormats controls the format of heading H1 to H3, those above H3 use H3 format
  267. struct MarkdownConfig
  268. {
  269. static const int NUMHEADINGS = 3;
  270. MarkdownLinkCallback* linkCallback = NULL;
  271. MarkdownTooltipCallback* tooltipCallback = NULL;
  272. MarkdownImageCallback* imageCallback = NULL;
  273. const char* linkIcon = ""; // icon displayd in link tooltip
  274. MarkdownHeadingFormat headingFormats[ NUMHEADINGS ] = { { NULL, true }, { NULL, true }, { NULL, true } };
  275. void* userData = NULL;
  276. MarkdownFormalCallback* formatCallback = defaultMarkdownFormatCallback;
  277. };
  278. //-----------------------------------------------------------------------------
  279. // External interface
  280. //-----------------------------------------------------------------------------
  281. inline void Markdown( const char* markdown_, size_t markdownLength_, const MarkdownConfig& mdConfig_ );
  282. //-----------------------------------------------------------------------------
  283. // Internals
  284. //-----------------------------------------------------------------------------
  285. struct TextRegion;
  286. struct Line;
  287. inline void UnderLine( ImColor col_ );
  288. inline void RenderLine( const char* markdown_, Line& line_, TextRegion& textRegion_, const MarkdownConfig& mdConfig_ );
  289. struct TextRegion
  290. {
  291. TextRegion() : indentX( 0.0f )
  292. {
  293. }
  294. ~TextRegion()
  295. {
  296. ResetIndent();
  297. }
  298. // ImGui::TextWrapped will wrap at the starting position
  299. // so to work around this we render using our own wrapping for the first line
  300. void RenderTextWrapped( const char* text_, const char* text_end_, bool bIndentToHere_ = false )
  301. {
  302. float scale = ImGui::GetIO().FontGlobalScale;
  303. float widthLeft = GetContentRegionAvail().x;
  304. const char* endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );
  305. ImGui::TextUnformatted( text_, endLine );
  306. if( bIndentToHere_ )
  307. {
  308. float indentNeeded = GetContentRegionAvail().x - widthLeft;
  309. if( indentNeeded )
  310. {
  311. ImGui::Indent( indentNeeded );
  312. indentX += indentNeeded;
  313. }
  314. }
  315. widthLeft = GetContentRegionAvail().x;
  316. while( endLine < text_end_ )
  317. {
  318. text_ = endLine;
  319. if( *text_ == ' ' ) { ++text_; } // skip a space at start of line
  320. endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );
  321. if( text_ == endLine )
  322. {
  323. endLine++;
  324. }
  325. ImGui::TextUnformatted( text_, endLine );
  326. }
  327. }
  328. void RenderListTextWrapped( const char* text_, const char* text_end_ )
  329. {
  330. ImGui::Bullet();
  331. ImGui::SameLine();
  332. RenderTextWrapped( text_, text_end_, true );
  333. }
  334. bool RenderLinkText( const char* text_, const char* text_end_, const Link& link_,
  335. const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_ );
  336. void RenderLinkTextWrapped( const char* text_, const char* text_end_, const Link& link_,
  337. const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_, bool bIndentToHere_ = false );
  338. void ResetIndent()
  339. {
  340. if( indentX > 0.0f )
  341. {
  342. ImGui::Unindent( indentX );
  343. }
  344. indentX = 0.0f;
  345. }
  346. private:
  347. float indentX;
  348. };
  349. // Text that starts after a new line (or at beginning) and ends with a newline (or at end)
  350. struct Line {
  351. bool isHeading = false;
  352. bool isEmphasis = false;
  353. bool isUnorderedListStart = false;
  354. bool isLeadingSpace = true; // spaces at start of line
  355. int leadSpaceCount = 0;
  356. int headingCount = 0;
  357. int emphasisCount = 0;
  358. int lineStart = 0;
  359. int lineEnd = 0;
  360. int lastRenderPosition = 0; // lines may get rendered in multiple pieces
  361. };
  362. struct TextBlock { // subset of line
  363. int start = 0;
  364. int stop = 0;
  365. int size() const
  366. {
  367. return stop - start;
  368. }
  369. };
  370. struct Link {
  371. enum LinkState {
  372. NO_LINK,
  373. HAS_SQUARE_BRACKET_OPEN,
  374. HAS_SQUARE_BRACKETS,
  375. HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN,
  376. };
  377. LinkState state = NO_LINK;
  378. TextBlock text;
  379. TextBlock url;
  380. bool isImage = false;
  381. int num_brackets_open = 0;
  382. };
  383. struct Emphasis {
  384. enum EmphasisState {
  385. NONE,
  386. LEFT,
  387. MIDDLE,
  388. RIGHT,
  389. };
  390. EmphasisState state = NONE;
  391. TextBlock text;
  392. char sym;
  393. };
  394. inline void UnderLine( ImColor col_ )
  395. {
  396. ImVec2 min = ImGui::GetItemRectMin();
  397. ImVec2 max = ImGui::GetItemRectMax();
  398. min.y = max.y;
  399. ImGui::GetWindowDrawList()->AddLine( min, max, col_, 1.0f );
  400. }
  401. inline void RenderLine( const char* markdown_, Line& line_, TextRegion& textRegion_, const MarkdownConfig& mdConfig_ )
  402. {
  403. // indent
  404. int indentStart = 0;
  405. if( line_.isUnorderedListStart ) // ImGui unordered list render always adds one indent
  406. {
  407. indentStart = 1;
  408. }
  409. for( int j = indentStart; j < line_.leadSpaceCount / 2; ++j ) // add indents
  410. {
  411. ImGui::Indent();
  412. }
  413. // render
  414. MarkdownFormatInfo formatInfo;
  415. formatInfo.config = &mdConfig_;
  416. int textStart = line_.lastRenderPosition + 1;
  417. int textSize = line_.lineEnd - textStart;
  418. if( line_.isUnorderedListStart ) // render unordered list
  419. {
  420. formatInfo.type = MarkdownFormatType::UNORDERED_LIST;
  421. mdConfig_.formatCallback( formatInfo, true );
  422. const char* text = markdown_ + textStart + 1;
  423. textRegion_.RenderListTextWrapped( text, text + textSize - 1 );
  424. }
  425. else if( line_.isHeading ) // render heading
  426. {
  427. formatInfo.level = line_.headingCount;
  428. formatInfo.type = MarkdownFormatType::HEADING;
  429. mdConfig_.formatCallback( formatInfo, true );
  430. const char* text = markdown_ + textStart + 1;
  431. textRegion_.RenderTextWrapped( text, text + textSize - 1 );
  432. }
  433. else if( line_.isEmphasis ) // render emphasis
  434. {
  435. formatInfo.level = line_.emphasisCount;
  436. formatInfo.type = MarkdownFormatType::EMPHASIS;
  437. mdConfig_.formatCallback(formatInfo, true);
  438. const char* text = markdown_ + textStart;
  439. textRegion_.RenderTextWrapped(text, text + textSize);
  440. }
  441. else // render a normal paragraph chunk
  442. {
  443. formatInfo.type = MarkdownFormatType::NORMAL_TEXT;
  444. mdConfig_.formatCallback( formatInfo, true );
  445. const char* text = markdown_ + textStart;
  446. textRegion_.RenderTextWrapped( text, text + textSize );
  447. }
  448. mdConfig_.formatCallback( formatInfo, false );
  449. // unindent
  450. for( int j = indentStart; j < line_.leadSpaceCount / 2; ++j )
  451. {
  452. ImGui::Unindent();
  453. }
  454. }
  455. // render markdown
  456. inline void Markdown( const char* markdown_, size_t markdownLength_, const MarkdownConfig& mdConfig_ )
  457. {
  458. static const char* linkHoverStart = NULL; // we need to preserve status of link hovering between frames
  459. ImGuiStyle& style = ImGui::GetStyle();
  460. Line line;
  461. Link link;
  462. Emphasis em;
  463. TextRegion textRegion;
  464. char c = 0;
  465. for( int i=0; i < (int)markdownLength_; ++i )
  466. {
  467. c = markdown_[i]; // get the character at index
  468. if( c == 0 ) { break; } // shouldn't happen but don't go beyond 0.
  469. // If we're at the beginning of the line, count any spaces
  470. if( line.isLeadingSpace )
  471. {
  472. if( c == ' ' )
  473. {
  474. ++line.leadSpaceCount;
  475. continue;
  476. }
  477. else
  478. {
  479. line.isLeadingSpace = false;
  480. line.lastRenderPosition = i - 1;
  481. if(( c == '*' ) && ( line.leadSpaceCount >= 2 ))
  482. {
  483. if( ( (int)markdownLength_ > i + 1 ) && ( markdown_[ i + 1 ] == ' ' ) ) // space after '*'
  484. {
  485. line.isUnorderedListStart = true;
  486. ++i;
  487. ++line.lastRenderPosition;
  488. }
  489. // carry on processing as could be emphasis
  490. }
  491. else if( c == '#' )
  492. {
  493. line.headingCount++;
  494. bool bContinueChecking = true;
  495. int j = i;
  496. while( ++j < (int)markdownLength_ && bContinueChecking )
  497. {
  498. c = markdown_[j];
  499. switch( c )
  500. {
  501. case '#':
  502. line.headingCount++;
  503. break;
  504. case ' ':
  505. line.lastRenderPosition = j - 1;
  506. i = j;
  507. line.isHeading = true;
  508. bContinueChecking = false;
  509. break;
  510. default:
  511. line.isHeading = false;
  512. bContinueChecking = false;
  513. break;
  514. }
  515. }
  516. if( line.isHeading )
  517. {
  518. // reset emphasis status, we do not support emphasis around headers for now
  519. em = Emphasis();
  520. continue;
  521. }
  522. }
  523. }
  524. }
  525. // Test to see if we have a link
  526. switch( link.state )
  527. {
  528. case Link::NO_LINK:
  529. if( c == '[' && !line.isHeading ) // we do not support headings with links for now
  530. {
  531. link.state = Link::HAS_SQUARE_BRACKET_OPEN;
  532. link.text.start = i + 1;
  533. if( i > 0 && markdown_[i - 1] == '!' )
  534. {
  535. link.isImage = true;
  536. }
  537. }
  538. break;
  539. case Link::HAS_SQUARE_BRACKET_OPEN:
  540. if( c == ']' )
  541. {
  542. link.state = Link::HAS_SQUARE_BRACKETS;
  543. link.text.stop = i;
  544. }
  545. break;
  546. case Link::HAS_SQUARE_BRACKETS:
  547. if( c == '(' )
  548. {
  549. link.state = Link::HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN;
  550. link.url.start = i + 1;
  551. link.num_brackets_open = 1;
  552. }
  553. break;
  554. case Link::HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN:
  555. if( c == '(' )
  556. {
  557. ++link.num_brackets_open;
  558. }
  559. else if( c == ')' )
  560. {
  561. --link.num_brackets_open;
  562. }
  563. if( link.num_brackets_open == 0 )
  564. {
  565. // reset emphasis status, we do not support emphasis around links for now
  566. em = Emphasis();
  567. // render previous line content
  568. line.lineEnd = link.text.start - ( link.isImage ? 2 : 1 );
  569. RenderLine( markdown_, line, textRegion, mdConfig_ );
  570. line.leadSpaceCount = 0;
  571. link.url.stop = i;
  572. line.isUnorderedListStart = false; // the following text shouldn't have bullets
  573. ImGui::SameLine( 0.0f, 0.0f );
  574. if( link.isImage ) // it's an image, render it.
  575. {
  576. bool drawnImage = false;
  577. bool useLinkCallback = false;
  578. if( mdConfig_.imageCallback )
  579. {
  580. MarkdownImageData imageData = mdConfig_.imageCallback( { markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true } );
  581. useLinkCallback = imageData.useLinkCallback;
  582. if( imageData.isValid )
  583. {
  584. ImGui::Image( imageData.user_texture_id, imageData.size, imageData.uv0, imageData.uv1, imageData.tint_col, imageData.border_col );
  585. drawnImage = true;
  586. }
  587. }
  588. if( !drawnImage )
  589. {
  590. ImGui::Text( "( Image %.*s not loaded )", link.url.size(), markdown_ + link.url.start );
  591. }
  592. if( ImGui::IsItemHovered() )
  593. {
  594. if( ImGui::IsMouseReleased( 0 ) && mdConfig_.linkCallback && useLinkCallback )
  595. {
  596. mdConfig_.linkCallback( { markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true } );
  597. }
  598. if( link.text.size() > 0 && mdConfig_.tooltipCallback )
  599. {
  600. mdConfig_.tooltipCallback( { { markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true }, mdConfig_.linkIcon } );
  601. }
  602. }
  603. }
  604. else // it's a link, render it.
  605. {
  606. textRegion.RenderLinkTextWrapped( markdown_ + link.text.start, markdown_ + link.text.start + link.text.size(), link, markdown_, mdConfig_, &linkHoverStart, false );
  607. }
  608. ImGui::SameLine( 0.0f, 0.0f );
  609. // reset the link by reinitializing it
  610. link = Link();
  611. line.lastRenderPosition = i;
  612. break;
  613. }
  614. }
  615. // Test to see if we have emphasis styling
  616. switch( em.state )
  617. {
  618. case Emphasis::NONE:
  619. if( link.state == Link::NO_LINK && !line.isHeading )
  620. {
  621. int next = i + 1;
  622. int prev = i - 1;
  623. if( ( c == '*' || c == '_' )
  624. && ( i == line.lineStart
  625. || markdown_[ prev ] == ' '
  626. || markdown_[ prev ] == '\t' ) // empasis must be preceded by whitespace or line start
  627. && (int)markdownLength_ > next // emphasis must precede non-whitespace
  628. && markdown_[ next ] != ' '
  629. && markdown_[ next ] != '\n'
  630. && markdown_[ next ] != '\t' )
  631. {
  632. em.state = Emphasis::LEFT;
  633. em.sym = c;
  634. em.text.start = i;
  635. line.emphasisCount = 1;
  636. continue;
  637. }
  638. }
  639. break;
  640. case Emphasis::LEFT:
  641. if( em.sym == c )
  642. {
  643. ++line.emphasisCount;
  644. continue;
  645. }
  646. else
  647. {
  648. em.text.start = i;
  649. em.state = Emphasis::MIDDLE;
  650. }
  651. break;
  652. case Emphasis::MIDDLE:
  653. if( em.sym == c )
  654. {
  655. em.state = Emphasis::RIGHT;
  656. em.text.stop = i;
  657. // pass through to case Emphasis::RIGHT
  658. }
  659. else
  660. {
  661. break;
  662. }
  663. case Emphasis::RIGHT:
  664. if( em.sym == c )
  665. {
  666. if( line.emphasisCount < 3 && ( i - em.text.stop + 1 == line.emphasisCount ) )
  667. {
  668. // render text up to emphasis
  669. int lineEnd = em.text.start - line.emphasisCount;
  670. if( lineEnd > line.lineStart )
  671. {
  672. line.lineEnd = lineEnd;
  673. RenderLine( markdown_, line, textRegion, mdConfig_ );
  674. ImGui::SameLine( 0.0f, 0.0f );
  675. line.isUnorderedListStart = false;
  676. line.leadSpaceCount = 0;
  677. }
  678. line.isEmphasis = true;
  679. line.lastRenderPosition = em.text.start - 1;
  680. line.lineStart = em.text.start;
  681. line.lineEnd = em.text.stop;
  682. RenderLine( markdown_, line, textRegion, mdConfig_ );
  683. ImGui::SameLine( 0.0f, 0.0f );
  684. line.isEmphasis = false;
  685. line.lastRenderPosition = i;
  686. em = Emphasis();
  687. }
  688. continue;
  689. }
  690. else
  691. {
  692. em.state = Emphasis::NONE;
  693. // render text up to here
  694. int start = em.text.start - line.emphasisCount;
  695. if( start < line.lineStart )
  696. {
  697. line.lineEnd = line.lineStart;
  698. line.lineStart = start;
  699. line.lastRenderPosition = start - 1;
  700. RenderLine(markdown_, line, textRegion, mdConfig_);
  701. line.lineStart = line.lineEnd;
  702. line.lastRenderPosition = line.lineStart - 1;
  703. }
  704. }
  705. break;
  706. }
  707. // handle end of line (render)
  708. if( c == '\n' )
  709. {
  710. // first check if the line is a horizontal rule
  711. line.lineEnd = i;
  712. if( em.state == Emphasis::MIDDLE && line.emphasisCount >=3 &&
  713. ( line.lineStart + line.emphasisCount ) == i )
  714. {
  715. ImGui::Separator();
  716. }
  717. else
  718. {
  719. // render the line: multiline emphasis requires a complex implementation so not supporting
  720. RenderLine( markdown_, line, textRegion, mdConfig_ );
  721. }
  722. // reset the line and emphasis state
  723. line = Line();
  724. em = Emphasis();
  725. line.lineStart = i + 1;
  726. line.lastRenderPosition = i;
  727. textRegion.ResetIndent();
  728. // reset the link
  729. link = Link();
  730. }
  731. }
  732. if( em.state == Emphasis::LEFT && line.emphasisCount >= 3 )
  733. {
  734. ImGui::Separator();
  735. }
  736. else
  737. {
  738. // render any remaining text if last char wasn't 0
  739. if( markdownLength_ && line.lineStart < (int)markdownLength_ && markdown_[ line.lineStart ] != 0 )
  740. {
  741. // handle both null terminated and non null terminated strings
  742. line.lineEnd = (int)markdownLength_;
  743. if( 0 == markdown_[ line.lineEnd - 1 ] )
  744. {
  745. --line.lineEnd;
  746. }
  747. RenderLine( markdown_, line, textRegion, mdConfig_ );
  748. }
  749. }
  750. }
  751. inline bool TextRegion::RenderLinkText( const char* text_, const char* text_end_, const Link& link_,
  752. const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_ )
  753. {
  754. MarkdownFormatInfo formatInfo;
  755. formatInfo.config = &mdConfig_;
  756. formatInfo.type = MarkdownFormatType::LINK;
  757. mdConfig_.formatCallback( formatInfo, true );
  758. ImGui::PushTextWrapPos( -1.0f );
  759. ImGui::TextUnformatted( text_, text_end_ );
  760. ImGui::PopTextWrapPos();
  761. bool bThisItemHovered = ImGui::IsItemHovered();
  762. if(bThisItemHovered)
  763. {
  764. *linkHoverStart_ = markdown_ + link_.text.start;
  765. }
  766. bool bHovered = bThisItemHovered || ( *linkHoverStart_ == ( markdown_ + link_.text.start ) );
  767. formatInfo.itemHovered = bHovered;
  768. mdConfig_.formatCallback( formatInfo, false );
  769. if(bHovered)
  770. {
  771. if( ImGui::IsMouseReleased( 0 ) && mdConfig_.linkCallback )
  772. {
  773. mdConfig_.linkCallback( { markdown_ + link_.text.start, link_.text.size(), markdown_ + link_.url.start, link_.url.size(), mdConfig_.userData, false } );
  774. }
  775. if( mdConfig_.tooltipCallback )
  776. {
  777. mdConfig_.tooltipCallback( { { markdown_ + link_.text.start, link_.text.size(), markdown_ + link_.url.start, link_.url.size(), mdConfig_.userData, false }, mdConfig_.linkIcon } );
  778. }
  779. }
  780. return bThisItemHovered;
  781. }
  782. inline void TextRegion::RenderLinkTextWrapped( const char* text_, const char* text_end_, const Link& link_,
  783. const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_, bool bIndentToHere_ )
  784. {
  785. float scale = ImGui::GetIO().FontGlobalScale;
  786. float widthLeft = GetContentRegionAvail().x;
  787. const char* endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );
  788. bool bHovered = RenderLinkText( text_, endLine, link_, markdown_, mdConfig_, linkHoverStart_ );
  789. if( bIndentToHere_ )
  790. {
  791. float indentNeeded = GetContentRegionAvail().x - widthLeft;
  792. if( indentNeeded )
  793. {
  794. ImGui::Indent( indentNeeded );
  795. indentX += indentNeeded;
  796. }
  797. }
  798. widthLeft = GetContentRegionAvail().x;
  799. while( endLine < text_end_ )
  800. {
  801. text_ = endLine;
  802. if( *text_ == ' ' ) { ++text_; } // skip a space at start of line
  803. endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );
  804. if( text_ == endLine )
  805. {
  806. endLine++;
  807. }
  808. bool bThisLineHovered = RenderLinkText( text_, endLine, link_, markdown_, mdConfig_, linkHoverStart_ );
  809. bHovered = bHovered || bThisLineHovered;
  810. }
  811. if( !bHovered && *linkHoverStart_ == markdown_ + link_.text.start )
  812. {
  813. *linkHoverStart_ = NULL;
  814. }
  815. }
  816. inline void defaultMarkdownFormatCallback( const MarkdownFormatInfo& markdownFormatInfo_, bool start_ )
  817. {
  818. switch( markdownFormatInfo_.type )
  819. {
  820. case MarkdownFormatType::NORMAL_TEXT:
  821. break;
  822. case MarkdownFormatType::EMPHASIS:
  823. {
  824. MarkdownHeadingFormat fmt;
  825. // default styling for emphasis uses last headingFormats - for your own styling
  826. // implement EMPHASIS in your formatCallback
  827. if( markdownFormatInfo_.level == 1 )
  828. {
  829. // normal emphasis
  830. if( start_ )
  831. {
  832. ImGui::PushStyleColor( ImGuiCol_Text, ImGui::GetStyle().Colors[ ImGuiCol_TextDisabled ] );
  833. }
  834. else
  835. {
  836. ImGui::PopStyleColor();
  837. }
  838. }
  839. else
  840. {
  841. // strong emphasis
  842. fmt = markdownFormatInfo_.config->headingFormats[ MarkdownConfig::NUMHEADINGS - 1 ];
  843. if( start_ )
  844. {
  845. if( fmt.font )
  846. {
  847. ImGui::PushFont( fmt.font );
  848. }
  849. }
  850. else
  851. {
  852. if( fmt.font )
  853. {
  854. ImGui::PopFont();
  855. }
  856. }
  857. }
  858. break;
  859. }
  860. case MarkdownFormatType::HEADING:
  861. {
  862. MarkdownHeadingFormat fmt;
  863. if( markdownFormatInfo_.level > MarkdownConfig::NUMHEADINGS )
  864. {
  865. fmt = markdownFormatInfo_.config->headingFormats[ MarkdownConfig::NUMHEADINGS - 1 ];
  866. }
  867. else
  868. {
  869. fmt = markdownFormatInfo_.config->headingFormats[ markdownFormatInfo_.level - 1 ];
  870. }
  871. if( start_ )
  872. {
  873. if( fmt.font )
  874. {
  875. ImGui::PushFont( fmt.font );
  876. }
  877. ImGui::NewLine();
  878. }
  879. else
  880. {
  881. if( fmt.separator )
  882. {
  883. ImGui::Separator();
  884. ImGui::NewLine();
  885. }
  886. else
  887. {
  888. ImGui::NewLine();
  889. }
  890. if( fmt.font )
  891. {
  892. ImGui::PopFont();
  893. }
  894. }
  895. break;
  896. }
  897. case MarkdownFormatType::UNORDERED_LIST:
  898. break;
  899. case MarkdownFormatType::LINK:
  900. if( start_ )
  901. {
  902. ImGui::PushStyleColor( ImGuiCol_Text, ImGui::GetStyle().Colors[ ImGuiCol_ButtonHovered ] );
  903. }
  904. else
  905. {
  906. ImGui::PopStyleColor();
  907. if( markdownFormatInfo_.itemHovered )
  908. {
  909. ImGui::UnderLine( ImGui::GetStyle().Colors[ ImGuiCol_ButtonHovered ] );
  910. }
  911. else
  912. {
  913. ImGui::UnderLine( ImGui::GetStyle().Colors[ ImGuiCol_Button ] );
  914. }
  915. }
  916. break;
  917. }
  918. }
  919. }