TextView.cs 31 KB

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