TextView.cs 29 KB

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