TextView.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  1. //
  2. // TextView.cs: multi-line text editing
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. //
  8. // TODO:
  9. // In ReadOnly mode backspace/space behave like pageup/pagedown
  10. // Attributed text on spans
  11. // Replace insertion with Insert method
  12. // String accumulation (Control-k, control-k is not preserving the last new line, see StringToRunes
  13. // Alt-D, Alt-Backspace
  14. // API to set the cursor position
  15. // API to scroll to a particular place
  16. // keybindings to go to top/bottom
  17. // public API to insert, remove ranges
  18. // Add word forward/word backwards commands
  19. // Save buffer API
  20. // Mouse
  21. //
  22. // Desirable:
  23. // Move all the text manipulation into the TextModel
  24. using System;
  25. using System.Collections.Generic;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Text;
  29. using NStack;
  30. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public bool LoadFile (string file)
  35. {
  36. if (file == null)
  37. throw new ArgumentNullException (nameof (file));
  38. try {
  39. FilePath = file;
  40. var stream = File.OpenRead (file);
  41. } catch {
  42. return false;
  43. }
  44. LoadStream (File.OpenRead (file));
  45. return true;
  46. }
  47. public bool CloseFile ()
  48. {
  49. if (FilePath == null)
  50. throw new ArgumentNullException (nameof (FilePath));
  51. try {
  52. FilePath = null;
  53. lines = new List<List<Rune>> ();
  54. } catch {
  55. return false;
  56. }
  57. return true;
  58. }
  59. // Turns the ustring into runes, this does not split the
  60. // contents on a newline if it is present.
  61. internal static List<Rune> ToRunes (ustring str)
  62. {
  63. List<Rune> runes = new List<Rune> ();
  64. foreach (var x in str.ToRunes ()) {
  65. runes.Add (x);
  66. }
  67. return runes;
  68. }
  69. // Splits a string into a List that contains a List<Rune> for each line
  70. public static List<List<Rune>> StringToRunes (ustring content)
  71. {
  72. var lines = new List<List<Rune>> ();
  73. int start = 0, i = 0;
  74. // BUGBUG: I think this is buggy w.r.t Unicode. content.Length is bytes, and content[i] is bytes
  75. // and content[i] == 10 may be the middle of a Rune.
  76. for (; i < content.Length; i++) {
  77. if (content [i] == 10) {
  78. if (i - start > 0)
  79. lines.Add (ToRunes (content [start, i]));
  80. else
  81. lines.Add (ToRunes (ustring.Empty));
  82. start = i + 1;
  83. }
  84. }
  85. if (i - start >= 0)
  86. lines.Add (ToRunes (content [start, null]));
  87. return lines;
  88. }
  89. void Append (List<byte> line)
  90. {
  91. var str = ustring.Make (line.ToArray ());
  92. lines.Add (ToRunes (str));
  93. }
  94. public void LoadStream (Stream input)
  95. {
  96. if (input == null)
  97. throw new ArgumentNullException (nameof (input));
  98. lines = new List<List<Rune>> ();
  99. var buff = new BufferedStream (input);
  100. int v;
  101. var line = new List<byte> ();
  102. while ((v = buff.ReadByte ()) != -1) {
  103. if (v == 10) {
  104. Append (line);
  105. line.Clear ();
  106. continue;
  107. }
  108. line.Add ((byte)v);
  109. }
  110. if (line.Count > 0)
  111. Append (line);
  112. }
  113. public void LoadString (ustring content)
  114. {
  115. lines = StringToRunes (content);
  116. }
  117. public override string ToString ()
  118. {
  119. var sb = new StringBuilder ();
  120. for (int i = 0; i < lines.Count; i++) {
  121. sb.Append (ustring.Make (lines[i]));
  122. if ((i + 1) < lines.Count) {
  123. sb.AppendLine ();
  124. }
  125. }
  126. return sb.ToString ();
  127. }
  128. public string FilePath { get; set; }
  129. /// <summary>
  130. /// The number of text lines in the model
  131. /// </summary>
  132. public int Count => lines.Count;
  133. /// <summary>
  134. /// Returns the specified line as a List of Rune
  135. /// </summary>
  136. /// <returns>The line.</returns>
  137. /// <param name="line">Line number to retrieve.</param>
  138. public List<Rune> GetLine (int line) => line < Count ? lines [line] : lines [Count - 1];
  139. /// <summary>
  140. /// Adds a line to the model at the specified position.
  141. /// </summary>
  142. /// <param name="pos">Line number where the line will be inserted.</param>
  143. /// <param name="runes">The line of text, as a List of Rune.</param>
  144. public void AddLine (int pos, List<Rune> runes)
  145. {
  146. lines.Insert (pos, runes);
  147. }
  148. /// <summary>
  149. /// Removes the line at the specified position
  150. /// </summary>
  151. /// <param name="pos">Position.</param>
  152. public void RemoveLine (int pos)
  153. {
  154. lines.RemoveAt (pos);
  155. }
  156. internal static int SetCol (int col, int width, int cols)
  157. {
  158. if (col + cols <= width) {
  159. col += cols;
  160. }
  161. return col;
  162. }
  163. internal static int GetColFromX (List<Rune> t, int start, int x)
  164. {
  165. if (x < 0) {
  166. return x;
  167. }
  168. int size = start;
  169. var pX = x + start;
  170. for (int i = start; i < t.Count; i++) {
  171. var r = t [i];
  172. size += Rune.ColumnWidth (r);
  173. if (i == pX || (size > pX)) {
  174. return i - start;
  175. }
  176. }
  177. return t.Count - start;
  178. }
  179. // Returns the size and length in a range of the string.
  180. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1, bool checkNextRune = true)
  181. {
  182. if (t == null || t.Count == 0) {
  183. return (0, 0);
  184. }
  185. int size = 0;
  186. int len = 0;
  187. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  188. int i = start == -1 ? 0 : start;
  189. for (; i < tcount; i++) {
  190. var rune = t [i];
  191. size += Rune.ColumnWidth (rune);
  192. len += Rune.RuneLen (rune);
  193. if (checkNextRune && i == tcount - 1 && t.Count > tcount && Rune.ColumnWidth (t [i + 1]) > 1) {
  194. size += Rune.ColumnWidth (t [i + 1]);
  195. len += Rune.RuneLen (t [i + 1]);
  196. }
  197. }
  198. return (size, len);
  199. }
  200. // Returns the left column in a range of the string.
  201. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int currentColumn)
  202. {
  203. if (t == null) {
  204. return 0;
  205. }
  206. (var dSize, _) = TextModel.DisplaySize (t, start, end);
  207. if (dSize < width) {
  208. return start;
  209. }
  210. int size = 0;
  211. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  212. int col = 0;
  213. for (int i = tcount; i > start; i--) {
  214. var rune = t [i];
  215. var s = Rune.ColumnWidth (rune);
  216. size += s;
  217. if (size >= dSize - width) {
  218. col = tcount - i + start;
  219. if (start == 0 || col == start || (currentColumn == t.Count && (currentColumn - col > width))) {
  220. col++;
  221. }
  222. break;
  223. }
  224. }
  225. return col;
  226. }
  227. }
  228. /// <summary>
  229. /// Multi-line text editing <see cref="View"/>
  230. /// </summary>
  231. /// <remarks>
  232. /// <para>
  233. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  234. /// with it with the standard Emacs commands for movement or the arrow
  235. /// keys.
  236. /// </para>
  237. /// <list type="table">
  238. /// <listheader>
  239. /// <term>Shortcut</term>
  240. /// <description>Action performed</description>
  241. /// </listheader>
  242. /// <item>
  243. /// <term>Left cursor, Control-b</term>
  244. /// <description>
  245. /// Moves the editing point left.
  246. /// </description>
  247. /// </item>
  248. /// <item>
  249. /// <term>Right cursor, Control-f</term>
  250. /// <description>
  251. /// Moves the editing point right.
  252. /// </description>
  253. /// </item>
  254. /// <item>
  255. /// <term>Alt-b</term>
  256. /// <description>
  257. /// Moves one word back.
  258. /// </description>
  259. /// </item>
  260. /// <item>
  261. /// <term>Alt-f</term>
  262. /// <description>
  263. /// Moves one word forward.
  264. /// </description>
  265. /// </item>
  266. /// <item>
  267. /// <term>Up cursor, Control-p</term>
  268. /// <description>
  269. /// Moves the editing point one line up.
  270. /// </description>
  271. /// </item>
  272. /// <item>
  273. /// <term>Down cursor, Control-n</term>
  274. /// <description>
  275. /// Moves the editing point one line down
  276. /// </description>
  277. /// </item>
  278. /// <item>
  279. /// <term>Home key, Control-a</term>
  280. /// <description>
  281. /// Moves the cursor to the beginning of the line.
  282. /// </description>
  283. /// </item>
  284. /// <item>
  285. /// <term>End key, Control-e</term>
  286. /// <description>
  287. /// Moves the cursor to the end of the line.
  288. /// </description>
  289. /// </item>
  290. /// <item>
  291. /// <term>Control-Home</term>
  292. /// <description>
  293. /// Scrolls to the first line and moves the cursor there.
  294. /// </description>
  295. /// </item>
  296. /// <item>
  297. /// <term>Control-End</term>
  298. /// <description>
  299. /// Scrolls to the last line and moves the cursor there.
  300. /// </description>
  301. /// </item>
  302. /// <item>
  303. /// <term>Delete, Control-d</term>
  304. /// <description>
  305. /// Deletes the character in front of the cursor.
  306. /// </description>
  307. /// </item>
  308. /// <item>
  309. /// <term>Backspace</term>
  310. /// <description>
  311. /// Deletes the character behind the cursor.
  312. /// </description>
  313. /// </item>
  314. /// <item>
  315. /// <term>Control-k</term>
  316. /// <description>
  317. /// Deletes the text until the end of the line and replaces the kill buffer
  318. /// with the deleted text. You can paste this text in a different place by
  319. /// using Control-y.
  320. /// </description>
  321. /// </item>
  322. /// <item>
  323. /// <term>Control-y</term>
  324. /// <description>
  325. /// Pastes the content of the kill ring into the current position.
  326. /// </description>
  327. /// </item>
  328. /// <item>
  329. /// <term>Alt-d</term>
  330. /// <description>
  331. /// Deletes the word above the cursor and adds it to the kill ring. You
  332. /// can paste the contents of the kill ring with Control-y.
  333. /// </description>
  334. /// </item>
  335. /// <item>
  336. /// <term>Control-q</term>
  337. /// <description>
  338. /// Quotes the next input character, to prevent the normal processing of
  339. /// key handling to take place.
  340. /// </description>
  341. /// </item>
  342. /// </list>
  343. /// </remarks>
  344. public class TextView : View {
  345. TextModel model = new TextModel ();
  346. int topRow;
  347. int leftColumn;
  348. int currentRow;
  349. int currentColumn;
  350. int selectionStartColumn, selectionStartRow;
  351. bool selecting;
  352. //bool used;
  353. /// <summary>
  354. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  355. /// </summary>
  356. public event Action TextChanged;
  357. #if false
  358. /// <summary>
  359. /// Changed event, raised when the text has clicked.
  360. /// </summary>
  361. /// <remarks>
  362. /// Client code can hook up to this event, it is
  363. /// raised when the text in the entry changes.
  364. /// </remarks>
  365. public Action Changed;
  366. #endif
  367. /// <summary>
  368. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  369. /// </summary>
  370. /// <remarks>
  371. /// </remarks>
  372. public TextView (Rect frame) : base (frame)
  373. {
  374. CanFocus = true;
  375. }
  376. /// <summary>
  377. /// Initializes a <see cref="TextView"/> on the specified area,
  378. /// with dimensions controlled with the X, Y, Width and Height properties.
  379. /// </summary>
  380. public TextView () : base ()
  381. {
  382. CanFocus = true;
  383. }
  384. void ResetPosition ()
  385. {
  386. topRow = leftColumn = currentRow = currentColumn = 0;
  387. }
  388. /// <summary>
  389. /// Sets or gets the text in the <see cref="TextView"/>.
  390. /// </summary>
  391. /// <remarks>
  392. /// </remarks>
  393. public override ustring Text {
  394. get {
  395. return model.ToString ();
  396. }
  397. set {
  398. ResetPosition ();
  399. model.LoadString (value);
  400. TextChanged?.Invoke ();
  401. SetNeedsDisplay ();
  402. }
  403. }
  404. /// <summary>
  405. /// Loads the contents of the file into the <see cref="TextView"/>.
  406. /// </summary>
  407. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  408. /// <param name="path">Path to the file to load.</param>
  409. public bool LoadFile (string path)
  410. {
  411. if (path == null)
  412. throw new ArgumentNullException (nameof (path));
  413. ResetPosition ();
  414. var res = model.LoadFile (path);
  415. SetNeedsDisplay ();
  416. return res;
  417. }
  418. /// <summary>
  419. /// Loads the contents of the stream into the <see cref="TextView"/>.
  420. /// </summary>
  421. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  422. /// <param name="stream">Stream to load the contents from.</param>
  423. public void LoadStream (Stream stream)
  424. {
  425. if (stream == null)
  426. throw new ArgumentNullException (nameof (stream));
  427. ResetPosition ();
  428. model.LoadStream (stream);
  429. SetNeedsDisplay ();
  430. }
  431. /// <summary>
  432. /// Closes the contents of the stream into the <see cref="TextView"/>.
  433. /// </summary>
  434. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  435. public bool CloseFile ()
  436. {
  437. ResetPosition ();
  438. var res = model.CloseFile ();
  439. SetNeedsDisplay ();
  440. return res;
  441. }
  442. /// <summary>
  443. /// Gets the current cursor row.
  444. /// </summary>
  445. public int CurrentRow => currentRow;
  446. /// <summary>
  447. /// Gets the cursor column.
  448. /// </summary>
  449. /// <value>The cursor column.</value>
  450. public int CurrentColumn => currentColumn;
  451. /// <summary>
  452. /// Positions the cursor on the current row and column
  453. /// </summary>
  454. public override void PositionCursor ()
  455. {
  456. if (selecting) {
  457. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  458. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  459. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  460. }
  461. var line = model.GetLine (currentRow);
  462. var retreat = 0;
  463. var col = 0;
  464. if (line.Count > 0) {
  465. retreat = Math.Max ((SpecialRune (line [Math.Max (CurrentColumn - leftColumn - 1, 0)])
  466. ? 1 : 0), 0);
  467. for (int idx = leftColumn < 0 ? 0 : leftColumn; idx < line.Count; idx++) {
  468. if (idx == CurrentColumn)
  469. break;
  470. var cols = Rune.ColumnWidth (line [idx]);
  471. col += cols - 1;
  472. }
  473. }
  474. Move (CurrentColumn - leftColumn - retreat + col, CurrentRow - topRow);
  475. }
  476. void ClearRegion (int left, int top, int right, int bottom)
  477. {
  478. for (int row = top; row < bottom; row++) {
  479. Move (left, row);
  480. for (int col = left; col < right; col++)
  481. AddRune (col, row, ' ');
  482. }
  483. }
  484. void ColorNormal ()
  485. {
  486. Driver.SetAttribute (ColorScheme.Normal);
  487. }
  488. void ColorSelection ()
  489. {
  490. if (HasFocus)
  491. Driver.SetAttribute (ColorScheme.Focus);
  492. else
  493. Driver.SetAttribute (ColorScheme.Normal);
  494. }
  495. bool isReadOnly = false;
  496. /// <summary>
  497. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  498. /// </summary>
  499. /// <value>Boolean value(Default false)</value>
  500. public bool ReadOnly {
  501. get => isReadOnly;
  502. set {
  503. isReadOnly = value;
  504. }
  505. }
  506. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  507. void GetEncodedRegionBounds (out long start, out long end)
  508. {
  509. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  510. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  511. if (selection > point) {
  512. start = point;
  513. end = selection;
  514. } else {
  515. start = selection;
  516. end = point;
  517. }
  518. }
  519. bool PointInSelection (int col, int row)
  520. {
  521. long start, end;
  522. GetEncodedRegionBounds (out start, out end);
  523. var q = ((long)(uint)row << 32) | (uint)col;
  524. return q >= start && q <= end;
  525. }
  526. //
  527. // Returns a ustring with the text in the selected
  528. // region.
  529. //
  530. ustring GetRegion ()
  531. {
  532. long start, end;
  533. GetEncodedRegionBounds (out start, out end);
  534. int startRow = (int)(start >> 32);
  535. var maxrow = ((int)(end >> 32));
  536. int startCol = (int)(start & 0xffffffff);
  537. var endCol = (int)(end & 0xffffffff);
  538. var line = model.GetLine (startRow);
  539. if (startRow == maxrow)
  540. return StringFromRunes (line.GetRange (startCol, endCol));
  541. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  542. for (int row = startRow + 1; row < maxrow; row++) {
  543. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  544. }
  545. line = model.GetLine (maxrow);
  546. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  547. return res;
  548. }
  549. //
  550. // Clears the contents of the selected region
  551. //
  552. void ClearRegion ()
  553. {
  554. long start, end;
  555. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  556. GetEncodedRegionBounds (out start, out end);
  557. int startRow = (int)(start >> 32);
  558. var maxrow = ((int)(end >> 32));
  559. int startCol = (int)(start & 0xffffffff);
  560. var endCol = (int)(end & 0xffffffff);
  561. var line = model.GetLine (startRow);
  562. if (startRow == maxrow) {
  563. line.RemoveRange (startCol, endCol - startCol);
  564. currentColumn = startCol;
  565. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  566. return;
  567. }
  568. line.RemoveRange (startCol, line.Count - startCol);
  569. var line2 = model.GetLine (maxrow);
  570. line.AddRange (line2.Skip (endCol));
  571. for (int row = startRow + 1; row <= maxrow; row++) {
  572. model.RemoveLine (startRow + 1);
  573. }
  574. if (currentEncoded == end) {
  575. currentRow -= maxrow - (startRow);
  576. }
  577. currentColumn = startCol;
  578. SetNeedsDisplay ();
  579. }
  580. ///<inheritdoc/>
  581. public override void Redraw (Rect bounds)
  582. {
  583. ColorNormal ();
  584. int bottom = bounds.Bottom;
  585. int right = bounds.Right;
  586. for (int row = bounds.Top; row < bottom; row++) {
  587. int textLine = topRow + row;
  588. if (textLine >= model.Count) {
  589. ColorNormal ();
  590. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  591. continue;
  592. }
  593. var line = model.GetLine (textLine);
  594. int lineRuneCount = line.Count;
  595. if (line.Count < bounds.Left) {
  596. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  597. continue;
  598. }
  599. Move (bounds.Left, row);
  600. var col = 0;
  601. for (int idx = bounds.Left; idx < right; idx++) {
  602. var lineCol = leftColumn + idx;
  603. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  604. var cols = Rune.ColumnWidth (rune);
  605. if (selecting && PointInSelection (idx, row)) {
  606. ColorSelection ();
  607. } else {
  608. ColorNormal ();
  609. }
  610. if (!SpecialRune (rune)) {
  611. AddRune (col, row, rune);
  612. }
  613. col = TextModel.SetCol (col, bounds.Right, cols);
  614. }
  615. }
  616. PositionCursor ();
  617. }
  618. bool SpecialRune (Rune rune)
  619. {
  620. switch (rune) {
  621. case (uint)Key.Enter:
  622. case 0xd:
  623. return true;
  624. default:
  625. return false; }
  626. }
  627. ///<inheritdoc/>
  628. public override bool CanFocus {
  629. get => base.CanFocus;
  630. set { base.CanFocus = value; }
  631. }
  632. void SetClipboard (ustring text)
  633. {
  634. Clipboard.Contents = text;
  635. }
  636. void AppendClipboard (ustring text)
  637. {
  638. Clipboard.Contents = Clipboard.Contents + text;
  639. }
  640. void Insert (Rune rune)
  641. {
  642. var line = GetCurrentLine ();
  643. line.Insert (currentColumn, rune);
  644. var prow = currentRow - topRow;
  645. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  646. }
  647. ustring StringFromRunes (List<Rune> runes)
  648. {
  649. if (runes == null)
  650. throw new ArgumentNullException (nameof (runes));
  651. int size = 0;
  652. foreach (var rune in runes) {
  653. size += Utf8.RuneLen (rune);
  654. }
  655. var encoded = new byte [size];
  656. int offset = 0;
  657. foreach (var rune in runes) {
  658. offset += Utf8.EncodeRune (rune, encoded, offset);
  659. }
  660. return ustring.Make (encoded);
  661. }
  662. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  663. void InsertText (ustring text)
  664. {
  665. if (ustring.IsNullOrEmpty (text)) {
  666. return;
  667. }
  668. var lines = TextModel.StringToRunes (text);
  669. if (lines.Count == 0) {
  670. return;
  671. }
  672. var line = GetCurrentLine ();
  673. // Optimize single line
  674. if (lines.Count == 1) {
  675. line.InsertRange (currentColumn, lines [0]);
  676. currentColumn += lines [0].Count;
  677. if (currentColumn - leftColumn > Frame.Width) {
  678. leftColumn = currentColumn - Frame.Width + 1;
  679. }
  680. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  681. return;
  682. }
  683. // Keep a copy of the rest of the line
  684. var restCount = line.Count - currentColumn;
  685. var rest = line.GetRange (currentColumn, restCount);
  686. line.RemoveRange (currentColumn, restCount);
  687. // First line is inserted at the current location, the rest is appended
  688. line.InsertRange (currentColumn, lines [0]);
  689. for (int i = 1; i < lines.Count; i++) {
  690. model.AddLine (currentRow + i, lines [i]);
  691. }
  692. var last = model.GetLine (currentRow + lines.Count - 1);
  693. var lastp = last.Count;
  694. last.InsertRange (last.Count, rest);
  695. // Now adjust column and row positions
  696. currentRow += lines.Count - 1;
  697. currentColumn = lastp;
  698. Adjust ();
  699. }
  700. // The column we are tracking, or -1 if we are not tracking any column
  701. int columnTrack = -1;
  702. // Tries to snap the cursor to the tracking column
  703. void TrackColumn ()
  704. {
  705. // Now track the column
  706. var line = GetCurrentLine ();
  707. if (line.Count < columnTrack)
  708. currentColumn = line.Count;
  709. else if (columnTrack != -1)
  710. currentColumn = columnTrack;
  711. else if (currentColumn > line.Count)
  712. currentColumn = line.Count;
  713. Adjust ();
  714. }
  715. void Adjust ()
  716. {
  717. int offB = OffSetBackground ();
  718. var line = GetCurrentLine ();
  719. bool need = false;
  720. if (currentColumn < leftColumn) {
  721. leftColumn = currentColumn;
  722. need = true;
  723. } else if (currentColumn - leftColumn > Frame.Width + offB ||
  724. TextModel.DisplaySize (line, leftColumn, currentColumn).size >= Frame.Width + offB) {
  725. leftColumn = Math.Max (TextModel.CalculateLeftColumn (line, leftColumn,
  726. currentColumn, Frame.Width - 1 + offB, currentColumn), 0);
  727. need = true;
  728. }
  729. if (currentRow < topRow) {
  730. topRow = currentRow;
  731. need = true;
  732. } else if (currentRow - topRow > Frame.Height) {
  733. topRow = currentRow - Frame.Height + 1;
  734. need = true;
  735. }
  736. if (need) {
  737. SetNeedsDisplay ();
  738. } else {
  739. PositionCursor ();
  740. }
  741. }
  742. int OffSetBackground ()
  743. {
  744. int offB = 0;
  745. if (SuperView?.Frame.Right - Frame.Right < 0) {
  746. offB = SuperView.Frame.Right - Frame.Right - 1;
  747. }
  748. return offB;
  749. }
  750. /// <summary>
  751. /// Will scroll the <see cref="TextView"/> to display the specified row at the top
  752. /// </summary>
  753. /// <param name="row">Row that should be displayed at the top, if the value is negative it will be reset to zero</param>
  754. public void ScrollTo (int row)
  755. {
  756. if (row < 0)
  757. row = 0;
  758. topRow = row > model.Count ? model.Count - 1 : row;
  759. SetNeedsDisplay ();
  760. }
  761. bool lastWasKill;
  762. ///<inheritdoc/>
  763. public override bool ProcessKey (KeyEvent kb)
  764. {
  765. int restCount;
  766. List<Rune> rest;
  767. // Handle some state here - whether the last command was a kill
  768. // operation and the column tracking (up/down)
  769. switch (kb.Key) {
  770. case Key.N | Key.CtrlMask:
  771. case Key.CursorDown:
  772. case Key.P | Key.CtrlMask:
  773. case Key.CursorUp:
  774. lastWasKill = false;
  775. break;
  776. case Key.K | Key.CtrlMask:
  777. break;
  778. default:
  779. lastWasKill = false;
  780. columnTrack = -1;
  781. break;
  782. }
  783. // Dispatch the command.
  784. switch (kb.Key) {
  785. case Key.PageDown:
  786. case Key.V | Key.CtrlMask:
  787. int nPageDnShift = Frame.Height - 1;
  788. if (currentRow < model.Count) {
  789. if (columnTrack == -1)
  790. columnTrack = currentColumn;
  791. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  792. if (topRow < currentRow - nPageDnShift) {
  793. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  794. SetNeedsDisplay ();
  795. }
  796. TrackColumn ();
  797. PositionCursor ();
  798. }
  799. break;
  800. case Key.PageUp:
  801. case ((int)'v' + Key.AltMask):
  802. int nPageUpShift = Frame.Height - 1;
  803. if (currentRow > 0) {
  804. if (columnTrack == -1)
  805. columnTrack = currentColumn;
  806. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  807. if (currentRow < topRow) {
  808. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  809. SetNeedsDisplay ();
  810. }
  811. TrackColumn ();
  812. PositionCursor ();
  813. }
  814. break;
  815. case Key.N | Key.CtrlMask:
  816. case Key.CursorDown:
  817. MoveDown ();
  818. break;
  819. case Key.P | Key.CtrlMask:
  820. case Key.CursorUp:
  821. MoveUp ();
  822. break;
  823. case Key.F | Key.CtrlMask:
  824. case Key.CursorRight:
  825. var currentLine = GetCurrentLine ();
  826. if (currentColumn < currentLine.Count) {
  827. currentColumn++;
  828. } else {
  829. if (currentRow + 1 < model.Count) {
  830. currentRow++;
  831. currentColumn = 0;
  832. if (currentRow >= topRow + Frame.Height) {
  833. topRow++;
  834. }
  835. }
  836. }
  837. Adjust ();
  838. break;
  839. case Key.B | Key.CtrlMask:
  840. case Key.CursorLeft:
  841. if (currentColumn > 0) {
  842. currentColumn--;
  843. } else {
  844. if (currentRow > 0) {
  845. currentRow--;
  846. if (currentRow < topRow) {
  847. topRow--;
  848. }
  849. currentLine = GetCurrentLine ();
  850. currentColumn = currentLine.Count;
  851. }
  852. }
  853. Adjust ();
  854. break;
  855. case Key.Delete:
  856. case Key.Backspace:
  857. if (isReadOnly)
  858. break;
  859. if (currentColumn > 0) {
  860. // Delete backwards
  861. currentLine = GetCurrentLine ();
  862. currentLine.RemoveAt (currentColumn - 1);
  863. currentColumn--;
  864. if (currentColumn < leftColumn) {
  865. leftColumn--;
  866. SetNeedsDisplay ();
  867. } else
  868. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  869. } else {
  870. // Merges the current line with the previous one.
  871. if (currentRow == 0)
  872. return true;
  873. var prowIdx = currentRow - 1;
  874. var prevRow = model.GetLine (prowIdx);
  875. var prevCount = prevRow.Count;
  876. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  877. model.RemoveLine (currentRow);
  878. currentRow--;
  879. currentColumn = prevCount;
  880. Adjust ();
  881. }
  882. break;
  883. // Home, C-A
  884. case Key.Home:
  885. case Key.A | Key.CtrlMask:
  886. currentColumn = 0;
  887. Adjust ();
  888. break;
  889. case Key.DeleteChar:
  890. case Key.D | Key.CtrlMask: // Delete
  891. if (isReadOnly)
  892. break;
  893. currentLine = GetCurrentLine ();
  894. if (currentColumn == currentLine.Count) {
  895. if (currentRow + 1 == model.Count)
  896. break;
  897. var nextLine = model.GetLine (currentRow + 1);
  898. currentLine.AddRange (nextLine);
  899. model.RemoveLine (currentRow + 1);
  900. var sr = currentRow - topRow;
  901. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  902. } else {
  903. currentLine.RemoveAt (currentColumn);
  904. var r = currentRow - topRow;
  905. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  906. }
  907. break;
  908. case Key.End:
  909. case Key.E | Key.CtrlMask: // End
  910. currentLine = GetCurrentLine ();
  911. currentColumn = currentLine.Count;
  912. int pcol = leftColumn;
  913. Adjust ();
  914. break;
  915. case Key.K | Key.CtrlMask: // kill-to-end
  916. if (isReadOnly)
  917. break;
  918. currentLine = GetCurrentLine ();
  919. if (currentLine.Count == 0) {
  920. model.RemoveLine (currentRow);
  921. var val = ustring.Make ((Rune)'\n');
  922. if (lastWasKill)
  923. AppendClipboard (val);
  924. else
  925. SetClipboard (val);
  926. } else {
  927. restCount = currentLine.Count - currentColumn;
  928. rest = currentLine.GetRange (currentColumn, restCount);
  929. var val = StringFromRunes (rest);
  930. if (lastWasKill)
  931. AppendClipboard (val);
  932. else
  933. SetClipboard (val);
  934. currentLine.RemoveRange (currentColumn, restCount);
  935. }
  936. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  937. lastWasKill = true;
  938. break;
  939. case Key.Y | Key.CtrlMask: // Control-y, yank
  940. if (isReadOnly)
  941. break;
  942. InsertText (Clipboard.Contents);
  943. selecting = false;
  944. break;
  945. case Key.Space | Key.CtrlMask:
  946. selecting = true;
  947. selectionStartColumn = currentColumn;
  948. selectionStartRow = currentRow;
  949. break;
  950. case ((int)'W' + Key.AltMask):
  951. case Key.W | Key.CtrlMask:
  952. SetClipboard (GetRegion ());
  953. if (!isReadOnly)
  954. ClearRegion ();
  955. selecting = false;
  956. break;
  957. case (Key)((int)'b' + Key.AltMask):
  958. var newPos = WordBackward (currentColumn, currentRow);
  959. if (newPos.HasValue) {
  960. currentColumn = newPos.Value.col;
  961. currentRow = newPos.Value.row;
  962. }
  963. Adjust ();
  964. break;
  965. case (Key)((int)'f' + Key.AltMask):
  966. newPos = WordForward (currentColumn, currentRow);
  967. if (newPos.HasValue) {
  968. currentColumn = newPos.Value.col;
  969. currentRow = newPos.Value.row;
  970. }
  971. Adjust ();
  972. break;
  973. case Key.Enter:
  974. if (isReadOnly)
  975. break;
  976. currentLine = GetCurrentLine ();
  977. restCount = currentLine.Count - currentColumn;
  978. rest = currentLine.GetRange (currentColumn, restCount);
  979. currentLine.RemoveRange (currentColumn, restCount);
  980. model.AddLine (currentRow + 1, rest);
  981. currentRow++;
  982. bool fullNeedsDisplay = false;
  983. if (currentRow >= topRow + Frame.Height) {
  984. topRow++;
  985. fullNeedsDisplay = true;
  986. }
  987. currentColumn = 0;
  988. if (currentColumn < leftColumn) {
  989. fullNeedsDisplay = true;
  990. leftColumn = 0;
  991. }
  992. if (fullNeedsDisplay)
  993. SetNeedsDisplay ();
  994. else
  995. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  996. break;
  997. case Key.CtrlMask | Key.End:
  998. MoveEnd ();
  999. break;
  1000. case Key.CtrlMask | Key.Home:
  1001. MoveHome ();
  1002. break;
  1003. default:
  1004. // Ignore control characters and other special keys
  1005. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  1006. return false;
  1007. //So that special keys like tab can be processed
  1008. if (isReadOnly)
  1009. return true;
  1010. Insert ((uint)kb.Key);
  1011. currentColumn++;
  1012. if (currentColumn >= leftColumn + Frame.Width) {
  1013. leftColumn++;
  1014. SetNeedsDisplay ();
  1015. }
  1016. PositionCursor ();
  1017. return true;
  1018. }
  1019. return true;
  1020. }
  1021. private void MoveUp ()
  1022. {
  1023. if (currentRow > 0) {
  1024. if (columnTrack == -1)
  1025. columnTrack = currentColumn;
  1026. currentRow--;
  1027. if (currentRow < topRow) {
  1028. topRow--;
  1029. SetNeedsDisplay ();
  1030. }
  1031. TrackColumn ();
  1032. PositionCursor ();
  1033. }
  1034. }
  1035. private void MoveDown ()
  1036. {
  1037. if (currentRow + 1 < model.Count) {
  1038. if (columnTrack == -1)
  1039. columnTrack = currentColumn;
  1040. currentRow++;
  1041. if (currentRow >= topRow + Frame.Height) {
  1042. topRow++;
  1043. SetNeedsDisplay ();
  1044. }
  1045. TrackColumn ();
  1046. PositionCursor ();
  1047. }
  1048. }
  1049. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  1050. {
  1051. if (col < 0 || row < 0)
  1052. yield break;
  1053. if (row >= model.Count)
  1054. yield break;
  1055. var line = GetCurrentLine ();
  1056. if (col >= line.Count)
  1057. yield break;
  1058. while (row < model.Count) {
  1059. for (int c = col; c < line.Count; c++) {
  1060. yield return (c, row, line [c]);
  1061. }
  1062. col = 0;
  1063. row++;
  1064. line = GetCurrentLine ();
  1065. }
  1066. }
  1067. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  1068. /// <summary>
  1069. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  1070. /// </summary>
  1071. public void MoveEnd ()
  1072. {
  1073. currentRow = model.Count - 1;
  1074. TrackColumn ();
  1075. PositionCursor ();
  1076. }
  1077. /// <summary>
  1078. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1079. /// </summary>
  1080. public void MoveHome ()
  1081. {
  1082. currentRow = 0;
  1083. TrackColumn ();
  1084. PositionCursor ();
  1085. }
  1086. bool MoveNext (ref int col, ref int row, out Rune rune)
  1087. {
  1088. var line = model.GetLine (row);
  1089. if (col + 1 < line.Count) {
  1090. col++;
  1091. rune = line [col];
  1092. return true;
  1093. }
  1094. while (row + 1 < model.Count) {
  1095. col = 0;
  1096. row++;
  1097. line = model.GetLine (row);
  1098. if (line.Count > 0) {
  1099. rune = line [0];
  1100. return true;
  1101. }
  1102. }
  1103. rune = 0;
  1104. return false;
  1105. }
  1106. bool MovePrev (ref int col, ref int row, out Rune rune)
  1107. {
  1108. var line = model.GetLine (row);
  1109. if (col > 0) {
  1110. col--;
  1111. rune = line [col];
  1112. return true;
  1113. }
  1114. if (row == 0) {
  1115. rune = 0;
  1116. return false;
  1117. }
  1118. while (row > 0) {
  1119. row--;
  1120. line = model.GetLine (row);
  1121. col = line.Count - 1;
  1122. if (col >= 0) {
  1123. rune = line [col];
  1124. return true;
  1125. }
  1126. }
  1127. rune = 0;
  1128. return false;
  1129. }
  1130. (int col, int row)? WordForward (int fromCol, int fromRow)
  1131. {
  1132. var col = fromCol;
  1133. var row = fromRow;
  1134. var line = GetCurrentLine ();
  1135. var rune = RuneAt (col, row);
  1136. var srow = row;
  1137. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1138. while (MoveNext (ref col, ref row, out rune)) {
  1139. if (Rune.IsLetterOrDigit (rune))
  1140. break;
  1141. }
  1142. while (MoveNext (ref col, ref row, out rune)) {
  1143. if (!Rune.IsLetterOrDigit (rune))
  1144. break;
  1145. }
  1146. } else {
  1147. while (MoveNext (ref col, ref row, out rune)) {
  1148. if (!Rune.IsLetterOrDigit (rune))
  1149. break;
  1150. }
  1151. }
  1152. if (fromCol != col || fromRow != row)
  1153. return (col, row);
  1154. return null;
  1155. }
  1156. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1157. {
  1158. if (fromRow == 0 && fromCol == 0)
  1159. return null;
  1160. var col = fromCol;
  1161. var row = fromRow;
  1162. var line = GetCurrentLine ();
  1163. var rune = RuneAt (col, row);
  1164. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1165. while (MovePrev (ref col, ref row, out rune)) {
  1166. if (Rune.IsLetterOrDigit (rune))
  1167. break;
  1168. }
  1169. while (MovePrev (ref col, ref row, out rune)) {
  1170. if (!Rune.IsLetterOrDigit (rune))
  1171. break;
  1172. }
  1173. } else {
  1174. while (MovePrev (ref col, ref row, out rune)) {
  1175. if (!Rune.IsLetterOrDigit (rune))
  1176. break;
  1177. }
  1178. }
  1179. if (fromCol != col || fromRow != row)
  1180. return (col, row);
  1181. return null;
  1182. }
  1183. ///<inheritdoc/>
  1184. public override bool MouseEvent (MouseEvent ev)
  1185. {
  1186. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  1187. !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1188. return false;
  1189. }
  1190. if (!CanFocus) {
  1191. return true;
  1192. }
  1193. if (!HasFocus) {
  1194. SetFocus ();
  1195. }
  1196. if (ev.Flags == MouseFlags.Button1Clicked) {
  1197. if (model.Count > 0) {
  1198. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1199. if (ev.Y > maxCursorPositionableLine) {
  1200. currentRow = maxCursorPositionableLine;
  1201. } else {
  1202. currentRow = ev.Y + topRow;
  1203. }
  1204. var r = GetCurrentLine ();
  1205. var idx = TextModel.GetColFromX (r, leftColumn, ev.X);
  1206. if (idx - leftColumn >= r.Count) {
  1207. currentColumn = r.Count - leftColumn;
  1208. } else {
  1209. currentColumn = idx + leftColumn;
  1210. }
  1211. }
  1212. PositionCursor ();
  1213. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1214. lastWasKill = false;
  1215. MoveDown ();
  1216. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1217. lastWasKill = false;
  1218. MoveUp ();
  1219. }
  1220. return true;
  1221. }
  1222. }
  1223. }