TextView.cs 31 KB

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