TextView.cs 29 KB

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