TextFormatter.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Provides text formatting. Supports <see cref="View.HotKey"/>s, horizontal alignment, vertical alignment,
  4. /// multiple lines, and word-based line wrap.
  5. /// </summary>
  6. public class TextFormatter
  7. {
  8. private bool _autoSize;
  9. private Key _hotKey = new ();
  10. private int _hotKeyPos = -1;
  11. private List<string> _lines = new ();
  12. private bool _multiLine;
  13. private bool _preserveTrailingSpaces;
  14. private Size _size;
  15. private int _tabWidth = 4;
  16. private string _text;
  17. private TextAlignment _textAlignment;
  18. private TextDirection _textDirection;
  19. private VerticalTextAlignment _textVerticalAlignment;
  20. private bool _wordWrap = true;
  21. /// <summary>Controls the horizontal text-alignment property.</summary>
  22. /// <value>The text alignment.</value>
  23. public TextAlignment Alignment
  24. {
  25. get => _textAlignment;
  26. set => _textAlignment = EnableNeedsFormat (value);
  27. }
  28. /// <summary>Gets or sets whether the <see cref="Size"/> should be automatically changed to fit the <see cref="Text"/>.</summary>
  29. /// <remarks>
  30. /// <para>Used by <see cref="View.AutoSize"/> to resize the view's <see cref="View.ContentSize"/> to fit <see cref="Size"/>.</para>
  31. /// <para>
  32. /// <see cref="TextAlignment.Justified"/> and
  33. /// <see cref="VerticalTextAlignment.Justified"/> are ignored when <see cref="AutoSize"/> is <see langword="true"/>.
  34. /// </para>
  35. /// </remarks>
  36. public bool AutoSize
  37. {
  38. get => _autoSize;
  39. set
  40. {
  41. _autoSize = EnableNeedsFormat (value);
  42. if (_autoSize)
  43. {
  44. Size = GetAutoSize ();
  45. }
  46. }
  47. }
  48. private Size GetAutoSize ()
  49. {
  50. if (string.IsNullOrEmpty(_text))
  51. {
  52. return Size.Empty;
  53. }
  54. int width = int.MaxValue;
  55. int height = int.MaxValue;
  56. string text = _text;
  57. List<string> lines;
  58. if (FindHotKey (_text, HotKeySpecifier, out _hotKeyPos, out Key newHotKey))
  59. {
  60. HotKey = newHotKey;
  61. text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  62. text = ReplaceHotKeyWithTag (text, _hotKeyPos);
  63. }
  64. if (IsVerticalDirection (Direction))
  65. {
  66. int colsWidth = GetSumMaxCharWidth (text, 0, 1, TabWidth);
  67. lines = Format (
  68. text,
  69. height,
  70. VerticalAlignment == VerticalTextAlignment.Justified,
  71. width > colsWidth && WordWrap,
  72. PreserveTrailingSpaces,
  73. TabWidth,
  74. Direction,
  75. MultiLine
  76. );
  77. colsWidth = GetMaxColsForWidth (lines, width, TabWidth);
  78. if (lines.Count > colsWidth)
  79. {
  80. lines.RemoveRange (colsWidth, lines.Count - colsWidth);
  81. }
  82. height = lines.Max (static line => line.GetColumns ());
  83. width = lines.Count;
  84. }
  85. else
  86. {
  87. lines = Format (
  88. text,
  89. width,
  90. false, // Ignore justification because autosize means no justification
  91. height > 1 && WordWrap,
  92. PreserveTrailingSpaces,
  93. TabWidth,
  94. Direction,
  95. MultiLine
  96. );
  97. // Format always returns at least 1 line
  98. if (lines.Count == 1 && string.IsNullOrEmpty (lines [0]))
  99. {
  100. return Size.Empty;
  101. }
  102. width = lines.Max (static line => line.GetColumns ());
  103. height = lines.Count;
  104. }
  105. return new (width, height);
  106. }
  107. /// <summary>
  108. /// Gets the cursor position of the <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will
  109. /// be positioned over it.
  110. /// </summary>
  111. public int CursorPosition { get; internal set; }
  112. /// <summary>Controls the text-direction property.</summary>
  113. /// <value>The text vertical alignment.</value>
  114. public TextDirection Direction
  115. {
  116. get => _textDirection;
  117. set
  118. {
  119. _textDirection = EnableNeedsFormat (value);
  120. if (AutoSize)
  121. {
  122. Size = GetAutoSize ();
  123. }
  124. }
  125. }
  126. /// <summary>
  127. /// Determines if the viewport width will be used or only the text width will be used,
  128. /// If <see langword="true"/> all the viewport area will be filled with whitespaces and the same background color
  129. /// showing a perfect rectangle.
  130. /// </summary>
  131. public bool FillRemaining { get; set; }
  132. /// <summary>Gets or sets the hot key. Fires the <see cref="HotKeyChanged"/> event.</summary>
  133. public Key HotKey
  134. {
  135. get => _hotKey;
  136. internal set
  137. {
  138. if (_hotKey != value)
  139. {
  140. Key oldKey = _hotKey;
  141. _hotKey = value;
  142. HotKeyChanged?.Invoke (this, new KeyChangedEventArgs (oldKey, value));
  143. }
  144. }
  145. }
  146. /// <summary>The position in the text of the hot key. The hot key will be rendered using the hot color.</summary>
  147. public int HotKeyPos
  148. {
  149. get => _hotKeyPos;
  150. internal set => _hotKeyPos = value;
  151. }
  152. /// <summary>
  153. /// The specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable hot key support for this View
  154. /// instance. The default is '\xffff'.
  155. /// </summary>
  156. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  157. /// <summary>Gets or sets a value indicating whether multi line is allowed.</summary>
  158. /// <remarks>Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.</remarks>
  159. public bool MultiLine
  160. {
  161. get => _multiLine;
  162. set => _multiLine = EnableNeedsFormat (value);
  163. }
  164. /// <summary>Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.</summary>
  165. /// <remarks>
  166. /// <para>If <see langword="false"/> when Draw is called, the Draw call will be faster.</para>
  167. /// <para>Used by <see cref="Draw"/></para>
  168. /// <para>Set to <see langword="true"/> when any of the properties of <see cref="TextFormatter"/> are set.</para>
  169. /// <para>Set to <see langword="false"/> when the text is formatted (if <see cref="GetLines"/> is accessed).</para>
  170. /// </remarks>
  171. public bool NeedsFormat { get; set; }
  172. /// <summary>
  173. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved or not when
  174. /// <see cref="TextFormatter.WordWrap"/> is enabled. If <see langword="true"/> trailing spaces at the end of wrapped
  175. /// lines will be removed when <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  176. /// </summary>
  177. public bool PreserveTrailingSpaces
  178. {
  179. get => _preserveTrailingSpaces;
  180. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  181. }
  182. /// <summary>Gets or sets the size <see cref="Text"/> will be constrained to when formatted.</summary>
  183. /// <remarks>
  184. /// <para>
  185. /// Does not return the size of the formatted text but the size that will be used to constrain the text when
  186. /// formatted.
  187. /// </para>
  188. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  189. /// </remarks>
  190. public Size Size
  191. {
  192. get => _size;
  193. set
  194. {
  195. if (AutoSize)// && Alignment != TextAlignment.Justified && VerticalAlignment != VerticalTextAlignment.Justified)
  196. {
  197. //_size = EnableNeedsFormat (CalcRect (0, 0, Text, Direction, TabWidth).Size);
  198. _size = EnableNeedsFormat (value);
  199. }
  200. else
  201. {
  202. _size = EnableNeedsFormat (value);
  203. }
  204. }
  205. }
  206. /// <summary>Gets or sets the number of columns used for a tab.</summary>
  207. public int TabWidth
  208. {
  209. get => _tabWidth;
  210. set => _tabWidth = EnableNeedsFormat (value);
  211. }
  212. /// <summary>The text to be formatted. This string is never modified.</summary>
  213. public virtual string Text
  214. {
  215. get => _text;
  216. set
  217. {
  218. bool textWasNull = _text is null && value != null;
  219. _text = EnableNeedsFormat (value);
  220. // BUGBUG: If AutoSize is false, there should be no "automatic behavior" like setting the size
  221. if (AutoSize || (textWasNull && Size.IsEmpty))
  222. {
  223. Size = GetAutoSize ();
  224. }
  225. }
  226. }
  227. /// <summary>Controls the vertical text-alignment property.</summary>
  228. /// <value>The text vertical alignment.</value>
  229. public VerticalTextAlignment VerticalAlignment
  230. {
  231. get => _textVerticalAlignment;
  232. set => _textVerticalAlignment = EnableNeedsFormat (value);
  233. }
  234. /// <summary>Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="Size"/>.</summary>
  235. public bool WordWrap
  236. {
  237. get => _wordWrap;
  238. set => _wordWrap = EnableNeedsFormat (value);
  239. }
  240. /// <summary>Draws the text held by <see cref="TextFormatter"/> to <see cref="ConsoleDriver"/> using the colors specified.</summary>
  241. /// <remarks>
  242. /// Causes the text to be formatted (references <see cref="GetLines"/>). Sets <see cref="NeedsFormat"/> to
  243. /// <c>false</c>.
  244. /// </remarks>
  245. /// <param name="screen">Specifies the screen-relative location and maximum size for drawing the text.</param>
  246. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  247. /// <param name="hotColor">The color to use to draw the hotkey</param>
  248. /// <param name="maximum">Specifies the screen-relative location and maximum container size.</param>
  249. /// <param name="driver">The console driver currently used by the application.</param>
  250. /// <exception cref="ArgumentOutOfRangeException"></exception>
  251. public void Draw (
  252. Rectangle screen,
  253. Attribute normalColor,
  254. Attribute hotColor,
  255. Rectangle maximum = default,
  256. ConsoleDriver driver = null
  257. )
  258. {
  259. // With this check, we protect against subclasses with overrides of Text (like Button)
  260. if (string.IsNullOrEmpty (Text))
  261. {
  262. return;
  263. }
  264. driver ??= Application.Driver;
  265. driver?.SetAttribute (normalColor);
  266. List<string> linesFormatted = GetLines ();
  267. switch (Direction)
  268. {
  269. case TextDirection.TopBottom_RightLeft:
  270. case TextDirection.LeftRight_BottomTop:
  271. case TextDirection.RightLeft_BottomTop:
  272. case TextDirection.BottomTop_RightLeft:
  273. linesFormatted.Reverse ();
  274. break;
  275. }
  276. bool isVertical = IsVerticalDirection (Direction);
  277. Rectangle maxScreen = screen;
  278. if (driver is { })
  279. {
  280. // INTENT: What, exactly, is the intent of this?
  281. maxScreen = maximum == default (Rectangle)
  282. ? screen
  283. : new (
  284. Math.Max (maximum.X, screen.X),
  285. Math.Max (maximum.Y, screen.Y),
  286. Math.Max (
  287. Math.Min (maximum.Width, maximum.Right - screen.Left),
  288. 0
  289. ),
  290. Math.Max (
  291. Math.Min (
  292. maximum.Height,
  293. maximum.Bottom - screen.Top
  294. ),
  295. 0
  296. )
  297. );
  298. }
  299. if (maxScreen.Width == 0 || maxScreen.Height == 0)
  300. {
  301. return;
  302. }
  303. int lineOffset = !isVertical && screen.Y < 0 ? Math.Abs (screen.Y) : 0;
  304. for (int line = lineOffset; line < linesFormatted.Count; line++)
  305. {
  306. if ((isVertical && line > screen.Width) || (!isVertical && line > screen.Height))
  307. {
  308. continue;
  309. }
  310. if ((isVertical && line >= maxScreen.Left + maxScreen.Width)
  311. || (!isVertical && line >= maxScreen.Top + maxScreen.Height + lineOffset))
  312. {
  313. break;
  314. }
  315. Rune [] runes = linesFormatted [line].ToRunes ();
  316. runes = Direction switch
  317. {
  318. TextDirection.RightLeft_BottomTop => runes.Reverse ().ToArray (),
  319. TextDirection.RightLeft_TopBottom => runes.Reverse ().ToArray (),
  320. TextDirection.BottomTop_LeftRight => runes.Reverse ().ToArray (),
  321. TextDirection.BottomTop_RightLeft => runes.Reverse ().ToArray (),
  322. _ => runes
  323. };
  324. // When text is justified, we lost left or right, so we use the direction to align.
  325. int x, y;
  326. // Horizontal Alignment
  327. if (Alignment == TextAlignment.Right || (Alignment == TextAlignment.Justified && !IsLeftToRight (Direction)))
  328. {
  329. if (isVertical)
  330. {
  331. int runesWidth = GetWidestLineLength (linesFormatted, 0, line, TabWidth);
  332. x = screen.Right - runesWidth;
  333. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  334. }
  335. else
  336. {
  337. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  338. x = screen.Right - runesWidth;
  339. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  340. }
  341. }
  342. else if (Alignment is TextAlignment.Left or TextAlignment.Justified)
  343. {
  344. if (isVertical)
  345. {
  346. int runesWidth = line > 0
  347. ? GetWidestLineLength (linesFormatted, 0, line, TabWidth)
  348. : 0;
  349. x = screen.Left + runesWidth;
  350. }
  351. else
  352. {
  353. x = screen.Left;
  354. }
  355. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  356. }
  357. else if (Alignment == TextAlignment.Centered)
  358. {
  359. if (isVertical)
  360. {
  361. int runesWidth = GetWidestLineLength (linesFormatted, 0, line, TabWidth);
  362. x = screen.Left + line + (screen.Width - runesWidth) / 2;
  363. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  364. }
  365. else
  366. {
  367. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  368. x = screen.Left + (screen.Width - runesWidth) / 2;
  369. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  370. }
  371. }
  372. else
  373. {
  374. throw new ArgumentOutOfRangeException ($"{nameof (Alignment)}");
  375. }
  376. // Vertical Alignment
  377. if (VerticalAlignment == VerticalTextAlignment.Bottom || (VerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (Direction)))
  378. {
  379. if (isVertical)
  380. {
  381. y = screen.Bottom - runes.Length;
  382. }
  383. else
  384. {
  385. y = screen.Bottom - linesFormatted.Count + line;
  386. }
  387. }
  388. else if (VerticalAlignment is VerticalTextAlignment.Top or VerticalTextAlignment.Justified)
  389. {
  390. if (isVertical)
  391. {
  392. y = screen.Top;
  393. }
  394. else
  395. {
  396. y = screen.Top + line;
  397. }
  398. }
  399. else if (VerticalAlignment == VerticalTextAlignment.Middle)
  400. {
  401. if (isVertical)
  402. {
  403. int s = (screen.Height - runes.Length) / 2;
  404. y = screen.Top + s;
  405. }
  406. else
  407. {
  408. int s = (screen.Height - linesFormatted.Count) / 2;
  409. y = screen.Top + line + s;
  410. }
  411. }
  412. else
  413. {
  414. throw new ArgumentOutOfRangeException ($"{nameof (VerticalAlignment)}");
  415. }
  416. int colOffset = screen.X < 0 ? Math.Abs (screen.X) : 0;
  417. int start = isVertical ? screen.Top : screen.Left;
  418. int size = isVertical ? screen.Height : screen.Width;
  419. int current = start + colOffset;
  420. List<Point?> lastZeroWidthPos = null;
  421. Rune rune = default;
  422. int zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  423. for (int idx = (isVertical ? start - y : start - x) + colOffset;
  424. current < start + size + zeroLengthCount;
  425. idx++)
  426. {
  427. Rune lastRuneUsed = rune;
  428. if (lastZeroWidthPos is null)
  429. {
  430. if (idx < 0 || x + current + colOffset < 0)
  431. {
  432. current++;
  433. continue;
  434. }
  435. if (!FillRemaining && idx > runes.Length - 1)
  436. {
  437. break;
  438. }
  439. if ((!isVertical && current - start > maxScreen.Left + maxScreen.Width - screen.X + colOffset)
  440. || (isVertical && idx > maxScreen.Top + maxScreen.Height - screen.Y))
  441. {
  442. break;
  443. }
  444. }
  445. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - viewport.X + colOffset)
  446. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - viewport.Y))
  447. // break;
  448. rune = (Rune)' ';
  449. if (isVertical)
  450. {
  451. if (idx >= 0 && idx < runes.Length)
  452. {
  453. rune = runes [idx];
  454. }
  455. if (lastZeroWidthPos is null)
  456. {
  457. driver?.Move (x, current);
  458. }
  459. else
  460. {
  461. int foundIdx = lastZeroWidthPos.IndexOf (
  462. p =>
  463. p is { } && p.Value.Y == current
  464. );
  465. if (foundIdx > -1)
  466. {
  467. if (rune.IsCombiningMark ())
  468. {
  469. lastZeroWidthPos [foundIdx] =
  470. new Point (
  471. lastZeroWidthPos [foundIdx].Value.X + 1,
  472. current
  473. );
  474. driver?.Move (
  475. lastZeroWidthPos [foundIdx].Value.X,
  476. current
  477. );
  478. }
  479. else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ())
  480. {
  481. current++;
  482. driver?.Move (x, current);
  483. }
  484. else
  485. {
  486. driver?.Move (x, current);
  487. }
  488. }
  489. else
  490. {
  491. driver?.Move (x, current);
  492. }
  493. }
  494. }
  495. else
  496. {
  497. driver?.Move (current, y);
  498. if (idx >= 0 && idx < runes.Length)
  499. {
  500. rune = runes [idx];
  501. }
  502. }
  503. int runeWidth = GetRuneWidth (rune, TabWidth);
  504. if (HotKeyPos > -1 && idx == HotKeyPos)
  505. {
  506. if ((isVertical && VerticalAlignment == VerticalTextAlignment.Justified) || (!isVertical && Alignment == TextAlignment.Justified))
  507. {
  508. CursorPosition = idx - start;
  509. }
  510. driver?.SetAttribute (hotColor);
  511. driver?.AddRune (rune);
  512. driver?.SetAttribute (normalColor);
  513. }
  514. else
  515. {
  516. if (isVertical)
  517. {
  518. if (runeWidth == 0)
  519. {
  520. if (lastZeroWidthPos is null)
  521. {
  522. lastZeroWidthPos = new List<Point?> ();
  523. }
  524. int foundIdx = lastZeroWidthPos.IndexOf (
  525. p =>
  526. p is { } && p.Value.Y == current
  527. );
  528. if (foundIdx == -1)
  529. {
  530. current--;
  531. lastZeroWidthPos.Add (new Point (x + 1, current));
  532. }
  533. driver?.Move (x + 1, current);
  534. }
  535. }
  536. driver?.AddRune (rune);
  537. }
  538. if (isVertical)
  539. {
  540. if (runeWidth > 0)
  541. {
  542. current++;
  543. }
  544. }
  545. else
  546. {
  547. current += runeWidth;
  548. }
  549. int nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length
  550. ? runes [idx + 1].GetColumns ()
  551. : 0;
  552. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size)
  553. {
  554. break;
  555. }
  556. }
  557. }
  558. }
  559. /// <summary>Returns the formatted text, constrained to <see cref="Size"/>.</summary>
  560. /// <remarks>
  561. /// If <see cref="NeedsFormat"/> is <see langword="true"/>, causes a format, resetting <see cref="NeedsFormat"/>
  562. /// to <see langword="false"/>.
  563. /// </remarks>
  564. /// <returns>The formatted text.</returns>
  565. public string Format ()
  566. {
  567. var sb = new StringBuilder ();
  568. // Lines_get causes a Format
  569. foreach (string line in GetLines ())
  570. {
  571. sb.AppendLine (line);
  572. }
  573. return sb.ToString ().TrimEnd (Environment.NewLine.ToCharArray ());
  574. }
  575. /// <summary>Gets the size required to hold the formatted text, given the constraints placed by <see cref="Size"/>.</summary>
  576. /// <remarks>Causes a format, resetting <see cref="NeedsFormat"/> to <see langword="false"/>.</remarks>
  577. /// <returns>The size required to hold the formatted text.</returns>
  578. public Size FormatAndGetSize ()
  579. {
  580. if (string.IsNullOrEmpty (Text) || Size.Height == 0 || Size.Width == 0)
  581. {
  582. return Size.Empty;
  583. }
  584. int width = GetLines ().Max (static line => line.GetColumns ());
  585. int height = GetLines ().Count;
  586. return new (width, height);
  587. }
  588. /// <summary>Gets a list of formatted lines, constrained to <see cref="Size"/>.</summary>
  589. /// <remarks>
  590. /// <para>
  591. /// If the text needs to be formatted (if <see cref="NeedsFormat"/> is <see langword="true"/>)
  592. /// <see cref="Format(string, int, bool, bool, bool, int, TextDirection, bool)"/> will be called and upon return
  593. /// <see cref="NeedsFormat"/> will be <see langword="false"/>.
  594. /// </para>
  595. /// <para>
  596. /// If either of the dimensions of <see cref="Size"/> are zero, the text will not be formatted and no lines will
  597. /// be returned.
  598. /// </para>
  599. /// </remarks>
  600. public List<string> GetLines ()
  601. {
  602. // With this check, we protect against subclasses with overrides of Text
  603. if (string.IsNullOrEmpty (Text) || Size.Height == 0 || Size.Width == 0)
  604. {
  605. _lines = new List<string> { string.Empty };
  606. NeedsFormat = false;
  607. return _lines;
  608. }
  609. if (NeedsFormat)
  610. {
  611. string text = _text;
  612. if (FindHotKey (_text, HotKeySpecifier, out _hotKeyPos, out Key newHotKey))
  613. {
  614. HotKey = newHotKey;
  615. text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  616. text = ReplaceHotKeyWithTag (text, _hotKeyPos);
  617. }
  618. if (IsVerticalDirection (Direction))
  619. {
  620. int colsWidth = GetSumMaxCharWidth (text, 0, 1, TabWidth);
  621. _lines = Format (
  622. text,
  623. Size.Height,
  624. VerticalAlignment == VerticalTextAlignment.Justified,
  625. Size.Width > colsWidth && WordWrap,
  626. PreserveTrailingSpaces,
  627. TabWidth,
  628. Direction,
  629. MultiLine
  630. );
  631. if (!AutoSize)
  632. {
  633. colsWidth = GetMaxColsForWidth (_lines, Size.Width, TabWidth);
  634. if (_lines.Count > colsWidth)
  635. {
  636. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  637. }
  638. }
  639. }
  640. else
  641. {
  642. _lines = Format (
  643. text,
  644. Size.Width,
  645. Alignment == TextAlignment.Justified,
  646. Size.Height > 1 && WordWrap,
  647. PreserveTrailingSpaces,
  648. TabWidth,
  649. Direction,
  650. MultiLine
  651. );
  652. if (!AutoSize && _lines.Count > Size.Height)
  653. {
  654. _lines.RemoveRange (Size.Height, _lines.Count - Size.Height);
  655. }
  656. }
  657. NeedsFormat = false;
  658. }
  659. return _lines;
  660. }
  661. /// <summary>Event invoked when the <see cref="HotKey"/> is changed.</summary>
  662. public event EventHandler<KeyChangedEventArgs> HotKeyChanged;
  663. /// <summary>Sets <see cref="NeedsFormat"/> to <see langword="true"/> and returns the value.</summary>
  664. /// <typeparam name="T"></typeparam>
  665. /// <param name="value"></param>
  666. /// <returns></returns>
  667. private T EnableNeedsFormat<T> (T value)
  668. {
  669. NeedsFormat = true;
  670. return value;
  671. }
  672. #region Static Members
  673. /// <summary>Check if it is a horizontal direction</summary>
  674. public static bool IsHorizontalDirection (TextDirection textDirection)
  675. {
  676. return textDirection switch
  677. {
  678. TextDirection.LeftRight_TopBottom => true,
  679. TextDirection.LeftRight_BottomTop => true,
  680. TextDirection.RightLeft_TopBottom => true,
  681. TextDirection.RightLeft_BottomTop => true,
  682. _ => false
  683. };
  684. }
  685. /// <summary>Check if it is a vertical direction</summary>
  686. public static bool IsVerticalDirection (TextDirection textDirection)
  687. {
  688. return textDirection switch
  689. {
  690. TextDirection.TopBottom_LeftRight => true,
  691. TextDirection.TopBottom_RightLeft => true,
  692. TextDirection.BottomTop_LeftRight => true,
  693. TextDirection.BottomTop_RightLeft => true,
  694. _ => false
  695. };
  696. }
  697. /// <summary>Check if it is Left to Right direction</summary>
  698. public static bool IsLeftToRight (TextDirection textDirection)
  699. {
  700. return textDirection switch
  701. {
  702. TextDirection.LeftRight_TopBottom => true,
  703. TextDirection.LeftRight_BottomTop => true,
  704. _ => false
  705. };
  706. }
  707. /// <summary>Check if it is Top to Bottom direction</summary>
  708. public static bool IsTopToBottom (TextDirection textDirection)
  709. {
  710. return textDirection switch
  711. {
  712. TextDirection.TopBottom_LeftRight => true,
  713. TextDirection.TopBottom_RightLeft => true,
  714. _ => false
  715. };
  716. }
  717. // TODO: Move to StringExtensions?
  718. private static string StripCRLF (string str, bool keepNewLine = false)
  719. {
  720. List<Rune> runes = str.ToRuneList ();
  721. for (var i = 0; i < runes.Count; i++)
  722. {
  723. switch ((char)runes [i].Value)
  724. {
  725. case '\n':
  726. if (!keepNewLine)
  727. {
  728. runes.RemoveAt (i);
  729. }
  730. break;
  731. case '\r':
  732. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  733. {
  734. runes.RemoveAt (i);
  735. if (!keepNewLine)
  736. {
  737. runes.RemoveAt (i);
  738. }
  739. i++;
  740. }
  741. else
  742. {
  743. if (!keepNewLine)
  744. {
  745. runes.RemoveAt (i);
  746. }
  747. }
  748. break;
  749. }
  750. }
  751. return StringExtensions.ToString (runes);
  752. }
  753. // TODO: Move to StringExtensions?
  754. private static string ReplaceCRLFWithSpace (string str)
  755. {
  756. List<Rune> runes = str.ToRuneList ();
  757. for (var i = 0; i < runes.Count; i++)
  758. {
  759. switch (runes [i].Value)
  760. {
  761. case '\n':
  762. runes [i] = (Rune)' ';
  763. break;
  764. case '\r':
  765. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  766. {
  767. runes [i] = (Rune)' ';
  768. runes.RemoveAt (i + 1);
  769. i++;
  770. }
  771. else
  772. {
  773. runes [i] = (Rune)' ';
  774. }
  775. break;
  776. }
  777. }
  778. return StringExtensions.ToString (runes);
  779. }
  780. // TODO: Move to StringExtensions?
  781. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  782. {
  783. if (tabWidth == 0)
  784. {
  785. return str.Replace ("\t", "");
  786. }
  787. return str.Replace ("\t", new string (' ', tabWidth));
  788. }
  789. // TODO: Move to StringExtensions?
  790. /// <summary>
  791. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  792. /// ending newline.
  793. /// </summary>
  794. /// <param name="text">The text.</param>
  795. /// <returns>A list of text without the newline characters.</returns>
  796. public static List<string> SplitNewLine (string text)
  797. {
  798. List<Rune> runes = text.ToRuneList ();
  799. List<string> lines = new ();
  800. var start = 0;
  801. for (var i = 0; i < runes.Count; i++)
  802. {
  803. int end = i;
  804. switch (runes [i].Value)
  805. {
  806. case '\n':
  807. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  808. i++;
  809. start = i;
  810. break;
  811. case '\r':
  812. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  813. {
  814. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  815. i += 2;
  816. start = i;
  817. }
  818. else
  819. {
  820. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  821. i++;
  822. start = i;
  823. }
  824. break;
  825. }
  826. }
  827. switch (runes.Count)
  828. {
  829. case > 0 when lines.Count == 0:
  830. lines.Add (StringExtensions.ToString (runes));
  831. break;
  832. case > 0 when start < runes.Count:
  833. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  834. break;
  835. default:
  836. lines.Add ("");
  837. break;
  838. }
  839. return lines;
  840. }
  841. // TODO: Move to StringExtensions?
  842. /// <summary>
  843. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  844. /// columns. Note that some unicode characters take 2+ columns
  845. /// </summary>
  846. /// <param name="text"></param>
  847. /// <param name="width"></param>
  848. /// <returns></returns>
  849. public static string ClipOrPad (string text, int width)
  850. {
  851. if (string.IsNullOrEmpty (text))
  852. {
  853. return text;
  854. }
  855. // if value is not wide enough
  856. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  857. {
  858. // pad it out with spaces to the given alignment
  859. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  860. return text + new string (' ', toPad);
  861. }
  862. // value is too wide
  863. return new string (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  864. }
  865. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  866. /// <param name="text">The text to word wrap</param>
  867. /// <param name="width">The number of columns to constrain the text to</param>
  868. /// <param name="preserveTrailingSpaces">
  869. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  870. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  871. /// </param>
  872. /// <param name="tabWidth">The number of columns used for a tab.</param>
  873. /// <param name="textDirection">The text direction.</param>
  874. /// <returns>A list of word wrapped lines.</returns>
  875. /// <remarks>
  876. /// <para>This method does not do any justification.</para>
  877. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  878. /// <para>
  879. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  880. /// at the end of the last line.
  881. /// </para>
  882. /// </remarks>
  883. /// <returns>A list of lines.</returns>
  884. public static List<string> WordWrapText (
  885. string text,
  886. int width,
  887. bool preserveTrailingSpaces = false,
  888. int tabWidth = 0,
  889. TextDirection textDirection = TextDirection.LeftRight_TopBottom
  890. )
  891. {
  892. if (width < 0)
  893. {
  894. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  895. }
  896. int start = 0, end;
  897. List<string> lines = new ();
  898. if (string.IsNullOrEmpty (text))
  899. {
  900. return lines;
  901. }
  902. List<Rune> runes = StripCRLF (text).ToRuneList ();
  903. if (preserveTrailingSpaces)
  904. {
  905. while ((end = start) < runes.Count)
  906. {
  907. end = GetNextWhiteSpace (start, width, out bool incomplete);
  908. if (end == 0 && incomplete)
  909. {
  910. start = text.GetRuneCount ();
  911. break;
  912. }
  913. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  914. start = end;
  915. if (incomplete)
  916. {
  917. start = text.GetRuneCount ();
  918. break;
  919. }
  920. }
  921. }
  922. else
  923. {
  924. if (IsHorizontalDirection (textDirection))
  925. {
  926. while ((end = start
  927. + GetLengthThatFits (
  928. runes.GetRange (start, runes.Count - start),
  929. width,
  930. tabWidth
  931. ))
  932. < runes.Count)
  933. {
  934. while (runes [end].Value != ' ' && end > start)
  935. {
  936. end--;
  937. }
  938. if (end == start)
  939. {
  940. end = start
  941. + GetLengthThatFits (
  942. runes.GetRange (end, runes.Count - end),
  943. width,
  944. tabWidth
  945. );
  946. }
  947. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  948. if (end > start && GetRuneWidth (str, tabWidth) <= width)
  949. {
  950. lines.Add (str);
  951. start = end;
  952. if (runes [end].Value == ' ')
  953. {
  954. start++;
  955. }
  956. }
  957. else
  958. {
  959. end++;
  960. start = end;
  961. }
  962. }
  963. }
  964. else
  965. {
  966. while ((end = start + width) < runes.Count)
  967. {
  968. while (runes [end].Value != ' ' && end > start)
  969. {
  970. end--;
  971. }
  972. if (end == start)
  973. {
  974. end = start + width;
  975. }
  976. var zeroLength = 0;
  977. for (int i = end; i < runes.Count - start; i++)
  978. {
  979. Rune r = runes [i];
  980. if (r.GetColumns () == 0)
  981. {
  982. zeroLength++;
  983. }
  984. else
  985. {
  986. break;
  987. }
  988. }
  989. lines.Add (
  990. StringExtensions.ToString (
  991. runes.GetRange (
  992. start,
  993. end - start + zeroLength
  994. )
  995. )
  996. );
  997. end += zeroLength;
  998. start = end;
  999. if (runes [end].Value == ' ')
  1000. {
  1001. start++;
  1002. }
  1003. }
  1004. }
  1005. }
  1006. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1007. {
  1008. int to = from;
  1009. int length = cLength;
  1010. incomplete = false;
  1011. while (length < cWidth && to < runes.Count)
  1012. {
  1013. Rune rune = runes [to];
  1014. if (IsHorizontalDirection (textDirection))
  1015. {
  1016. length += rune.GetColumns ();
  1017. }
  1018. else
  1019. {
  1020. length++;
  1021. }
  1022. if (length > cWidth)
  1023. {
  1024. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1025. {
  1026. incomplete = true;
  1027. }
  1028. return to;
  1029. }
  1030. switch (rune.Value)
  1031. {
  1032. case ' ' when length == cWidth:
  1033. return to + 1;
  1034. case ' ' when length > cWidth:
  1035. return to;
  1036. case ' ':
  1037. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1038. case '\t':
  1039. {
  1040. length += tabWidth + 1;
  1041. if (length == tabWidth && tabWidth > cWidth)
  1042. {
  1043. return to + 1;
  1044. }
  1045. if (length > cWidth && tabWidth > cWidth)
  1046. {
  1047. return to;
  1048. }
  1049. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1050. }
  1051. default:
  1052. to++;
  1053. break;
  1054. }
  1055. }
  1056. return cLength switch
  1057. {
  1058. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1059. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1060. _ => to
  1061. };
  1062. }
  1063. if (start < text.GetRuneCount ())
  1064. {
  1065. string str = ReplaceTABWithSpaces (
  1066. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1067. tabWidth
  1068. );
  1069. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1070. {
  1071. lines.Add (str);
  1072. }
  1073. }
  1074. return lines;
  1075. }
  1076. /// <summary>Justifies text within a specified width.</summary>
  1077. /// <param name="text">The text to justify.</param>
  1078. /// <param name="width">
  1079. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1080. /// clipped.
  1081. /// </param>
  1082. /// <param name="talign">Alignment.</param>
  1083. /// <param name="textDirection">The text direction.</param>
  1084. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1085. /// <returns>Justified and clipped text.</returns>
  1086. public static string ClipAndJustify (
  1087. string text,
  1088. int width,
  1089. TextAlignment talign,
  1090. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1091. int tabWidth = 0
  1092. )
  1093. {
  1094. return ClipAndJustify (text, width, talign == TextAlignment.Justified, textDirection, tabWidth);
  1095. }
  1096. /// <summary>Justifies text within a specified width.</summary>
  1097. /// <param name="text">The text to justify.</param>
  1098. /// <param name="width">
  1099. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1100. /// clipped.
  1101. /// </param>
  1102. /// <param name="justify">Justify.</param>
  1103. /// <param name="textDirection">The text direction.</param>
  1104. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1105. /// <returns>Justified and clipped text.</returns>
  1106. public static string ClipAndJustify (
  1107. string text,
  1108. int width,
  1109. bool justify,
  1110. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1111. int tabWidth = 0
  1112. )
  1113. {
  1114. if (width < 0)
  1115. {
  1116. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1117. }
  1118. if (string.IsNullOrEmpty (text))
  1119. {
  1120. return text;
  1121. }
  1122. text = ReplaceTABWithSpaces (text, tabWidth);
  1123. List<Rune> runes = text.ToRuneList ();
  1124. if (runes.Count > width)
  1125. {
  1126. if (IsHorizontalDirection (textDirection))
  1127. {
  1128. return StringExtensions.ToString (
  1129. runes.GetRange (
  1130. 0,
  1131. GetLengthThatFits (text, width, tabWidth)
  1132. )
  1133. );
  1134. }
  1135. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1136. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1137. }
  1138. if (justify)
  1139. {
  1140. return Justify (text, width, ' ', textDirection, tabWidth);
  1141. }
  1142. if (IsHorizontalDirection (textDirection) && GetRuneWidth (text, tabWidth) > width)
  1143. {
  1144. return StringExtensions.ToString (
  1145. runes.GetRange (
  1146. 0,
  1147. GetLengthThatFits (text, width, tabWidth)
  1148. )
  1149. );
  1150. }
  1151. return text;
  1152. }
  1153. /// <summary>
  1154. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1155. /// <c>width</c>. Spaces will not be added to the start or end.
  1156. /// </summary>
  1157. /// <param name="text"></param>
  1158. /// <param name="width"></param>
  1159. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1160. /// <param name="textDirection">The text direction.</param>
  1161. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1162. /// <returns>The justified text.</returns>
  1163. public static string Justify (
  1164. string text,
  1165. int width,
  1166. char spaceChar = ' ',
  1167. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1168. int tabWidth = 0
  1169. )
  1170. {
  1171. if (width < 0)
  1172. {
  1173. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1174. }
  1175. if (string.IsNullOrEmpty (text))
  1176. {
  1177. return text;
  1178. }
  1179. text = ReplaceTABWithSpaces (text, tabWidth);
  1180. string [] words = text.Split (' ');
  1181. int textCount;
  1182. if (IsHorizontalDirection (textDirection))
  1183. {
  1184. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth));
  1185. }
  1186. else
  1187. {
  1188. textCount = words.Sum (arg => arg.GetRuneCount ());
  1189. }
  1190. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1191. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1192. var s = new StringBuilder ();
  1193. for (var w = 0; w < words.Length; w++)
  1194. {
  1195. string x = words [w];
  1196. s.Append (x);
  1197. if (w + 1 < words.Length)
  1198. {
  1199. for (var i = 0; i < spaces; i++)
  1200. {
  1201. s.Append (spaceChar);
  1202. }
  1203. }
  1204. if (extras > 0)
  1205. {
  1206. for (var i = 0; i < 1; i++)
  1207. {
  1208. s.Append (spaceChar);
  1209. }
  1210. extras--;
  1211. }
  1212. if (w + 1 == words.Length - 1)
  1213. {
  1214. for (var i = 0; i < extras; i++)
  1215. {
  1216. s.Append (spaceChar);
  1217. }
  1218. }
  1219. }
  1220. return s.ToString ();
  1221. }
  1222. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1223. /// <param name="text"></param>
  1224. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1225. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  1226. /// <param name="wordWrap">
  1227. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1228. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1229. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1230. /// </param>
  1231. /// <param name="preserveTrailingSpaces">
  1232. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1233. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1234. /// </param>
  1235. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1236. /// <param name="textDirection">The text direction.</param>
  1237. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1238. /// <returns>A list of word wrapped lines.</returns>
  1239. /// <remarks>
  1240. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1241. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1242. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1243. /// </remarks>
  1244. public static List<string> Format (
  1245. string text,
  1246. int width,
  1247. TextAlignment talign,
  1248. bool wordWrap,
  1249. bool preserveTrailingSpaces = false,
  1250. int tabWidth = 0,
  1251. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1252. bool multiLine = false
  1253. )
  1254. {
  1255. return Format (
  1256. text,
  1257. width,
  1258. talign == TextAlignment.Justified,
  1259. wordWrap,
  1260. preserveTrailingSpaces,
  1261. tabWidth,
  1262. textDirection,
  1263. multiLine
  1264. );
  1265. }
  1266. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1267. /// <param name="text"></param>
  1268. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1269. /// <param name="justify">Specifies whether the text should be justified.</param>
  1270. /// <param name="wordWrap">
  1271. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1272. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1273. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1274. /// </param>
  1275. /// <param name="preserveTrailingSpaces">
  1276. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1277. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1278. /// </param>
  1279. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1280. /// <param name="textDirection">The text direction.</param>
  1281. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1282. /// <returns>A list of word wrapped lines.</returns>
  1283. /// <remarks>
  1284. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1285. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1286. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1287. /// </remarks>
  1288. public static List<string> Format (
  1289. string text,
  1290. int width,
  1291. bool justify,
  1292. bool wordWrap,
  1293. bool preserveTrailingSpaces = false,
  1294. int tabWidth = 0,
  1295. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1296. bool multiLine = false
  1297. )
  1298. {
  1299. if (width < 0)
  1300. {
  1301. throw new ArgumentOutOfRangeException ($"{nameof (width)} cannot be negative.");
  1302. }
  1303. List<string> lineResult = new ();
  1304. if (string.IsNullOrEmpty (text) || width == 0)
  1305. {
  1306. lineResult.Add (string.Empty);
  1307. return lineResult;
  1308. }
  1309. if (!wordWrap)
  1310. {
  1311. text = ReplaceTABWithSpaces (text, tabWidth);
  1312. if (multiLine)
  1313. {
  1314. // Abhorrent case: Just a new line
  1315. if (text == "\n")
  1316. {
  1317. lineResult.Add (string.Empty);
  1318. return lineResult;
  1319. }
  1320. string [] lines = null;
  1321. if (text.Contains ("\r\n"))
  1322. {
  1323. lines = text.Split ("\r\n");
  1324. }
  1325. else if (text.Contains ('\n'))
  1326. {
  1327. lines = text.Split ('\n');
  1328. }
  1329. lines ??= new [] { text };
  1330. foreach (string line in lines)
  1331. {
  1332. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1333. }
  1334. return lineResult;
  1335. }
  1336. text = ReplaceCRLFWithSpace (text);
  1337. lineResult.Add (ClipAndJustify (text, width, justify, textDirection, tabWidth));
  1338. return lineResult;
  1339. }
  1340. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1341. int runeCount = runes.Count;
  1342. var lp = 0;
  1343. for (var i = 0; i < runeCount; i++)
  1344. {
  1345. Rune c = runes [i];
  1346. if (c.Value == '\n')
  1347. {
  1348. List<string> wrappedLines =
  1349. WordWrapText (
  1350. StringExtensions.ToString (runes.GetRange (lp, i - lp)),
  1351. width,
  1352. preserveTrailingSpaces,
  1353. tabWidth,
  1354. textDirection
  1355. );
  1356. foreach (string line in wrappedLines)
  1357. {
  1358. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1359. }
  1360. if (wrappedLines.Count == 0)
  1361. {
  1362. lineResult.Add (string.Empty);
  1363. }
  1364. lp = i + 1;
  1365. }
  1366. }
  1367. foreach (string line in WordWrapText (
  1368. StringExtensions.ToString (runes.GetRange (lp, runeCount - lp)),
  1369. width,
  1370. preserveTrailingSpaces,
  1371. tabWidth,
  1372. textDirection
  1373. ))
  1374. {
  1375. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1376. }
  1377. return lineResult;
  1378. }
  1379. /// <summary>Returns the number of lines needed to render the specified text given the width.</summary>
  1380. /// <remarks>Calls <see cref="Format()"/>.</remarks>
  1381. /// <returns>Number of lines.</returns>
  1382. /// <param name="text">Text, may contain newlines.</param>
  1383. /// <param name="width">The minimum width for the text.</param>
  1384. public static int GetLineCount (string text, int width)
  1385. {
  1386. List<string> result = Format (text, width, false, true);
  1387. return result.Count;
  1388. }
  1389. /// <summary>
  1390. /// Returns the maximum number of columns needed to render the text (single line or multiple lines, word wrapped)
  1391. /// given a number of columns to constrain the text to.
  1392. /// </summary>
  1393. /// <remarks>
  1394. /// Calls <see cref="Format()"/>. This API will return incorrect results if the text includes glyphs who's width
  1395. /// is dependent on surrounding glyphs (e.g. Arabic).
  1396. /// </remarks>
  1397. /// <returns>Width of the longest line after formatting the text constrained by <paramref name="maxColumns"/>.</returns>
  1398. /// <param name="text">Text, may contain newlines.</param>
  1399. /// <param name="maxColumns">The number of columns to constrain the text to for formatting.</param>
  1400. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1401. public static int GetWidestLineLength (string text, int maxColumns, int tabWidth = 0)
  1402. {
  1403. List<string> result = Format (text, maxColumns, false, true);
  1404. var max = 0;
  1405. result.ForEach (
  1406. s =>
  1407. {
  1408. var m = 0;
  1409. s.ToRuneList ().ForEach (r => m += GetRuneWidth (r, tabWidth));
  1410. if (m > max)
  1411. {
  1412. max = m;
  1413. }
  1414. }
  1415. );
  1416. return max;
  1417. }
  1418. /// <summary>
  1419. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1420. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1421. /// </summary>
  1422. /// <remarks>
  1423. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1424. /// glyphs (e.g. Arabic).
  1425. /// </remarks>
  1426. /// <param name="text">Text, may contain newlines.</param>
  1427. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1428. /// <returns>The length of the longest line.</returns>
  1429. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1430. {
  1431. List<string> result = SplitNewLine (text);
  1432. return result.Max (x => GetRuneWidth (x, tabWidth));
  1433. }
  1434. /// <summary>
  1435. /// Returns the number of columns in the widest line in the list based on the <paramref name="startIndex"/> and
  1436. /// the <paramref name="length"/>.
  1437. /// </summary>
  1438. /// <remarks>
  1439. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1440. /// glyphs (e.g. Arabic).
  1441. /// </remarks>
  1442. /// <param name="lines">The lines.</param>
  1443. /// <param name="startIndex">The start index.</param>
  1444. /// <param name="length">The length.</param>
  1445. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1446. /// <returns>The maximum characters width.</returns>
  1447. public static int GetWidestLineLength (
  1448. List<string> lines,
  1449. int startIndex = -1,
  1450. int length = -1,
  1451. int tabWidth = 0
  1452. )
  1453. {
  1454. var max = 0;
  1455. for (int i = startIndex == -1 ? 0 : startIndex;
  1456. i < (length == -1 ? lines.Count : startIndex + length);
  1457. i++)
  1458. {
  1459. string runes = lines [i];
  1460. if (runes.Length > 0)
  1461. {
  1462. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1463. }
  1464. }
  1465. return max;
  1466. }
  1467. /// <summary>
  1468. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1469. /// <paramref name="length"/>.
  1470. /// </summary>
  1471. /// <remarks>
  1472. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1473. /// glyphs (e.g. Arabic).
  1474. /// </remarks>
  1475. /// <param name="text">The text.</param>
  1476. /// <param name="startIndex">The start index.</param>
  1477. /// <param name="length">The length.</param>
  1478. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1479. /// <returns>The maximum characters width.</returns>
  1480. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1481. {
  1482. var max = 0;
  1483. Rune [] runes = text.ToRunes ();
  1484. for (int i = startIndex == -1 ? 0 : startIndex;
  1485. i < (length == -1 ? runes.Length : startIndex + length);
  1486. i++)
  1487. {
  1488. max += GetRuneWidth (runes [i], tabWidth);
  1489. }
  1490. return max;
  1491. }
  1492. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="columns"/>.</summary>
  1493. /// <remarks>
  1494. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1495. /// glyphs (e.g. Arabic).
  1496. /// </remarks>
  1497. /// <param name="text">The text.</param>
  1498. /// <param name="columns">The width.</param>
  1499. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1500. /// <returns>The index of the text that fit the width.</returns>
  1501. public static int GetLengthThatFits (string text, int columns, int tabWidth = 0) { return GetLengthThatFits (text?.ToRuneList (), columns, tabWidth); }
  1502. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="columns"/>.</summary>
  1503. /// <remarks>
  1504. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1505. /// glyphs (e.g. Arabic).
  1506. /// </remarks>
  1507. /// <param name="runes">The list of runes.</param>
  1508. /// <param name="columns">The width.</param>
  1509. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1510. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="columns"/>.</returns>
  1511. public static int GetLengthThatFits (List<Rune> runes, int columns, int tabWidth = 0)
  1512. {
  1513. if (runes is null || runes.Count == 0)
  1514. {
  1515. return 0;
  1516. }
  1517. var runesLength = 0;
  1518. var runeIdx = 0;
  1519. for (; runeIdx < runes.Count; runeIdx++)
  1520. {
  1521. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth);
  1522. if (runesLength + runeWidth > columns)
  1523. {
  1524. break;
  1525. }
  1526. runesLength += runeWidth;
  1527. }
  1528. return runeIdx;
  1529. }
  1530. private static int GetRuneWidth (string str, int tabWidth) { return GetRuneWidth (str.EnumerateRunes ().ToList (), tabWidth); }
  1531. private static int GetRuneWidth (List<Rune> runes, int tabWidth) { return runes.Sum (r => GetRuneWidth (r, tabWidth)); }
  1532. private static int GetRuneWidth (Rune rune, int tabWidth)
  1533. {
  1534. int runeWidth = rune.GetColumns ();
  1535. if (rune.Value == '\t')
  1536. {
  1537. return tabWidth;
  1538. }
  1539. if (runeWidth < 0 || runeWidth > 0)
  1540. {
  1541. return Math.Max (runeWidth, 1);
  1542. }
  1543. return runeWidth;
  1544. }
  1545. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  1546. /// <remarks>
  1547. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1548. /// glyphs (e.g. Arabic).
  1549. /// </remarks>
  1550. /// <param name="lines">The lines.</param>
  1551. /// <param name="width">The width.</param>
  1552. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1553. /// <returns>The index of the list that fit the width.</returns>
  1554. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  1555. {
  1556. var runesLength = 0;
  1557. var lineIdx = 0;
  1558. for (; lineIdx < lines.Count; lineIdx++)
  1559. {
  1560. List<Rune> runes = lines [lineIdx].ToRuneList ();
  1561. int maxRruneWidth = runes.Count > 0
  1562. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  1563. : 1;
  1564. if (runesLength + maxRruneWidth > width)
  1565. {
  1566. break;
  1567. }
  1568. runesLength += maxRruneWidth;
  1569. }
  1570. return lineIdx;
  1571. }
  1572. /// <summary>Calculates the rectangle required to hold text, assuming no word wrapping, justification, or hotkeys.</summary>
  1573. /// <remarks>
  1574. /// This API will return incorrect results if the text includes glyphs who's width is dependent on surrounding
  1575. /// glyphs (e.g. Arabic).
  1576. /// </remarks>
  1577. /// <param name="x">The x location of the rectangle</param>
  1578. /// <param name="y">The y location of the rectangle</param>
  1579. /// <param name="text">The text to measure</param>
  1580. /// <param name="direction">The text direction.</param>
  1581. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1582. /// <returns></returns>
  1583. public static Rectangle CalcRect (
  1584. int x,
  1585. int y,
  1586. string text,
  1587. TextDirection direction = TextDirection.LeftRight_TopBottom,
  1588. int tabWidth = 0
  1589. )
  1590. {
  1591. if (string.IsNullOrEmpty (text))
  1592. {
  1593. return new (new (x, y), Size.Empty);
  1594. }
  1595. int w, h;
  1596. if (IsHorizontalDirection (direction))
  1597. {
  1598. var mw = 0;
  1599. var ml = 1;
  1600. var cols = 0;
  1601. foreach (Rune rune in text.EnumerateRunes ())
  1602. {
  1603. if (rune.Value == '\n')
  1604. {
  1605. ml++;
  1606. if (cols > mw)
  1607. {
  1608. mw = cols;
  1609. }
  1610. cols = 0;
  1611. }
  1612. else if (rune.Value != '\r')
  1613. {
  1614. cols++;
  1615. var rw = 0;
  1616. if (rune.Value == '\t')
  1617. {
  1618. rw += tabWidth - 1;
  1619. }
  1620. else
  1621. {
  1622. rw = rune.GetColumns ();
  1623. if (rw > 0)
  1624. {
  1625. rw--;
  1626. }
  1627. else if (rw == 0)
  1628. {
  1629. cols--;
  1630. }
  1631. }
  1632. cols += rw;
  1633. }
  1634. }
  1635. if (cols > mw)
  1636. {
  1637. mw = cols;
  1638. }
  1639. w = mw;
  1640. h = ml;
  1641. }
  1642. else
  1643. {
  1644. int vw = 1, cw = 1;
  1645. var vh = 0;
  1646. var rows = 0;
  1647. foreach (Rune rune in text.EnumerateRunes ())
  1648. {
  1649. if (rune.Value == '\n')
  1650. {
  1651. vw++;
  1652. if (rows > vh)
  1653. {
  1654. vh = rows;
  1655. }
  1656. rows = 0;
  1657. cw = 1;
  1658. }
  1659. else if (rune.Value != '\r')
  1660. {
  1661. rows++;
  1662. var rw = 0;
  1663. if (rune.Value == '\t')
  1664. {
  1665. rw += tabWidth - 1;
  1666. rows += rw;
  1667. }
  1668. else
  1669. {
  1670. rw = rune.GetColumns ();
  1671. if (rw == 0)
  1672. {
  1673. rows--;
  1674. }
  1675. else if (cw < rw)
  1676. {
  1677. cw = rw;
  1678. vw++;
  1679. }
  1680. }
  1681. }
  1682. }
  1683. if (rows > vh)
  1684. {
  1685. vh = rows;
  1686. }
  1687. w = vw;
  1688. h = vh;
  1689. }
  1690. return new (x, y, w, h);
  1691. }
  1692. /// <summary>Finds the HotKey and its location in text.</summary>
  1693. /// <param name="text">The text to look in.</param>
  1694. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  1695. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  1696. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  1697. /// <param name="firstUpperCase">
  1698. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  1699. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  1700. /// Defaults to <see langword="false"/>.
  1701. /// </param>
  1702. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  1703. public static bool FindHotKey (
  1704. string text,
  1705. Rune hotKeySpecifier,
  1706. out int hotPos,
  1707. out Key hotKey,
  1708. bool firstUpperCase = false
  1709. )
  1710. {
  1711. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  1712. {
  1713. hotPos = -1;
  1714. hotKey = Key.Empty;
  1715. return false;
  1716. }
  1717. var curHotKey = (Rune)0;
  1718. int curHotPos = -1;
  1719. // Use first hot_key char passed into 'hotKey'.
  1720. // TODO: Ignore hot_key of two are provided
  1721. // TODO: Do not support non-alphanumeric chars that can't be typed
  1722. var i = 0;
  1723. foreach (Rune c in text.EnumerateRunes ())
  1724. {
  1725. if ((char)c.Value != 0xFFFD)
  1726. {
  1727. if (c == hotKeySpecifier)
  1728. {
  1729. curHotPos = i;
  1730. }
  1731. else if (curHotPos > -1)
  1732. {
  1733. curHotKey = c;
  1734. break;
  1735. }
  1736. }
  1737. i++;
  1738. }
  1739. // Legacy support - use first upper case char if the specifier was not found
  1740. if (curHotPos == -1 && firstUpperCase)
  1741. {
  1742. i = 0;
  1743. foreach (Rune c in text.EnumerateRunes ())
  1744. {
  1745. if ((char)c.Value != 0xFFFD)
  1746. {
  1747. if (Rune.IsUpper (c))
  1748. {
  1749. curHotKey = c;
  1750. curHotPos = i;
  1751. break;
  1752. }
  1753. }
  1754. i++;
  1755. }
  1756. }
  1757. if (curHotKey != (Rune)0 && curHotPos != -1)
  1758. {
  1759. hotPos = curHotPos;
  1760. var newHotKey = (KeyCode)curHotKey.Value;
  1761. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  1762. {
  1763. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  1764. {
  1765. newHotKey &= ~KeyCode.Space;
  1766. }
  1767. hotKey = newHotKey;
  1768. //hotKey.Scope = KeyBindingScope.HotKey;
  1769. return true;
  1770. }
  1771. }
  1772. hotPos = -1;
  1773. hotKey = KeyCode.Null;
  1774. return false;
  1775. }
  1776. /// <summary>
  1777. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  1778. /// hotkey.
  1779. /// </summary>
  1780. /// <param name="text">The text to tag the hotkey in.</param>
  1781. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  1782. /// <returns>The text with the hotkey tagged.</returns>
  1783. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  1784. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  1785. {
  1786. // Set the high bit
  1787. List<Rune> runes = text.ToRuneList ();
  1788. if (Rune.IsLetterOrDigit (runes [hotPos]))
  1789. {
  1790. runes [hotPos] = new Rune ((uint)runes [hotPos].Value);
  1791. }
  1792. return StringExtensions.ToString (runes);
  1793. }
  1794. /// <summary>Removes the hotkey specifier from text.</summary>
  1795. /// <param name="text">The text to manipulate.</param>
  1796. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  1797. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  1798. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  1799. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  1800. {
  1801. if (string.IsNullOrEmpty (text))
  1802. {
  1803. return text;
  1804. }
  1805. // Scan
  1806. var start = string.Empty;
  1807. var i = 0;
  1808. foreach (Rune c in text)
  1809. {
  1810. if (c == hotKeySpecifier && i == hotPos)
  1811. {
  1812. i++;
  1813. continue;
  1814. }
  1815. start += c;
  1816. i++;
  1817. }
  1818. return start;
  1819. }
  1820. #endregion // Static Members
  1821. }