TextView.cs 31 KB

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