TextView.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. }
  735. currentLine = GetCurrentLine ();
  736. currentColumn = currentLine.Count;
  737. int prev = leftColumn;
  738. leftColumn = currentColumn - Frame.Width + 1;
  739. if (leftColumn < 0)
  740. leftColumn = 0;
  741. if (prev != leftColumn)
  742. SetNeedsDisplay ();
  743. PositionCursor ();
  744. }
  745. }
  746. break;
  747. case Key.Delete:
  748. case Key.Backspace:
  749. if (isReadOnly)
  750. break;
  751. if (currentColumn > 0) {
  752. // Delete backwards
  753. currentLine = GetCurrentLine ();
  754. currentLine.RemoveAt (currentColumn - 1);
  755. currentColumn--;
  756. if (currentColumn < leftColumn) {
  757. leftColumn--;
  758. SetNeedsDisplay ();
  759. } else
  760. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  761. } else {
  762. // Merges the current line with the previous one.
  763. if (currentRow == 0)
  764. return true;
  765. var prowIdx = currentRow - 1;
  766. var prevRow = model.GetLine (prowIdx);
  767. var prevCount = prevRow.Count;
  768. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  769. model.RemoveLine (currentRow);
  770. currentRow--;
  771. currentColumn = prevCount;
  772. leftColumn = currentColumn - Frame.Width + 1;
  773. if (leftColumn < 0)
  774. leftColumn = 0;
  775. SetNeedsDisplay ();
  776. }
  777. break;
  778. // Home, C-A
  779. case Key.Home:
  780. case Key.ControlA:
  781. currentColumn = 0;
  782. if (currentColumn < leftColumn) {
  783. leftColumn = 0;
  784. SetNeedsDisplay ();
  785. } else
  786. PositionCursor ();
  787. break;
  788. case Key.DeleteChar:
  789. case Key.ControlD: // Delete
  790. if (isReadOnly)
  791. break;
  792. currentLine = GetCurrentLine ();
  793. if (currentColumn == currentLine.Count) {
  794. if (currentRow + 1 == model.Count)
  795. break;
  796. var nextLine = model.GetLine (currentRow + 1);
  797. currentLine.AddRange (nextLine);
  798. model.RemoveLine (currentRow + 1);
  799. var sr = currentRow - topRow;
  800. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  801. } else {
  802. currentLine.RemoveAt (currentColumn);
  803. var r = currentRow - topRow;
  804. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  805. }
  806. break;
  807. case Key.End:
  808. case Key.ControlE: // End
  809. currentLine = GetCurrentLine ();
  810. currentColumn = currentLine.Count;
  811. int pcol = leftColumn;
  812. leftColumn = currentColumn - Frame.Width + 1;
  813. if (leftColumn < 0)
  814. leftColumn = 0;
  815. if (pcol != leftColumn)
  816. SetNeedsDisplay ();
  817. PositionCursor ();
  818. break;
  819. case Key.ControlK: // kill-to-end
  820. if (isReadOnly)
  821. break;
  822. currentLine = GetCurrentLine ();
  823. if (currentLine.Count == 0) {
  824. model.RemoveLine (currentRow);
  825. var val = ustring.Make ((Rune)'\n');
  826. if (lastWasKill)
  827. AppendClipboard (val);
  828. else
  829. SetClipboard (val);
  830. } else {
  831. restCount = currentLine.Count - currentColumn;
  832. rest = currentLine.GetRange (currentColumn, restCount);
  833. var val = StringFromRunes (rest);
  834. if (lastWasKill)
  835. AppendClipboard (val);
  836. else
  837. SetClipboard (val);
  838. currentLine.RemoveRange (currentColumn, restCount);
  839. }
  840. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  841. lastWasKill = true;
  842. break;
  843. case Key.ControlY: // Control-y, yank
  844. if (isReadOnly)
  845. break;
  846. InsertText (Clipboard.Contents);
  847. selecting = false;
  848. break;
  849. case Key.ControlSpace:
  850. selecting = true;
  851. selectionStartColumn = currentColumn;
  852. selectionStartRow = currentRow;
  853. break;
  854. case ((int)'w' + Key.AltMask):
  855. SetClipboard (GetRegion ());
  856. selecting = false;
  857. break;
  858. case Key.ControlW:
  859. SetClipboard (GetRegion ());
  860. if (!isReadOnly)
  861. ClearRegion ();
  862. selecting = false;
  863. break;
  864. case (Key)((int)'b' + Key.AltMask):
  865. var newPos = WordBackward (currentColumn, currentRow);
  866. if (newPos.HasValue) {
  867. currentColumn = newPos.Value.col;
  868. currentRow = newPos.Value.row;
  869. }
  870. Adjust ();
  871. break;
  872. case (Key)((int)'f' + Key.AltMask):
  873. newPos = WordForward (currentColumn, currentRow);
  874. if (newPos.HasValue) {
  875. currentColumn = newPos.Value.col;
  876. currentRow = newPos.Value.row;
  877. }
  878. Adjust ();
  879. break;
  880. case Key.Enter:
  881. if (isReadOnly)
  882. break;
  883. var orow = currentRow;
  884. currentLine = GetCurrentLine ();
  885. restCount = currentLine.Count - currentColumn;
  886. rest = currentLine.GetRange (currentColumn, restCount);
  887. currentLine.RemoveRange (currentColumn, restCount);
  888. model.AddLine (currentRow + 1, rest);
  889. currentRow++;
  890. bool fullNeedsDisplay = false;
  891. if (currentRow >= topRow + Frame.Height) {
  892. topRow++;
  893. fullNeedsDisplay = true;
  894. }
  895. currentColumn = 0;
  896. if (currentColumn < leftColumn) {
  897. fullNeedsDisplay = true;
  898. leftColumn = 0;
  899. }
  900. if (fullNeedsDisplay)
  901. SetNeedsDisplay ();
  902. else
  903. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  904. break;
  905. default:
  906. // Ignore control characters and other special keys
  907. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  908. return false;
  909. //So that special keys like tab can be processed
  910. if (isReadOnly)
  911. return true;
  912. Insert ((uint)kb.Key);
  913. currentColumn++;
  914. if (currentColumn >= leftColumn + Frame.Width) {
  915. leftColumn++;
  916. SetNeedsDisplay ();
  917. }
  918. PositionCursor ();
  919. return true;
  920. }
  921. return true;
  922. }
  923. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  924. {
  925. if (col < 0 || row < 0)
  926. yield break;
  927. if (row >= model.Count)
  928. yield break;
  929. var line = GetCurrentLine ();
  930. if (col >= line.Count)
  931. yield break;
  932. while (row < model.Count) {
  933. for (int c = col; c < line.Count; c++) {
  934. yield return (c, row, line [c]);
  935. }
  936. col = 0;
  937. row++;
  938. line = GetCurrentLine ();
  939. }
  940. }
  941. Rune RuneAt (int col, int row) => model.GetLine (row) [col];
  942. bool MoveNext (ref int col, ref int row, out Rune rune)
  943. {
  944. var line = model.GetLine (row);
  945. if (col + 1 < line.Count) {
  946. col++;
  947. rune = line [col];
  948. return true;
  949. }
  950. while (row + 1 < model.Count){
  951. col = 0;
  952. row++;
  953. line = model.GetLine (row);
  954. if (line.Count > 0) {
  955. rune = line [0];
  956. return true;
  957. }
  958. }
  959. rune = 0;
  960. return false;
  961. }
  962. bool MovePrev (ref int col, ref int row, out Rune rune)
  963. {
  964. var line = model.GetLine (row);
  965. if (col > 0) {
  966. col--;
  967. rune = line [col];
  968. return true;
  969. }
  970. if (row == 0) {
  971. rune = 0;
  972. return false;
  973. }
  974. while (row > 0) {
  975. row--;
  976. line = model.GetLine (row);
  977. col = line.Count - 1;
  978. if (col >= 0) {
  979. rune = line [col];
  980. return true;
  981. }
  982. }
  983. rune = 0;
  984. return false;
  985. }
  986. (int col, int row)? WordForward (int fromCol, int fromRow)
  987. {
  988. var col = fromCol;
  989. var row = fromRow;
  990. var line = GetCurrentLine ();
  991. var rune = RuneAt (col, row);
  992. var srow = row;
  993. if (Rune.IsPunctuation (rune) || Rune.IsWhiteSpace (rune)) {
  994. while (MoveNext (ref col, ref row, out rune)){
  995. if (Rune.IsLetterOrDigit (rune))
  996. break;
  997. }
  998. while (MoveNext (ref col, ref row, out rune)) {
  999. if (!Rune.IsLetterOrDigit (rune))
  1000. break;
  1001. }
  1002. } else {
  1003. while (MoveNext (ref col, ref row, out rune)) {
  1004. if (!Rune.IsLetterOrDigit (rune))
  1005. break;
  1006. }
  1007. }
  1008. if (fromCol != col || fromRow != row)
  1009. return (col, row);
  1010. return null;
  1011. }
  1012. (int col, int row)? WordBackward (int fromCol, int fromRow)
  1013. {
  1014. if (fromRow == 0 && fromCol == 0)
  1015. return null;
  1016. var col = fromCol;
  1017. var row = fromRow;
  1018. var line = GetCurrentLine ();
  1019. var rune = RuneAt (col, row);
  1020. if (Rune.IsPunctuation (rune) || Rune.IsSymbol (rune) || Rune.IsWhiteSpace (rune)) {
  1021. while (MovePrev (ref col, ref row, out rune)){
  1022. if (Rune.IsLetterOrDigit (rune))
  1023. break;
  1024. }
  1025. while (MovePrev (ref col, ref row, out rune)){
  1026. if (!Rune.IsLetterOrDigit (rune))
  1027. break;
  1028. }
  1029. } else {
  1030. while (MovePrev (ref col, ref row, out rune)) {
  1031. if (!Rune.IsLetterOrDigit (rune))
  1032. break;
  1033. }
  1034. }
  1035. if (fromCol != col || fromRow != row)
  1036. return (col, row);
  1037. return null;
  1038. }
  1039. public override bool MouseEvent (MouseEvent ev)
  1040. {
  1041. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  1042. return false;
  1043. }
  1044. if (!HasFocus)
  1045. SuperView.SetFocus (this);
  1046. var maxCursorPositionableLine = (model.Count - 1) - topRow;
  1047. if (ev.Y > maxCursorPositionableLine) {
  1048. currentRow = maxCursorPositionableLine;
  1049. } else {
  1050. currentRow = ev.Y + topRow;
  1051. }
  1052. var r = GetCurrentLine ();
  1053. if (ev.X - leftColumn >= r.Count)
  1054. currentColumn = r.Count - leftColumn;
  1055. else
  1056. currentColumn = ev.X - leftColumn;
  1057. PositionCursor ();
  1058. return true;
  1059. }
  1060. }
  1061. }