TextView.cs 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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. }
  157. /// <summary>
  158. /// Multi-line text editing <see cref="View"/>
  159. /// </summary>
  160. /// <remarks>
  161. /// <para>
  162. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  163. /// with it with the standard Emacs commands for movement or the arrow
  164. /// keys.
  165. /// </para>
  166. /// <list type="table">
  167. /// <listheader>
  168. /// <term>Shortcut</term>
  169. /// <description>Action performed</description>
  170. /// </listheader>
  171. /// <item>
  172. /// <term>Left cursor, Control-b</term>
  173. /// <description>
  174. /// Moves the editing point left.
  175. /// </description>
  176. /// </item>
  177. /// <item>
  178. /// <term>Right cursor, Control-f</term>
  179. /// <description>
  180. /// Moves the editing point right.
  181. /// </description>
  182. /// </item>
  183. /// <item>
  184. /// <term>Alt-b</term>
  185. /// <description>
  186. /// Moves one word back.
  187. /// </description>
  188. /// </item>
  189. /// <item>
  190. /// <term>Alt-f</term>
  191. /// <description>
  192. /// Moves one word forward.
  193. /// </description>
  194. /// </item>
  195. /// <item>
  196. /// <term>Up cursor, Control-p</term>
  197. /// <description>
  198. /// Moves the editing point one line up.
  199. /// </description>
  200. /// </item>
  201. /// <item>
  202. /// <term>Down cursor, Control-n</term>
  203. /// <description>
  204. /// Moves the editing point one line down
  205. /// </description>
  206. /// </item>
  207. /// <item>
  208. /// <term>Home key, Control-a</term>
  209. /// <description>
  210. /// Moves the cursor to the beginning of the line.
  211. /// </description>
  212. /// </item>
  213. /// <item>
  214. /// <term>End key, Control-e</term>
  215. /// <description>
  216. /// Moves the cursor to the end of the line.
  217. /// </description>
  218. /// </item>
  219. /// <item>
  220. /// <term>Control-Home</term>
  221. /// <description>
  222. /// Scrolls to the first line and moves the cursor there.
  223. /// </description>
  224. /// </item>
  225. /// <item>
  226. /// <term>Control-End</term>
  227. /// <description>
  228. /// Scrolls to the last line and moves the cursor there.
  229. /// </description>
  230. /// </item>
  231. /// <item>
  232. /// <term>Delete, Control-d</term>
  233. /// <description>
  234. /// Deletes the character in front of the cursor.
  235. /// </description>
  236. /// </item>
  237. /// <item>
  238. /// <term>Backspace</term>
  239. /// <description>
  240. /// Deletes the character behind the cursor.
  241. /// </description>
  242. /// </item>
  243. /// <item>
  244. /// <term>Control-k</term>
  245. /// <description>
  246. /// Deletes the text until the end of the line and replaces the kill buffer
  247. /// with the deleted text. You can paste this text in a different place by
  248. /// using Control-y.
  249. /// </description>
  250. /// </item>
  251. /// <item>
  252. /// <term>Control-y</term>
  253. /// <description>
  254. /// Pastes the content of the kill ring into the current position.
  255. /// </description>
  256. /// </item>
  257. /// <item>
  258. /// <term>Alt-d</term>
  259. /// <description>
  260. /// Deletes the word above the cursor and adds it to the kill ring. You
  261. /// can paste the contents of the kill ring with Control-y.
  262. /// </description>
  263. /// </item>
  264. /// <item>
  265. /// <term>Control-q</term>
  266. /// <description>
  267. /// Quotes the next input character, to prevent the normal processing of
  268. /// key handling to take place.
  269. /// </description>
  270. /// </item>
  271. /// </list>
  272. /// </remarks>
  273. public class TextView : View {
  274. TextModel model = new TextModel ();
  275. int topRow;
  276. int leftColumn;
  277. int currentRow;
  278. int currentColumn;
  279. int selectionStartColumn, selectionStartRow;
  280. bool selecting;
  281. //bool used;
  282. /// <summary>
  283. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  284. /// </summary>
  285. public Action TextChanged;
  286. #if false
  287. /// <summary>
  288. /// Changed event, raised when the text has clicked.
  289. /// </summary>
  290. /// <remarks>
  291. /// Client code can hook up to this event, it is
  292. /// raised when the text in the entry changes.
  293. /// </remarks>
  294. public Action Changed;
  295. #endif
  296. /// <summary>
  297. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  298. /// </summary>
  299. /// <remarks>
  300. /// </remarks>
  301. public TextView (Rect frame) : base (frame)
  302. {
  303. CanFocus = true;
  304. }
  305. /// <summary>
  306. /// Initializes a <see cref="TextView"/> on the specified area,
  307. /// with dimensions controlled with the X, Y, Width and Height properties.
  308. /// </summary>
  309. public TextView () : base ()
  310. {
  311. CanFocus = true;
  312. }
  313. void ResetPosition ()
  314. {
  315. topRow = leftColumn = currentRow = currentColumn = 0;
  316. }
  317. /// <summary>
  318. /// Sets or gets the text in the <see cref="TextView"/>.
  319. /// </summary>
  320. /// <remarks>
  321. /// </remarks>
  322. public override ustring Text {
  323. get {
  324. return model.ToString ();
  325. }
  326. set {
  327. ResetPosition ();
  328. model.LoadString (value);
  329. TextChanged?.Invoke ();
  330. SetNeedsDisplay ();
  331. }
  332. }
  333. /// <summary>
  334. /// Loads the contents of the file into the <see cref="TextView"/>.
  335. /// </summary>
  336. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  337. /// <param name="path">Path to the file to load.</param>
  338. public bool LoadFile (string path)
  339. {
  340. if (path == null)
  341. throw new ArgumentNullException (nameof (path));
  342. ResetPosition ();
  343. var res = model.LoadFile (path);
  344. SetNeedsDisplay ();
  345. return res;
  346. }
  347. /// <summary>
  348. /// Loads the contents of the stream into the <see cref="TextView"/>.
  349. /// </summary>
  350. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  351. /// <param name="stream">Stream to load the contents from.</param>
  352. public void LoadStream (Stream stream)
  353. {
  354. if (stream == null)
  355. throw new ArgumentNullException (nameof (stream));
  356. ResetPosition ();
  357. model.LoadStream (stream);
  358. SetNeedsDisplay ();
  359. }
  360. /// <summary>
  361. /// Closes the contents of the stream into the <see cref="TextView"/>.
  362. /// </summary>
  363. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  364. public bool CloseFile ()
  365. {
  366. ResetPosition ();
  367. var res = model.CloseFile ();
  368. SetNeedsDisplay ();
  369. return res;
  370. }
  371. /// <summary>
  372. /// Gets the current cursor row.
  373. /// </summary>
  374. public int CurrentRow => currentRow;
  375. /// <summary>
  376. /// Gets the cursor column.
  377. /// </summary>
  378. /// <value>The cursor column.</value>
  379. public int CurrentColumn => currentColumn;
  380. /// <summary>
  381. /// Positions the cursor on the current row and column
  382. /// </summary>
  383. public override void PositionCursor ()
  384. {
  385. if (selecting) {
  386. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  387. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  388. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  389. }
  390. Move (CurrentColumn - leftColumn, CurrentRow - topRow);
  391. }
  392. void ClearRegion (int left, int top, int right, int bottom)
  393. {
  394. for (int row = top; row < bottom; row++) {
  395. Move (left, row);
  396. for (int col = left; col < right; col++)
  397. AddRune (col, row, ' ');
  398. }
  399. }
  400. void ColorNormal ()
  401. {
  402. Driver.SetAttribute (ColorScheme.Normal);
  403. }
  404. void ColorSelection ()
  405. {
  406. if (HasFocus)
  407. Driver.SetAttribute (ColorScheme.Focus);
  408. else
  409. Driver.SetAttribute (ColorScheme.Normal);
  410. }
  411. bool isReadOnly = false;
  412. /// <summary>
  413. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  414. /// </summary>
  415. /// <value>Boolean value(Default false)</value>
  416. public bool ReadOnly {
  417. get => isReadOnly;
  418. set {
  419. isReadOnly = value;
  420. }
  421. }
  422. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  423. void GetEncodedRegionBounds (out long start, out long end)
  424. {
  425. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  426. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  427. if (selection > point) {
  428. start = point;
  429. end = selection;
  430. } else {
  431. start = selection;
  432. end = point;
  433. }
  434. }
  435. bool PointInSelection (int col, int row)
  436. {
  437. long start, end;
  438. GetEncodedRegionBounds (out start, out end);
  439. var q = ((long)(uint)row << 32) | (uint)col;
  440. return q >= start && q <= end;
  441. }
  442. //
  443. // Returns a ustring with the text in the selected
  444. // region.
  445. //
  446. ustring GetRegion ()
  447. {
  448. long start, end;
  449. GetEncodedRegionBounds (out start, out end);
  450. int startRow = (int)(start >> 32);
  451. var maxrow = ((int)(end >> 32));
  452. int startCol = (int)(start & 0xffffffff);
  453. var endCol = (int)(end & 0xffffffff);
  454. var line = model.GetLine (startRow);
  455. if (startRow == maxrow)
  456. return StringFromRunes (line.GetRange (startCol, endCol));
  457. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  458. for (int row = startRow + 1; row < maxrow; row++) {
  459. res = res + ustring.Make ((Rune)10) + StringFromRunes (model.GetLine (row));
  460. }
  461. line = model.GetLine (maxrow);
  462. res = res + ustring.Make ((Rune)10) + StringFromRunes (line.GetRange (0, endCol));
  463. return res;
  464. }
  465. //
  466. // Clears the contents of the selected region
  467. //
  468. void ClearRegion ()
  469. {
  470. long start, end;
  471. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  472. GetEncodedRegionBounds (out start, out end);
  473. int startRow = (int)(start >> 32);
  474. var maxrow = ((int)(end >> 32));
  475. int startCol = (int)(start & 0xffffffff);
  476. var endCol = (int)(end & 0xffffffff);
  477. var line = model.GetLine (startRow);
  478. if (startRow == maxrow) {
  479. line.RemoveRange (startCol, endCol - startCol);
  480. currentColumn = startCol;
  481. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  482. return;
  483. }
  484. line.RemoveRange (startCol, line.Count - startCol);
  485. var line2 = model.GetLine (maxrow);
  486. line.AddRange (line2.Skip (endCol));
  487. for (int row = startRow + 1; row <= maxrow; row++) {
  488. model.RemoveLine (startRow + 1);
  489. }
  490. if (currentEncoded == end) {
  491. currentRow -= maxrow - (startRow);
  492. }
  493. currentColumn = startCol;
  494. SetNeedsDisplay ();
  495. }
  496. ///<inheritdoc/>
  497. public override void Redraw (Rect bounds)
  498. {
  499. ColorNormal ();
  500. int bottom = bounds.Bottom;
  501. int right = bounds.Right;
  502. for (int row = bounds.Top; row < bottom; row++) {
  503. int textLine = topRow + row;
  504. if (textLine >= model.Count) {
  505. ColorNormal ();
  506. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  507. continue;
  508. }
  509. var line = model.GetLine (textLine);
  510. int lineRuneCount = line.Count;
  511. if (line.Count < bounds.Left) {
  512. ClearRegion (bounds.Left, row, bounds.Right, row + 1);
  513. continue;
  514. }
  515. Move (bounds.Left, row);
  516. for (int col = bounds.Left; col < right; col++) {
  517. var lineCol = leftColumn + col;
  518. var rune = lineCol >= lineRuneCount ? ' ' : line [lineCol];
  519. if (selecting && PointInSelection (col, row))
  520. ColorSelection ();
  521. else
  522. ColorNormal ();
  523. AddRune (col, row, rune);
  524. }
  525. }
  526. PositionCursor ();
  527. }
  528. ///<inheritdoc/>
  529. public override bool CanFocus {
  530. get => base.CanFocus;
  531. set { base.CanFocus = value; }
  532. }
  533. void SetClipboard (ustring text)
  534. {
  535. Clipboard.Contents = text;
  536. }
  537. void AppendClipboard (ustring text)
  538. {
  539. Clipboard.Contents = Clipboard.Contents + text;
  540. }
  541. void Insert (Rune rune)
  542. {
  543. var line = GetCurrentLine ();
  544. line.Insert (currentColumn, rune);
  545. var prow = currentRow - topRow;
  546. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  547. }
  548. ustring StringFromRunes (List<Rune> runes)
  549. {
  550. if (runes == null)
  551. throw new ArgumentNullException (nameof (runes));
  552. int size = 0;
  553. foreach (var rune in runes) {
  554. size += Utf8.RuneLen (rune);
  555. }
  556. var encoded = new byte [size];
  557. int offset = 0;
  558. foreach (var rune in runes) {
  559. offset += Utf8.EncodeRune (rune, encoded, offset);
  560. }
  561. return ustring.Make (encoded);
  562. }
  563. List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  564. void InsertText (ustring text)
  565. {
  566. var lines = TextModel.StringToRunes (text);
  567. if (lines.Count == 0)
  568. return;
  569. var line = GetCurrentLine ();
  570. // Optmize single line
  571. if (lines.Count == 1) {
  572. line.InsertRange (currentColumn, lines [0]);
  573. currentColumn += lines [0].Count;
  574. if (currentColumn - leftColumn > Frame.Width)
  575. leftColumn = currentColumn - Frame.Width + 1;
  576. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, currentRow - topRow + 1));
  577. return;
  578. }
  579. // Keep a copy of the rest of the line
  580. var restCount = line.Count - currentColumn;
  581. var rest = line.GetRange (currentColumn, restCount);
  582. line.RemoveRange (currentColumn, restCount);
  583. // First line is inserted at the current location, the rest is appended
  584. line.InsertRange (currentColumn, lines [0]);
  585. for (int i = 1; i < lines.Count; i++)
  586. model.AddLine (currentRow + i, lines [i]);
  587. var last = model.GetLine (currentRow + lines.Count - 1);
  588. var lastp = last.Count;
  589. last.InsertRange (last.Count, rest);
  590. // Now adjjust column and row positions
  591. currentRow += lines.Count - 1;
  592. currentColumn = lastp;
  593. if (currentRow - topRow > Frame.Height) {
  594. topRow = currentRow - Frame.Height + 1;
  595. if (topRow < 0)
  596. topRow = 0;
  597. }
  598. if (currentColumn < leftColumn)
  599. leftColumn = currentColumn;
  600. if (currentColumn - leftColumn >= Frame.Width)
  601. leftColumn = currentColumn - Frame.Width + 1;
  602. SetNeedsDisplay ();
  603. }
  604. // The column we are tracking, or -1 if we are not tracking any column
  605. int columnTrack = -1;
  606. // Tries to snap the cursor to the tracking column
  607. void TrackColumn ()
  608. {
  609. // Now track the column
  610. var line = GetCurrentLine ();
  611. if (line.Count < columnTrack)
  612. currentColumn = line.Count;
  613. else if (columnTrack != -1)
  614. currentColumn = columnTrack;
  615. else if (currentColumn > line.Count)
  616. currentColumn = line.Count;
  617. Adjust ();
  618. }
  619. void Adjust ()
  620. {
  621. bool need = false;
  622. if (currentColumn < leftColumn) {
  623. currentColumn = leftColumn;
  624. need = true;
  625. }
  626. if (currentColumn - leftColumn > Frame.Width) {
  627. leftColumn = currentColumn - Frame.Width + 1;
  628. need = true;
  629. }
  630. if (currentRow < topRow) {
  631. topRow = currentRow;
  632. need = true;
  633. }
  634. if (currentRow - topRow > Frame.Height) {
  635. topRow = currentRow - Frame.Height + 1;
  636. need = true;
  637. }
  638. if (need)
  639. SetNeedsDisplay ();
  640. else
  641. PositionCursor ();
  642. }
  643. /// <summary>
  644. /// Will scroll the <see cref="TextView"/> to display the specified row at the top
  645. /// </summary>
  646. /// <param name="row">Row that should be displayed at the top, if the value is negative it will be reset to zero</param>
  647. public void ScrollTo (int row)
  648. {
  649. if (row < 0)
  650. row = 0;
  651. topRow = row > model.Count ? model.Count - 1 : row;
  652. SetNeedsDisplay ();
  653. }
  654. bool lastWasKill;
  655. ///<inheritdoc/>
  656. public override bool ProcessKey (KeyEvent kb)
  657. {
  658. int restCount;
  659. List<Rune> rest;
  660. // Handle some state here - whether the last command was a kill
  661. // operation and the column tracking (up/down)
  662. switch (kb.Key) {
  663. case Key.ControlN:
  664. case Key.CursorDown:
  665. case Key.ControlP:
  666. case Key.CursorUp:
  667. lastWasKill = false;
  668. break;
  669. case Key.ControlK:
  670. break;
  671. default:
  672. lastWasKill = false;
  673. columnTrack = -1;
  674. break;
  675. }
  676. // Dispatch the command.
  677. switch (kb.Key) {
  678. case Key.PageDown:
  679. case Key.ControlV:
  680. int nPageDnShift = Frame.Height - 1;
  681. if (currentRow < model.Count) {
  682. if (columnTrack == -1)
  683. columnTrack = currentColumn;
  684. currentRow = (currentRow + nPageDnShift) > model.Count ? model.Count : currentRow + nPageDnShift;
  685. if (topRow < currentRow - nPageDnShift) {
  686. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  687. SetNeedsDisplay ();
  688. }
  689. TrackColumn ();
  690. PositionCursor ();
  691. }
  692. break;
  693. case Key.PageUp:
  694. case ((int)'v' + Key.AltMask):
  695. int nPageUpShift = Frame.Height - 1;
  696. if (currentRow > 0) {
  697. if (columnTrack == -1)
  698. columnTrack = currentColumn;
  699. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  700. if (currentRow < topRow) {
  701. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  702. SetNeedsDisplay ();
  703. }
  704. TrackColumn ();
  705. PositionCursor ();
  706. }
  707. break;
  708. case Key.ControlN:
  709. case Key.CursorDown:
  710. MoveDown ();
  711. break;
  712. case Key.ControlP:
  713. case Key.CursorUp:
  714. MoveUp ();
  715. break;
  716. case Key.ControlF:
  717. case Key.CursorRight:
  718. var currentLine = GetCurrentLine ();
  719. if (currentColumn < currentLine.Count) {
  720. currentColumn++;
  721. if (currentColumn >= leftColumn + Frame.Width) {
  722. leftColumn++;
  723. SetNeedsDisplay ();
  724. }
  725. PositionCursor ();
  726. } else {
  727. if (currentRow + 1 < model.Count) {
  728. currentRow++;
  729. currentColumn = 0;
  730. leftColumn = 0;
  731. if (currentRow >= topRow + Frame.Height) {
  732. topRow++;
  733. }
  734. SetNeedsDisplay ();
  735. PositionCursor ();
  736. }
  737. break;
  738. }
  739. break;
  740. case Key.ControlB:
  741. case Key.CursorLeft:
  742. if (currentColumn > 0) {
  743. currentColumn--;
  744. if (currentColumn < leftColumn) {
  745. leftColumn--;
  746. SetNeedsDisplay ();
  747. }
  748. PositionCursor ();
  749. } else {
  750. if (currentRow > 0) {
  751. currentRow--;
  752. if (currentRow < topRow) {
  753. topRow--;
  754. SetNeedsDisplay ();
  755. }
  756. currentLine = GetCurrentLine ();
  757. currentColumn = currentLine.Count;
  758. int prev = leftColumn;
  759. leftColumn = currentColumn - Frame.Width + 1;
  760. if (leftColumn < 0)
  761. leftColumn = 0;
  762. if (prev != leftColumn)
  763. SetNeedsDisplay ();
  764. PositionCursor ();
  765. }
  766. }
  767. break;
  768. case Key.Delete:
  769. case Key.Backspace:
  770. if (isReadOnly)
  771. break;
  772. if (currentColumn > 0) {
  773. // Delete backwards
  774. currentLine = GetCurrentLine ();
  775. currentLine.RemoveAt (currentColumn - 1);
  776. currentColumn--;
  777. if (currentColumn < leftColumn) {
  778. leftColumn--;
  779. SetNeedsDisplay ();
  780. } else
  781. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  782. } else {
  783. // Merges the current line with the previous one.
  784. if (currentRow == 0)
  785. return true;
  786. var prowIdx = currentRow - 1;
  787. var prevRow = model.GetLine (prowIdx);
  788. var prevCount = prevRow.Count;
  789. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  790. model.RemoveLine (currentRow);
  791. currentRow--;
  792. currentColumn = prevCount;
  793. leftColumn = currentColumn - Frame.Width + 1;
  794. if (leftColumn < 0)
  795. leftColumn = 0;
  796. SetNeedsDisplay ();
  797. }
  798. break;
  799. // Home, C-A
  800. case Key.Home:
  801. case Key.ControlA:
  802. currentColumn = 0;
  803. if (currentColumn < leftColumn) {
  804. leftColumn = 0;
  805. SetNeedsDisplay ();
  806. } else
  807. PositionCursor ();
  808. break;
  809. case Key.DeleteChar:
  810. case Key.ControlD: // Delete
  811. if (isReadOnly)
  812. break;
  813. currentLine = GetCurrentLine ();
  814. if (currentColumn == currentLine.Count) {
  815. if (currentRow + 1 == model.Count)
  816. break;
  817. var nextLine = model.GetLine (currentRow + 1);
  818. currentLine.AddRange (nextLine);
  819. model.RemoveLine (currentRow + 1);
  820. var sr = currentRow - topRow;
  821. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  822. } else {
  823. currentLine.RemoveAt (currentColumn);
  824. var r = currentRow - topRow;
  825. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  826. }
  827. break;
  828. case Key.End:
  829. case Key.ControlE: // End
  830. currentLine = GetCurrentLine ();
  831. currentColumn = currentLine.Count;
  832. int pcol = leftColumn;
  833. leftColumn = currentColumn - Frame.Width + 1;
  834. if (leftColumn < 0)
  835. leftColumn = 0;
  836. if (pcol != leftColumn)
  837. SetNeedsDisplay ();
  838. PositionCursor ();
  839. break;
  840. case Key.ControlK: // kill-to-end
  841. if (isReadOnly)
  842. break;
  843. currentLine = GetCurrentLine ();
  844. if (currentLine.Count == 0) {
  845. model.RemoveLine (currentRow);
  846. var val = ustring.Make ((Rune)'\n');
  847. if (lastWasKill)
  848. AppendClipboard (val);
  849. else
  850. SetClipboard (val);
  851. } else {
  852. restCount = currentLine.Count - currentColumn;
  853. rest = currentLine.GetRange (currentColumn, restCount);
  854. var val = StringFromRunes (rest);
  855. if (lastWasKill)
  856. AppendClipboard (val);
  857. else
  858. SetClipboard (val);
  859. currentLine.RemoveRange (currentColumn, restCount);
  860. }
  861. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  862. lastWasKill = true;
  863. break;
  864. case Key.ControlY: // Control-y, yank
  865. if (isReadOnly)
  866. break;
  867. InsertText (Clipboard.Contents);
  868. selecting = false;
  869. break;
  870. case Key.ControlSpace:
  871. selecting = true;
  872. selectionStartColumn = currentColumn;
  873. selectionStartRow = currentRow;
  874. break;
  875. case ((int)'w' + Key.AltMask):
  876. SetClipboard (GetRegion ());
  877. selecting = false;
  878. break;
  879. case Key.ControlW:
  880. SetClipboard (GetRegion ());
  881. if (!isReadOnly)
  882. ClearRegion ();
  883. selecting = false;
  884. break;
  885. case (Key)((int)'b' + Key.AltMask):
  886. var newPos = WordBackward (currentColumn, currentRow);
  887. if (newPos.HasValue) {
  888. currentColumn = newPos.Value.col;
  889. currentRow = newPos.Value.row;
  890. }
  891. Adjust ();
  892. break;
  893. case (Key)((int)'f' + Key.AltMask):
  894. newPos = WordForward (currentColumn, currentRow);
  895. if (newPos.HasValue) {
  896. currentColumn = newPos.Value.col;
  897. currentRow = newPos.Value.row;
  898. }
  899. Adjust ();
  900. break;
  901. case Key.Enter:
  902. if (isReadOnly)
  903. break;
  904. var orow = currentRow;
  905. currentLine = GetCurrentLine ();
  906. restCount = currentLine.Count - currentColumn;
  907. rest = currentLine.GetRange (currentColumn, restCount);
  908. currentLine.RemoveRange (currentColumn, restCount);
  909. model.AddLine (currentRow + 1, rest);
  910. currentRow++;
  911. bool fullNeedsDisplay = false;
  912. if (currentRow >= topRow + Frame.Height) {
  913. topRow++;
  914. fullNeedsDisplay = true;
  915. }
  916. currentColumn = 0;
  917. if (currentColumn < leftColumn) {
  918. fullNeedsDisplay = true;
  919. leftColumn = 0;
  920. }
  921. if (fullNeedsDisplay)
  922. SetNeedsDisplay ();
  923. else
  924. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  925. break;
  926. case Key.CtrlMask | Key.End:
  927. MoveEnd ();
  928. break;
  929. case Key.CtrlMask | Key.Home:
  930. MoveHome ();
  931. break;
  932. default:
  933. // Ignore control characters and other special keys
  934. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  935. return false;
  936. //So that special keys like tab can be processed
  937. if (isReadOnly)
  938. return true;
  939. Insert ((uint)kb.Key);
  940. currentColumn++;
  941. if (currentColumn >= leftColumn + Frame.Width) {
  942. leftColumn++;
  943. SetNeedsDisplay ();
  944. }
  945. PositionCursor ();
  946. return true;
  947. }
  948. return true;
  949. }
  950. private void MoveUp ()
  951. {
  952. if (currentRow > 0) {
  953. if (columnTrack == -1)
  954. columnTrack = currentColumn;
  955. currentRow--;
  956. if (currentRow < topRow) {
  957. topRow--;
  958. SetNeedsDisplay ();
  959. }
  960. TrackColumn ();
  961. PositionCursor ();
  962. }
  963. }
  964. private void MoveDown ()
  965. {
  966. if (currentRow + 1 < model.Count) {
  967. if (columnTrack == -1)
  968. columnTrack = currentColumn;
  969. currentRow++;
  970. if (currentRow >= topRow + Frame.Height) {
  971. topRow++;
  972. SetNeedsDisplay ();
  973. }
  974. TrackColumn ();
  975. PositionCursor ();
  976. }
  977. }
  978. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  979. {
  980. if (col < 0 || row < 0)
  981. yield break;
  982. if (row >= model.Count)
  983. yield break;
  984. var line = GetCurrentLine ();
  985. if (col >= line.Count)
  986. yield break;
  987. while (row < model.Count) {
  988. for (int c = col; c < line.Count; c++) {
  989. yield return (c, row, line [c]);
  990. }
  991. col = 0;
  992. row++;
  993. line = GetCurrentLine ();
  994. }
  995. }
  996. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  997. /// <summary>
  998. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  999. /// </summary>
  1000. public void MoveEnd ()
  1001. {
  1002. currentRow = model.Count - 1;
  1003. TrackColumn ();
  1004. PositionCursor ();
  1005. }
  1006. /// <summary>
  1007. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  1008. /// </summary>
  1009. public void MoveHome ()
  1010. {
  1011. currentRow = 0;
  1012. TrackColumn ();
  1013. PositionCursor ();
  1014. }
  1015. bool MoveNext (ref int col, ref int row, out Rune rune)
  1016. {
  1017. var line = model.GetLine (row);
  1018. if (col + 1 < line.Count) {
  1019. col++;
  1020. rune = line [col];
  1021. return true;
  1022. }
  1023. while (row + 1 < model.Count) {
  1024. col = 0;
  1025. row++;
  1026. line = model.GetLine (row);
  1027. if (line.Count > 0) {
  1028. rune = line [0];
  1029. return true;
  1030. }
  1031. }
  1032. rune = 0;
  1033. return false;
  1034. }
  1035. bool MovePrev (ref int col, ref int row, out Rune rune)
  1036. {
  1037. var line = model.GetLine (row);
  1038. if (col > 0) {
  1039. col--;
  1040. rune = line [col];
  1041. return true;
  1042. }
  1043. if (row == 0) {
  1044. rune = 0;
  1045. return false;
  1046. }
  1047. while (row > 0) {
  1048. row--;
  1049. line = model.GetLine (row);
  1050. col = line.Count - 1;
  1051. if (col >= 0) {
  1052. rune = line [col];
  1053. return true;
  1054. }
  1055. }
  1056. rune = 0;
  1057. return false;
  1058. }
  1059. (int col, int row)? WordForward (int fromCol, int fromRow)
  1060. {
  1061. var col = fromCol;
  1062. var row = fromRow;
  1063. var line = GetCurrentLine ();
  1064. var rune = RuneAt (col, row);
  1065. var srow = row;
  1066. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  1067. while (MoveNext (ref col, ref row, out rune)) {
  1068. if (Rune.IsLetterOrDigit (rune))
  1069. break;
  1070. }
  1071. while (MoveNext (ref col, ref row, out rune)) {
  1072. if (!Rune.IsLetterOrDigit (rune))
  1073. break;
  1074. }
  1075. } else {
  1076. while (MoveNext (ref col, ref row, out rune)) {
  1077. if (!Rune.IsLetterOrDigit (rune))
  1078. break;
  1079. }
  1080. }
  1081. if (fromCol != col || fromRow != row)
  1082. return (col, row);
  1083. return null;
  1084. }
  1085. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1086. {
  1087. if (fromRow == 0 && fromCol == 0)
  1088. return null;
  1089. var col = fromCol;
  1090. var row = fromRow;
  1091. var line = GetCurrentLine ();
  1092. var rune = RuneAt (col, row);
  1093. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1094. while (MovePrev (ref col, ref row, out rune)) {
  1095. if (Rune.IsLetterOrDigit (rune))
  1096. break;
  1097. }
  1098. while (MovePrev (ref col, ref row, out rune)) {
  1099. if (!Rune.IsLetterOrDigit (rune))
  1100. break;
  1101. }
  1102. } else {
  1103. while (MovePrev (ref col, ref row, out rune)) {
  1104. if (!Rune.IsLetterOrDigit (rune))
  1105. break;
  1106. }
  1107. }
  1108. if (fromCol != col || fromRow != row)
  1109. return (col, row);
  1110. return null;
  1111. }
  1112. ///<inheritdoc/>
  1113. public override bool MouseEvent (MouseEvent ev)
  1114. {
  1115. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) &&
  1116. !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)) {
  1117. return false;
  1118. }
  1119. if (!CanFocus) {
  1120. return true;
  1121. }
  1122. if (!HasFocus) {
  1123. SetFocus ();
  1124. }
  1125. if (ev.Flags == MouseFlags.Button1Clicked) {
  1126. if (model.Count > 0) {
  1127. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1128. if (ev.Y > maxCursorPositionableLine) {
  1129. currentRow = maxCursorPositionableLine;
  1130. } else {
  1131. currentRow = ev.Y + topRow;
  1132. }
  1133. var r = GetCurrentLine ();
  1134. if (ev.X - leftColumn >= r.Count)
  1135. currentColumn = r.Count - leftColumn;
  1136. else
  1137. currentColumn = ev.X - leftColumn;
  1138. }
  1139. PositionCursor ();
  1140. } else if (ev.Flags == MouseFlags.WheeledDown) {
  1141. lastWasKill = false;
  1142. MoveDown ();
  1143. } else if (ev.Flags == MouseFlags.WheeledUp) {
  1144. lastWasKill = false;
  1145. MoveUp ();
  1146. }
  1147. return true;
  1148. }
  1149. }
  1150. }