TextView.cs 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156
  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. using Rune = System.Rune;
  31. namespace Terminal.Gui {
  32. class TextModel {
  33. List<List<Rune>> lines = new List<List<Rune>> ();
  34. public event Action LinesLoaded;
  35. public bool LoadFile (string file)
  36. {
  37. FilePath = file ?? throw new ArgumentNullException (nameof (file));
  38. var stream = File.OpenRead (file);
  39. LoadStream (stream);
  40. return true;
  41. }
  42. public bool CloseFile ()
  43. {
  44. if (FilePath == null)
  45. throw new ArgumentNullException (nameof (FilePath));
  46. FilePath = null;
  47. lines = new List<List<Rune>> ();
  48. return true;
  49. }
  50. // Turns the ustring into runes, this does not split the
  51. // contents on a newline if it is present.
  52. internal static List<Rune> ToRunes (ustring str)
  53. {
  54. List<Rune> runes = new List<Rune> ();
  55. foreach (var x in str.ToRunes ()) {
  56. runes.Add (x);
  57. }
  58. return runes;
  59. }
  60. // Splits a string into a List that contains a List<Rune> for each line
  61. public static List<List<Rune>> StringToRunes (ustring content)
  62. {
  63. var lines = new List<List<Rune>> ();
  64. int start = 0, i = 0;
  65. var hasCR = false;
  66. // ASCII code 13 = Carriage Return.
  67. // ASCII code 10 = Line Feed.
  68. for (; i < content.Length; i++) {
  69. if (content [i] == 13) {
  70. hasCR = true;
  71. continue;
  72. }
  73. if (content [i] == 10) {
  74. if (i - start > 0)
  75. lines.Add (ToRunes (content [start, hasCR ? i - 1 : i]));
  76. else
  77. lines.Add (ToRunes (ustring.Empty));
  78. start = i + 1;
  79. hasCR = false;
  80. }
  81. }
  82. if (i - start >= 0)
  83. lines.Add (ToRunes (content [start, null]));
  84. return lines;
  85. }
  86. void Append (List<byte> line)
  87. {
  88. var str = ustring.Make (line.ToArray ());
  89. lines.Add (ToRunes (str));
  90. }
  91. public void LoadStream (Stream input)
  92. {
  93. if (input == null)
  94. throw new ArgumentNullException (nameof (input));
  95. lines = new List<List<Rune>> ();
  96. var buff = new BufferedStream (input);
  97. int v;
  98. var line = new List<byte> ();
  99. var wasNewLine = false;
  100. while ((v = buff.ReadByte ()) != -1) {
  101. if (v == 13) {
  102. continue;
  103. }
  104. if (v == 10) {
  105. Append (line);
  106. line.Clear ();
  107. wasNewLine = true;
  108. continue;
  109. }
  110. line.Add ((byte)v);
  111. wasNewLine = false;
  112. }
  113. if (line.Count > 0 || wasNewLine)
  114. Append (line);
  115. buff.Dispose ();
  116. OnLinesLoaded ();
  117. }
  118. public void LoadString (ustring content)
  119. {
  120. lines = StringToRunes (content);
  121. OnLinesLoaded ();
  122. }
  123. void OnLinesLoaded ()
  124. {
  125. LinesLoaded?.Invoke ();
  126. }
  127. public override string ToString ()
  128. {
  129. var sb = new StringBuilder ();
  130. for (int i = 0; i < lines.Count; i++) {
  131. sb.Append (ustring.Make (lines [i]));
  132. if ((i + 1) < lines.Count) {
  133. sb.AppendLine ();
  134. }
  135. }
  136. return sb.ToString ();
  137. }
  138. public string FilePath { get; set; }
  139. /// <summary>
  140. /// The number of text lines in the model
  141. /// </summary>
  142. public int Count => lines.Count;
  143. /// <summary>
  144. /// Returns the specified line as a List of Rune
  145. /// </summary>
  146. /// <returns>The line.</returns>
  147. /// <param name="line">Line number to retrieve.</param>
  148. public List<Rune> GetLine (int line)
  149. {
  150. if (lines.Count > 0) {
  151. if (line < Count) {
  152. return lines [line];
  153. } else {
  154. return lines [Count - 1];
  155. }
  156. } else {
  157. lines.Add (new List<Rune> ());
  158. return lines [0];
  159. }
  160. }
  161. /// <summary>
  162. /// Adds a line to the model at the specified position.
  163. /// </summary>
  164. /// <param name="pos">Line number where the line will be inserted.</param>
  165. /// <param name="runes">The line of text, as a List of Rune.</param>
  166. public void AddLine (int pos, List<Rune> runes)
  167. {
  168. lines.Insert (pos, runes);
  169. }
  170. /// <summary>
  171. /// Removes the line at the specified position
  172. /// </summary>
  173. /// <param name="pos">Position.</param>
  174. public void RemoveLine (int pos)
  175. {
  176. if (lines.Count > 0) {
  177. if (lines.Count == 1 && lines [0].Count == 0) {
  178. return;
  179. }
  180. lines.RemoveAt (pos);
  181. }
  182. }
  183. public void ReplaceLine (int pos, List<Rune> runes)
  184. {
  185. if (lines.Count > 0 && pos < lines.Count) {
  186. lines [pos] = new List<Rune> (runes);
  187. } else if (lines.Count == 0 || (lines.Count > 0 && pos >= lines.Count)) {
  188. lines.Add (runes);
  189. }
  190. }
  191. /// <summary>
  192. /// Returns the maximum line length of the visible lines.
  193. /// </summary>
  194. /// <param name="first">The first line.</param>
  195. /// <param name="last">The last line.</param>
  196. /// <param name="tabWidth">The tab width.</param>
  197. public int GetMaxVisibleLine (int first, int last, int tabWidth)
  198. {
  199. int maxLength = 0;
  200. last = last < lines.Count ? last : lines.Count;
  201. for (int i = first; i < last; i++) {
  202. var line = GetLine (i);
  203. var tabSum = line.Sum (r => r == '\t' ? Math.Max (tabWidth - 1, 0) : 0);
  204. var l = line.Count + tabSum;
  205. if (l > maxLength) {
  206. maxLength = l;
  207. }
  208. }
  209. return maxLength;
  210. }
  211. internal static bool SetCol (ref int col, int width, int cols)
  212. {
  213. if (col + cols <= width) {
  214. col += cols;
  215. return true;
  216. }
  217. return false;
  218. }
  219. internal static int GetColFromX (List<Rune> t, int start, int x, int tabWidth = 0)
  220. {
  221. if (x < 0) {
  222. return x;
  223. }
  224. int size = start;
  225. var pX = x + start;
  226. for (int i = start; i < t.Count; i++) {
  227. var r = t [i];
  228. size += Rune.ColumnWidth (r);
  229. if (r == '\t') {
  230. size += tabWidth + 1;
  231. }
  232. if (i == pX || (size > pX)) {
  233. return i - start;
  234. }
  235. }
  236. return t.Count - start;
  237. }
  238. // Returns the size and length in a range of the string.
  239. internal static (int size, int length) DisplaySize (List<Rune> t, int start = -1, int end = -1,
  240. bool checkNextRune = true, int tabWidth = 0)
  241. {
  242. if (t == null || t.Count == 0) {
  243. return (0, 0);
  244. }
  245. int size = 0;
  246. int len = 0;
  247. int tcount = end == -1 ? t.Count : end > t.Count ? t.Count : end;
  248. int i = start == -1 ? 0 : start;
  249. for (; i < tcount; i++) {
  250. var rune = t [i];
  251. size += Rune.ColumnWidth (rune);
  252. len += Rune.RuneLen (rune);
  253. if (rune == '\t') {
  254. size += tabWidth + 1;
  255. len += tabWidth - 1;
  256. }
  257. if (checkNextRune && i == tcount - 1 && t.Count > tcount
  258. && IsWideRune (t [i + 1], tabWidth, out int s, out int l)) {
  259. size += s;
  260. len += l;
  261. }
  262. }
  263. bool IsWideRune (Rune r, int tWidth, out int s, out int l)
  264. {
  265. s = Rune.ColumnWidth (r);
  266. l = Rune.RuneLen (r);
  267. if (r == '\t') {
  268. s += tWidth + 1;
  269. l += tWidth - 1;
  270. }
  271. return s > 1;
  272. }
  273. return (size, len);
  274. }
  275. // Returns the left column in a range of the string.
  276. internal static int CalculateLeftColumn (List<Rune> t, int start, int end, int width, int tabWidth = 0)
  277. {
  278. if (t == null || t.Count == 0) {
  279. return 0;
  280. }
  281. int size = 0;
  282. int tcount = end > t.Count - 1 ? t.Count - 1 : end;
  283. int col = 0;
  284. for (int i = tcount; i >= 0; i--) {
  285. var rune = t [i];
  286. size += Rune.ColumnWidth (rune);
  287. if (rune == '\t') {
  288. size += tabWidth + 1;
  289. }
  290. if (size > width) {
  291. if (col + width == end) {
  292. col++;
  293. }
  294. break;
  295. } else if ((end < t.Count && col > 0 && start < end && col == start) || (end - col == width - 1)) {
  296. break;
  297. }
  298. col = i;
  299. }
  300. return col;
  301. }
  302. (Point startPointToFind, Point currentPointToFind, bool found) toFind;
  303. internal (Point current, bool found) FindNextText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  304. {
  305. if (text == null || lines.Count == 0) {
  306. gaveFullTurn = false;
  307. return (Point.Empty, false);
  308. }
  309. if (toFind.found) {
  310. toFind.currentPointToFind.X++;
  311. }
  312. var foundPos = GetFoundNextTextPoint (text, lines.Count, matchCase, matchWholeWord, toFind.currentPointToFind);
  313. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  314. foundPos = GetFoundNextTextPoint (text, toFind.startPointToFind.Y + 1, matchCase, matchWholeWord, Point.Empty);
  315. }
  316. gaveFullTurn = ApplyToFind (foundPos);
  317. return foundPos;
  318. }
  319. internal (Point current, bool found) FindPreviousText (ustring text, out bool gaveFullTurn, bool matchCase = false, bool matchWholeWord = false)
  320. {
  321. if (text == null || lines.Count == 0) {
  322. gaveFullTurn = false;
  323. return (Point.Empty, false);
  324. }
  325. if (toFind.found) {
  326. toFind.currentPointToFind.X++;
  327. }
  328. var linesCount = toFind.currentPointToFind.IsEmpty ? lines.Count - 1 : toFind.currentPointToFind.Y;
  329. var foundPos = GetFoundPreviousTextPoint (text, linesCount, matchCase, matchWholeWord, toFind.currentPointToFind);
  330. if (!foundPos.found && toFind.currentPointToFind != toFind.startPointToFind) {
  331. foundPos = GetFoundPreviousTextPoint (text, lines.Count - 1, matchCase, matchWholeWord,
  332. new Point (lines [lines.Count - 1].Count, lines.Count));
  333. }
  334. gaveFullTurn = ApplyToFind (foundPos);
  335. return foundPos;
  336. }
  337. internal (Point current, bool found) ReplaceAllText (ustring text, bool matchCase = false, bool matchWholeWord = false, ustring textToReplace = null)
  338. {
  339. bool found = false;
  340. Point pos = Point.Empty;
  341. for (int i = 0; i < lines.Count; i++) {
  342. var x = lines [i];
  343. var txt = GetText (x);
  344. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  345. var col = txt.IndexOf (matchText);
  346. while (col > -1) {
  347. if (matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  348. if (col + 1 > txt.Length) {
  349. break;
  350. }
  351. col = txt.IndexOf (matchText, col + 1);
  352. continue;
  353. }
  354. if (col > -1) {
  355. if (!found) {
  356. found = true;
  357. }
  358. lines [i] = ReplaceText (x, textToReplace, matchText, col).ToRuneList ();
  359. x = lines [i];
  360. txt = GetText (x);
  361. pos = new Point (col, i);
  362. col += (textToReplace.Length - matchText.Length);
  363. }
  364. if (col + 1 > txt.Length) {
  365. break;
  366. }
  367. col = txt.IndexOf (matchText, col + 1);
  368. }
  369. }
  370. string GetText (List<Rune> x)
  371. {
  372. var txt = ustring.Make (x).ToString ();
  373. if (!matchCase) {
  374. txt = txt.ToUpper ();
  375. }
  376. return txt;
  377. }
  378. return (pos, found);
  379. }
  380. ustring ReplaceText (List<Rune> source, ustring textToReplace, string matchText, int col)
  381. {
  382. var origTxt = ustring.Make (source);
  383. (int _, int len) = TextModel.DisplaySize (source, 0, col, false);
  384. (var _, var len2) = TextModel.DisplaySize (source, col, col + matchText.Length, false);
  385. (var _, var len3) = TextModel.DisplaySize (source, col + matchText.Length, origTxt.RuneCount, false);
  386. return origTxt [0, len] +
  387. textToReplace.ToString () +
  388. origTxt [len + len2, len + len2 + len3];
  389. }
  390. bool ApplyToFind ((Point current, bool found) foundPos)
  391. {
  392. bool gaveFullTurn = false;
  393. if (foundPos.found) {
  394. toFind.currentPointToFind = foundPos.current;
  395. if (toFind.found && toFind.currentPointToFind == toFind.startPointToFind) {
  396. gaveFullTurn = true;
  397. }
  398. if (!toFind.found) {
  399. toFind.startPointToFind = toFind.currentPointToFind = foundPos.current;
  400. toFind.found = foundPos.found;
  401. }
  402. }
  403. return gaveFullTurn;
  404. }
  405. (Point current, bool found) GetFoundNextTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  406. {
  407. for (int i = start.Y; i < linesCount; i++) {
  408. var x = lines [i];
  409. var txt = ustring.Make (x).ToString ();
  410. if (!matchCase) {
  411. txt = txt.ToUpper ();
  412. }
  413. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  414. var col = txt.IndexOf (matchText, Math.Min (start.X, txt.Length));
  415. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  416. continue;
  417. }
  418. if (col > -1 && ((i == start.Y && col >= start.X)
  419. || i > start.Y)
  420. && txt.Contains (matchText)) {
  421. return (new Point (col, i), true);
  422. } else if (col == -1 && start.X > 0) {
  423. start.X = 0;
  424. }
  425. }
  426. return (Point.Empty, false);
  427. }
  428. (Point current, bool found) GetFoundPreviousTextPoint (ustring text, int linesCount, bool matchCase, bool matchWholeWord, Point start)
  429. {
  430. for (int i = linesCount; i >= 0; i--) {
  431. var x = lines [i];
  432. var txt = ustring.Make (x).ToString ();
  433. if (!matchCase) {
  434. txt = txt.ToUpper ();
  435. }
  436. if (start.Y != i) {
  437. start.X = Math.Max (x.Count - 1, 0);
  438. }
  439. var matchText = !matchCase ? text.ToUpper ().ToString () : text.ToString ();
  440. var col = txt.LastIndexOf (matchText, toFind.found ? start.X - 1 : start.X);
  441. if (col > -1 && matchWholeWord && !MatchWholeWord (txt, matchText, col)) {
  442. continue;
  443. }
  444. if (col > -1 && ((i <= linesCount && col <= start.X)
  445. || i < start.Y)
  446. && txt.Contains (matchText)) {
  447. return (new Point (col, i), true);
  448. }
  449. }
  450. return (Point.Empty, false);
  451. }
  452. bool MatchWholeWord (string source, string matchText, int index = 0)
  453. {
  454. if (string.IsNullOrEmpty (source) || string.IsNullOrEmpty (matchText)) {
  455. return false;
  456. }
  457. var txt = matchText.Trim ();
  458. var start = index > 0 ? index - 1 : 0;
  459. var end = index + txt.Length;
  460. if ((start == 0 || Rune.IsWhiteSpace (source [start]))
  461. && (end == source.Length || Rune.IsWhiteSpace (source [end]))) {
  462. return true;
  463. }
  464. return false;
  465. }
  466. /// <summary>
  467. /// Redefine column and line tracking.
  468. /// </summary>
  469. /// <param name="point">Contains the column and line.</param>
  470. internal void ResetContinuousFind (Point point)
  471. {
  472. toFind.startPointToFind = toFind.currentPointToFind = point;
  473. toFind.found = false;
  474. }
  475. }
  476. class HistoryText {
  477. public enum LineStatus {
  478. Original,
  479. Replaced,
  480. Removed,
  481. Added
  482. }
  483. public class HistoryTextItem {
  484. public List<List<Rune>> Lines;
  485. public Point CursorPosition;
  486. public LineStatus LineStatus;
  487. public bool IsUndoing;
  488. public Point FinalCursorPosition;
  489. public HistoryTextItem RemovedOnAdded;
  490. public HistoryTextItem (List<List<Rune>> lines, Point curPos, LineStatus linesStatus)
  491. {
  492. Lines = lines;
  493. CursorPosition = curPos;
  494. LineStatus = linesStatus;
  495. }
  496. public HistoryTextItem (HistoryTextItem historyTextItem)
  497. {
  498. Lines = new List<List<Rune>> (historyTextItem.Lines);
  499. CursorPosition = new Point (historyTextItem.CursorPosition.X, historyTextItem.CursorPosition.Y);
  500. LineStatus = historyTextItem.LineStatus;
  501. }
  502. public override string ToString ()
  503. {
  504. return $"(Count: {Lines.Count}, Cursor: {CursorPosition}, Status: {LineStatus})";
  505. }
  506. }
  507. List<HistoryTextItem> historyTextItems = new List<HistoryTextItem> ();
  508. int idxHistoryText = -1;
  509. ustring originalText;
  510. public bool IsFromHistory { get; private set; }
  511. public bool HasHistoryChanges => idxHistoryText > -1;
  512. public event Action<HistoryTextItem> ChangeText;
  513. public void Add (List<List<Rune>> lines, Point curPos, LineStatus lineStatus = LineStatus.Original)
  514. {
  515. if (lineStatus == LineStatus.Original && historyTextItems.Count > 0
  516. && historyTextItems.Last ().LineStatus == LineStatus.Original) {
  517. return;
  518. }
  519. if (lineStatus == LineStatus.Replaced && historyTextItems.Count > 0
  520. && historyTextItems.Last ().LineStatus == LineStatus.Replaced) {
  521. return;
  522. }
  523. if (historyTextItems.Count == 0 && lineStatus != LineStatus.Original)
  524. throw new ArgumentException ("The first item must be the original.");
  525. if (idxHistoryText >= 0 && idxHistoryText + 1 < historyTextItems.Count)
  526. historyTextItems.RemoveRange (idxHistoryText + 1, historyTextItems.Count - idxHistoryText - 1);
  527. historyTextItems.Add (new HistoryTextItem (lines, curPos, lineStatus));
  528. idxHistoryText++;
  529. }
  530. public void ReplaceLast (List<List<Rune>> lines, Point curPos, LineStatus lineStatus)
  531. {
  532. var found = historyTextItems.FindLast (x => x.LineStatus == lineStatus);
  533. if (found != null) {
  534. found.Lines = lines;
  535. found.CursorPosition = curPos;
  536. }
  537. }
  538. public void Undo ()
  539. {
  540. if (historyTextItems?.Count > 0 && idxHistoryText > 0) {
  541. IsFromHistory = true;
  542. idxHistoryText--;
  543. var historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]) {
  544. IsUndoing = true
  545. };
  546. ProcessChanges (ref historyTextItem);
  547. IsFromHistory = false;
  548. }
  549. }
  550. public void Redo ()
  551. {
  552. if (historyTextItems?.Count > 0 && idxHistoryText < historyTextItems.Count - 1) {
  553. IsFromHistory = true;
  554. idxHistoryText++;
  555. var historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]) {
  556. IsUndoing = false
  557. };
  558. ProcessChanges (ref historyTextItem);
  559. IsFromHistory = false;
  560. }
  561. }
  562. void ProcessChanges (ref HistoryTextItem historyTextItem)
  563. {
  564. if (historyTextItem.IsUndoing) {
  565. if (idxHistoryText - 1 > -1 && ((historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Added)
  566. || historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed
  567. || (historyTextItem.LineStatus == LineStatus.Replaced &&
  568. historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original))) {
  569. idxHistoryText--;
  570. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Added
  571. && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  572. idxHistoryText--;
  573. }
  574. historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]);
  575. historyTextItem.IsUndoing = true;
  576. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  577. }
  578. if (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Added) {
  579. historyTextItem.RemovedOnAdded = new HistoryTextItem (historyTextItems [idxHistoryText + 1]);
  580. }
  581. if ((historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original)
  582. || (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Original)
  583. || (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed)) {
  584. if (!historyTextItem.Lines [0].SequenceEqual (historyTextItems [idxHistoryText - 1].Lines [0])
  585. && historyTextItem.CursorPosition == historyTextItems [idxHistoryText - 1].CursorPosition) {
  586. historyTextItem.Lines [0] = new List<Rune> (historyTextItems [idxHistoryText - 1].Lines [0]);
  587. }
  588. if (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  589. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText - 2].CursorPosition;
  590. } else {
  591. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText - 1].CursorPosition;
  592. }
  593. } else {
  594. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  595. }
  596. OnChangeText (historyTextItem);
  597. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Removed
  598. || historyTextItems [idxHistoryText].LineStatus == LineStatus.Added) {
  599. idxHistoryText--;
  600. }
  601. } else if (!historyTextItem.IsUndoing) {
  602. if (idxHistoryText + 1 < historyTextItems.Count && (historyTextItem.LineStatus == LineStatus.Original
  603. || historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Added
  604. || historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Removed)) {
  605. idxHistoryText++;
  606. historyTextItem = new HistoryTextItem (historyTextItems [idxHistoryText]);
  607. historyTextItem.IsUndoing = false;
  608. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  609. }
  610. if (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText - 1].LineStatus == LineStatus.Removed) {
  611. historyTextItem.RemovedOnAdded = new HistoryTextItem (historyTextItems [idxHistoryText - 1]);
  612. }
  613. if ((historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Replaced)
  614. || (historyTextItem.LineStatus == LineStatus.Removed && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Original)
  615. || (historyTextItem.LineStatus == LineStatus.Added && historyTextItems [idxHistoryText + 1].LineStatus == LineStatus.Replaced)) {
  616. if (historyTextItem.LineStatus == LineStatus.Removed
  617. && !historyTextItem.Lines [0].SequenceEqual (historyTextItems [idxHistoryText + 1].Lines [0])) {
  618. historyTextItem.Lines [0] = new List<Rune> (historyTextItems [idxHistoryText + 1].Lines [0]);
  619. }
  620. historyTextItem.FinalCursorPosition = historyTextItems [idxHistoryText + 1].CursorPosition;
  621. } else {
  622. historyTextItem.FinalCursorPosition = historyTextItem.CursorPosition;
  623. }
  624. OnChangeText (historyTextItem);
  625. while (historyTextItems [idxHistoryText].LineStatus == LineStatus.Removed
  626. || historyTextItems [idxHistoryText].LineStatus == LineStatus.Added) {
  627. idxHistoryText++;
  628. }
  629. }
  630. }
  631. void OnChangeText (HistoryTextItem lines)
  632. {
  633. ChangeText?.Invoke (lines);
  634. }
  635. public void Clear (ustring text)
  636. {
  637. historyTextItems.Clear ();
  638. idxHistoryText = -1;
  639. originalText = text;
  640. }
  641. public bool IsDirty (ustring text)
  642. {
  643. return originalText != text;
  644. }
  645. }
  646. class WordWrapManager {
  647. class WrappedLine {
  648. public int ModelLine;
  649. public int Row;
  650. public int RowIndex;
  651. public int ColWidth;
  652. }
  653. List<WrappedLine> wrappedModelLines = new List<WrappedLine> ();
  654. int frameWidth;
  655. bool isWrapModelRefreshing;
  656. public TextModel Model { get; private set; }
  657. public WordWrapManager (TextModel model)
  658. {
  659. Model = model;
  660. }
  661. public TextModel WrapModel (int width, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  662. int row = 0, int col = 0, int startRow = 0, int startCol = 0, int tabWidth = 0)
  663. {
  664. frameWidth = width;
  665. var modelRow = isWrapModelRefreshing ? row : GetModelLineFromWrappedLines (row);
  666. var modelCol = isWrapModelRefreshing ? col : GetModelColFromWrappedLines (row, col);
  667. var modelStartRow = isWrapModelRefreshing ? startRow : GetModelLineFromWrappedLines (startRow);
  668. var modelStartCol = isWrapModelRefreshing ? startCol : GetModelColFromWrappedLines (startRow, startCol);
  669. var wrappedModel = new TextModel ();
  670. int lines = 0;
  671. nRow = 0;
  672. nCol = 0;
  673. nStartRow = 0;
  674. nStartCol = 0;
  675. bool isRowAndColSetted = row == 0 && col == 0;
  676. bool isStartRowAndColSetted = startRow == 0 && startCol == 0;
  677. List<WrappedLine> wModelLines = new List<WrappedLine> ();
  678. for (int i = 0; i < Model.Count; i++) {
  679. var line = Model.GetLine (i);
  680. var wrappedLines = ToListRune (
  681. TextFormatter.Format (ustring.Make (line), width,
  682. TextAlignment.Left, true, true, tabWidth));
  683. int sumColWidth = 0;
  684. for (int j = 0; j < wrappedLines.Count; j++) {
  685. var wrapLine = wrappedLines [j];
  686. if (!isRowAndColSetted && modelRow == i) {
  687. if (nCol + wrapLine.Count <= modelCol) {
  688. nCol += wrapLine.Count;
  689. nRow = lines;
  690. if (nCol == modelCol) {
  691. nCol = wrapLine.Count;
  692. isRowAndColSetted = true;
  693. } else if (j == wrappedLines.Count - 1) {
  694. nCol = wrapLine.Count - j + modelCol - nCol;
  695. isRowAndColSetted = true;
  696. }
  697. } else {
  698. var offset = nCol + wrapLine.Count - modelCol;
  699. nCol = wrapLine.Count - offset;
  700. nRow = lines;
  701. isRowAndColSetted = true;
  702. }
  703. }
  704. if (!isStartRowAndColSetted && modelStartRow == i) {
  705. if (nStartCol + wrapLine.Count <= modelStartCol) {
  706. nStartCol += wrapLine.Count;
  707. nStartRow = lines;
  708. if (nStartCol == modelStartCol) {
  709. nStartCol = wrapLine.Count;
  710. isStartRowAndColSetted = true;
  711. } else if (j == wrappedLines.Count - 1) {
  712. nStartCol = wrapLine.Count - j + modelStartCol - nStartCol;
  713. isStartRowAndColSetted = true;
  714. }
  715. } else {
  716. var offset = nStartCol + wrapLine.Count - modelStartCol;
  717. nStartCol = wrapLine.Count - offset;
  718. nStartRow = lines;
  719. isStartRowAndColSetted = true;
  720. }
  721. }
  722. wrappedModel.AddLine (lines, wrapLine);
  723. sumColWidth += wrapLine.Count;
  724. var wrappedLine = new WrappedLine () {
  725. ModelLine = i,
  726. Row = lines,
  727. RowIndex = j,
  728. ColWidth = wrapLine.Count,
  729. };
  730. wModelLines.Add (wrappedLine);
  731. lines++;
  732. }
  733. }
  734. wrappedModelLines = wModelLines;
  735. return wrappedModel;
  736. }
  737. public List<List<Rune>> ToListRune (List<ustring> textList)
  738. {
  739. var runesList = new List<List<Rune>> ();
  740. foreach (var text in textList) {
  741. runesList.Add (text.ToRuneList ());
  742. }
  743. return runesList;
  744. }
  745. public int GetModelLineFromWrappedLines (int line) => wrappedModelLines.Count > 0
  746. ? wrappedModelLines [Math.Min (line, wrappedModelLines.Count - 1)].ModelLine
  747. : 0;
  748. public int GetModelColFromWrappedLines (int line, int col)
  749. {
  750. if (wrappedModelLines?.Count == 0) {
  751. return 0;
  752. }
  753. var modelLine = GetModelLineFromWrappedLines (line);
  754. var firstLine = wrappedModelLines.IndexOf (r => r.ModelLine == modelLine);
  755. int modelCol = 0;
  756. for (int i = firstLine; i <= line; i++) {
  757. var wLine = wrappedModelLines [i];
  758. if (i < line) {
  759. modelCol += wLine.ColWidth;
  760. } else {
  761. modelCol += col;
  762. }
  763. }
  764. return modelCol;
  765. }
  766. List<Rune> GetCurrentLine (int row) => Model.GetLine (row);
  767. public void AddLine (int row, int col)
  768. {
  769. var modelRow = GetModelLineFromWrappedLines (row);
  770. var modelCol = GetModelColFromWrappedLines (row, col);
  771. var line = GetCurrentLine (modelRow);
  772. var restCount = line.Count - modelCol;
  773. var rest = line.GetRange (modelCol, restCount);
  774. line.RemoveRange (modelCol, restCount);
  775. Model.AddLine (modelRow + 1, rest);
  776. isWrapModelRefreshing = true;
  777. WrapModel (frameWidth, out _, out _, out _, out _, modelRow + 1, 0);
  778. isWrapModelRefreshing = false;
  779. }
  780. public bool Insert (int row, int col, Rune rune)
  781. {
  782. var line = GetCurrentLine (GetModelLineFromWrappedLines (row));
  783. line.Insert (GetModelColFromWrappedLines (row, col), rune);
  784. if (line.Count > frameWidth) {
  785. return true;
  786. } else {
  787. return false;
  788. }
  789. }
  790. public bool RemoveAt (int row, int col)
  791. {
  792. var modelRow = GetModelLineFromWrappedLines (row);
  793. var line = GetCurrentLine (modelRow);
  794. var modelCol = GetModelColFromWrappedLines (row, col);
  795. if (modelCol >= line.Count) {
  796. Model.RemoveLine (modelRow);
  797. RemoveAt (row, 0);
  798. return false;
  799. }
  800. line.RemoveAt (modelCol);
  801. if (line.Count > frameWidth || (row + 1 < wrappedModelLines.Count
  802. && wrappedModelLines [row + 1].ModelLine == modelRow)) {
  803. return true;
  804. }
  805. return false;
  806. }
  807. public bool RemoveLine (int row, int col, out bool lineRemoved, bool forward = true)
  808. {
  809. lineRemoved = false;
  810. var modelRow = GetModelLineFromWrappedLines (row);
  811. var line = GetCurrentLine (modelRow);
  812. var modelCol = GetModelColFromWrappedLines (row, col);
  813. if (modelCol == 0 && line.Count == 0) {
  814. Model.RemoveLine (modelRow);
  815. return false;
  816. } else if (modelCol < line.Count) {
  817. if (forward) {
  818. line.RemoveAt (modelCol);
  819. return true;
  820. } else if (modelCol - 1 > -1) {
  821. line.RemoveAt (modelCol - 1);
  822. return true;
  823. }
  824. }
  825. lineRemoved = true;
  826. if (forward) {
  827. if (modelRow + 1 == Model.Count) {
  828. return false;
  829. }
  830. var nextLine = Model.GetLine (modelRow + 1);
  831. line.AddRange (nextLine);
  832. Model.RemoveLine (modelRow + 1);
  833. if (line.Count > frameWidth) {
  834. return true;
  835. }
  836. } else {
  837. if (modelRow == 0) {
  838. return false;
  839. }
  840. var prevLine = Model.GetLine (modelRow - 1);
  841. prevLine.AddRange (line);
  842. Model.RemoveLine (modelRow);
  843. if (prevLine.Count > frameWidth) {
  844. return true;
  845. }
  846. }
  847. return false;
  848. }
  849. public bool RemoveRange (int row, int index, int count)
  850. {
  851. var modelRow = GetModelLineFromWrappedLines (row);
  852. var line = GetCurrentLine (modelRow);
  853. var modelCol = GetModelColFromWrappedLines (row, index);
  854. try {
  855. line.RemoveRange (modelCol, count);
  856. } catch (Exception) {
  857. return false;
  858. }
  859. return true;
  860. }
  861. public void UpdateModel (TextModel model, out int nRow, out int nCol, out int nStartRow, out int nStartCol,
  862. int row, int col, int startRow, int startCol)
  863. {
  864. isWrapModelRefreshing = true;
  865. Model = model;
  866. WrapModel (frameWidth, out nRow, out nCol, out nStartRow, out nStartCol, row, col, startRow, startCol);
  867. isWrapModelRefreshing = false;
  868. }
  869. }
  870. /// <summary>
  871. /// Multi-line text editing <see cref="View"/>
  872. /// </summary>
  873. /// <remarks>
  874. /// <para>
  875. /// <see cref="TextView"/> provides a multi-line text editor. Users interact
  876. /// with it with the standard Emacs commands for movement or the arrow
  877. /// keys.
  878. /// </para>
  879. /// <list type="table">
  880. /// <listheader>
  881. /// <term>Shortcut</term>
  882. /// <description>Action performed</description>
  883. /// </listheader>
  884. /// <item>
  885. /// <term>Left cursor, Control-b</term>
  886. /// <description>
  887. /// Moves the editing point left.
  888. /// </description>
  889. /// </item>
  890. /// <item>
  891. /// <term>Right cursor, Control-f</term>
  892. /// <description>
  893. /// Moves the editing point right.
  894. /// </description>
  895. /// </item>
  896. /// <item>
  897. /// <term>Alt-b</term>
  898. /// <description>
  899. /// Moves one word back.
  900. /// </description>
  901. /// </item>
  902. /// <item>
  903. /// <term>Alt-f</term>
  904. /// <description>
  905. /// Moves one word forward.
  906. /// </description>
  907. /// </item>
  908. /// <item>
  909. /// <term>Up cursor, Control-p</term>
  910. /// <description>
  911. /// Moves the editing point one line up.
  912. /// </description>
  913. /// </item>
  914. /// <item>
  915. /// <term>Down cursor, Control-n</term>
  916. /// <description>
  917. /// Moves the editing point one line down
  918. /// </description>
  919. /// </item>
  920. /// <item>
  921. /// <term>Home key, Control-a</term>
  922. /// <description>
  923. /// Moves the cursor to the beginning of the line.
  924. /// </description>
  925. /// </item>
  926. /// <item>
  927. /// <term>End key, Control-e</term>
  928. /// <description>
  929. /// Moves the cursor to the end of the line.
  930. /// </description>
  931. /// </item>
  932. /// <item>
  933. /// <term>Control-Home</term>
  934. /// <description>
  935. /// Scrolls to the first line and moves the cursor there.
  936. /// </description>
  937. /// </item>
  938. /// <item>
  939. /// <term>Control-End</term>
  940. /// <description>
  941. /// Scrolls to the last line and moves the cursor there.
  942. /// </description>
  943. /// </item>
  944. /// <item>
  945. /// <term>Delete, Control-d</term>
  946. /// <description>
  947. /// Deletes the character in front of the cursor.
  948. /// </description>
  949. /// </item>
  950. /// <item>
  951. /// <term>Backspace</term>
  952. /// <description>
  953. /// Deletes the character behind the cursor.
  954. /// </description>
  955. /// </item>
  956. /// <item>
  957. /// <term>Control-k</term>
  958. /// <description>
  959. /// Deletes the text until the end of the line and replaces the kill buffer
  960. /// with the deleted text. You can paste this text in a different place by
  961. /// using Control-y.
  962. /// </description>
  963. /// </item>
  964. /// <item>
  965. /// <term>Control-y</term>
  966. /// <description>
  967. /// Pastes the content of the kill ring into the current position.
  968. /// </description>
  969. /// </item>
  970. /// <item>
  971. /// <term>Alt-d</term>
  972. /// <description>
  973. /// Deletes the word above the cursor and adds it to the kill ring. You
  974. /// can paste the contents of the kill ring with Control-y.
  975. /// </description>
  976. /// </item>
  977. /// <item>
  978. /// <term>Control-q</term>
  979. /// <description>
  980. /// Quotes the next input character, to prevent the normal processing of
  981. /// key handling to take place.
  982. /// </description>
  983. /// </item>
  984. /// </list>
  985. /// </remarks>
  986. public class TextView : View {
  987. TextModel model = new TextModel ();
  988. int topRow;
  989. int leftColumn;
  990. int currentRow;
  991. int currentColumn;
  992. int selectionStartColumn, selectionStartRow;
  993. bool selecting;
  994. bool wordWrap;
  995. WordWrapManager wrapManager;
  996. bool continuousFind;
  997. int bottomOffset, rightOffset;
  998. int tabWidth = 4;
  999. bool allowsTab = true;
  1000. bool allowsReturn = true;
  1001. bool multiline = true;
  1002. HistoryText historyText = new HistoryText ();
  1003. /// <summary>
  1004. /// Raised when the <see cref="Text"/> of the <see cref="TextView"/> changes.
  1005. /// </summary>
  1006. public event Action TextChanged;
  1007. /// <summary>
  1008. /// Provides autocomplete context menu based on suggestions at the current cursor
  1009. /// position. Populate <see cref="Autocomplete.AllSuggestions"/> to enable this feature
  1010. /// </summary>
  1011. public IAutocomplete Autocomplete { get; protected set; } = new TextViewAutocomplete ();
  1012. #if false
  1013. /// <summary>
  1014. /// Changed event, raised when the text has clicked.
  1015. /// </summary>
  1016. /// <remarks>
  1017. /// Client code can hook up to this event, it is
  1018. /// raised when the text in the entry changes.
  1019. /// </remarks>
  1020. public Action Changed;
  1021. #endif
  1022. /// <summary>
  1023. /// Initializes a <see cref="TextView"/> on the specified area, with absolute position and size.
  1024. /// </summary>
  1025. /// <remarks>
  1026. /// </remarks>
  1027. public TextView (Rect frame) : base (frame)
  1028. {
  1029. Initialize ();
  1030. }
  1031. /// <summary>
  1032. /// Initializes a <see cref="TextView"/> on the specified area,
  1033. /// with dimensions controlled with the X, Y, Width and Height properties.
  1034. /// </summary>
  1035. public TextView () : base ()
  1036. {
  1037. Initialize ();
  1038. }
  1039. void Initialize ()
  1040. {
  1041. CanFocus = true;
  1042. Used = true;
  1043. model.LinesLoaded += Model_LinesLoaded;
  1044. historyText.ChangeText += HistoryText_ChangeText;
  1045. Initialized += TextView_Initialized;
  1046. // Things this view knows how to do
  1047. AddCommand (Command.PageDown, () => { ProcessPageDown (); return true; });
  1048. AddCommand (Command.PageDownExtend, () => { ProcessPageDownExtend (); return true; });
  1049. AddCommand (Command.PageUp, () => { ProcessPageUp (); return true; });
  1050. AddCommand (Command.PageUpExtend, () => { ProcessPageUpExtend (); return true; });
  1051. AddCommand (Command.LineDown, () => { ProcessMoveDown (); return true; });
  1052. AddCommand (Command.LineDownExtend, () => { ProcessMoveDownExtend (); return true; });
  1053. AddCommand (Command.LineUp, () => { ProcessMoveUp (); return true; });
  1054. AddCommand (Command.LineUpExtend, () => { ProcessMoveUpExtend (); return true; });
  1055. AddCommand (Command.Right, () => ProcessMoveRight ());
  1056. AddCommand (Command.RightExtend, () => { ProcessMoveRightExtend (); return true; });
  1057. AddCommand (Command.Left, () => ProcessMoveLeft ());
  1058. AddCommand (Command.LeftExtend, () => { ProcessMoveLeftExtend (); return true; });
  1059. AddCommand (Command.DeleteCharLeft, () => { ProcessDeleteCharLeft (); return true; });
  1060. AddCommand (Command.StartOfLine, () => { ProcessMoveStartOfLine (); return true; });
  1061. AddCommand (Command.StartOfLineExtend, () => { ProcessMoveStartOfLineExtend (); return true; });
  1062. AddCommand (Command.DeleteCharRight, () => { ProcessDeleteCharRight (); return true; });
  1063. AddCommand (Command.EndOfLine, () => { ProcessMoveEndOfLine (); return true; });
  1064. AddCommand (Command.EndOfLineExtend, () => { ProcessMoveEndOfLineExtend (); return true; });
  1065. AddCommand (Command.CutToEndLine, () => { KillToEndOfLine (); return true; });
  1066. AddCommand (Command.CutToStartLine, () => { KillToStartOfLine (); return true; });
  1067. AddCommand (Command.Paste, () => { ProcessPaste (); return true; });
  1068. AddCommand (Command.ToggleExtend, () => { ToggleSelecting (); return true; });
  1069. AddCommand (Command.Copy, () => { ProcessCopy (); return true; });
  1070. AddCommand (Command.Cut, () => { ProcessCut (); return true; });
  1071. AddCommand (Command.WordLeft, () => { ProcessMoveWordBackward (); return true; });
  1072. AddCommand (Command.WordLeftExtend, () => { ProcessMoveWordBackwardExtend (); return true; });
  1073. AddCommand (Command.WordRight, () => { ProcessMoveWordForward (); return true; });
  1074. AddCommand (Command.WordRightExtend, () => { ProcessMoveWordForwardExtend (); return true; });
  1075. AddCommand (Command.KillWordForwards, () => { ProcessKillWordForward (); return true; });
  1076. AddCommand (Command.KillWordBackwards, () => { ProcessKillWordBackward (); return true; });
  1077. AddCommand (Command.NewLine, () => ProcessReturn ());
  1078. AddCommand (Command.BottomEnd, () => { MoveBottomEnd (); return true; });
  1079. AddCommand (Command.BottomEndExtend, () => { MoveBottomEndExtend (); return true; });
  1080. AddCommand (Command.TopHome, () => { MoveTopHome (); return true; });
  1081. AddCommand (Command.TopHomeExtend, () => { MoveTopHomeExtend (); return true; });
  1082. AddCommand (Command.SelectAll, () => { ProcessSelectAll (); return true; });
  1083. AddCommand (Command.ToggleOverwrite, () => { ProcessSetOverwrite (); return true; });
  1084. AddCommand (Command.EnableOverwrite, () => { SetOverwrite (true); return true; });
  1085. AddCommand (Command.DisableOverwrite, () => { SetOverwrite (false); return true; });
  1086. AddCommand (Command.Tab, () => ProcessTab ());
  1087. AddCommand (Command.BackTab, () => ProcessBackTab ());
  1088. AddCommand (Command.NextView, () => ProcessMoveNextView ());
  1089. AddCommand (Command.PreviousView, () => ProcessMovePreviousView ());
  1090. AddCommand (Command.Undo, () => { UndoChanges (); return true; });
  1091. AddCommand (Command.Redo, () => { RedoChanges (); return true; });
  1092. // Default keybindings for this view
  1093. AddKeyBinding (Key.PageDown, Command.PageDown);
  1094. AddKeyBinding (Key.V | Key.CtrlMask, Command.PageDown);
  1095. AddKeyBinding (Key.PageDown | Key.ShiftMask, Command.PageDownExtend);
  1096. AddKeyBinding (Key.PageUp, Command.PageUp);
  1097. AddKeyBinding (((int)'V' + Key.AltMask), Command.PageUp);
  1098. AddKeyBinding (Key.PageUp | Key.ShiftMask, Command.PageUpExtend);
  1099. AddKeyBinding (Key.N | Key.CtrlMask, Command.LineDown);
  1100. AddKeyBinding (Key.CursorDown, Command.LineDown);
  1101. AddKeyBinding (Key.CursorDown | Key.ShiftMask, Command.LineDownExtend);
  1102. AddKeyBinding (Key.P | Key.CtrlMask, Command.LineUp);
  1103. AddKeyBinding (Key.CursorUp, Command.LineUp);
  1104. AddKeyBinding (Key.CursorUp | Key.ShiftMask, Command.LineUpExtend);
  1105. AddKeyBinding (Key.F | Key.CtrlMask, Command.Right);
  1106. AddKeyBinding (Key.CursorRight, Command.Right);
  1107. AddKeyBinding (Key.CursorRight | Key.ShiftMask, Command.RightExtend);
  1108. AddKeyBinding (Key.B | Key.CtrlMask, Command.Left);
  1109. AddKeyBinding (Key.CursorLeft, Command.Left);
  1110. AddKeyBinding (Key.CursorLeft | Key.ShiftMask, Command.LeftExtend);
  1111. AddKeyBinding (Key.Delete, Command.DeleteCharLeft);
  1112. AddKeyBinding (Key.Backspace, Command.DeleteCharLeft);
  1113. AddKeyBinding (Key.Home, Command.StartOfLine);
  1114. AddKeyBinding (Key.A | Key.CtrlMask, Command.StartOfLine);
  1115. AddKeyBinding (Key.Home | Key.ShiftMask, Command.StartOfLineExtend);
  1116. AddKeyBinding (Key.DeleteChar, Command.DeleteCharRight);
  1117. AddKeyBinding (Key.D | Key.CtrlMask, Command.DeleteCharRight);
  1118. AddKeyBinding (Key.End, Command.EndOfLine);
  1119. AddKeyBinding (Key.E | Key.CtrlMask, Command.EndOfLine);
  1120. AddKeyBinding (Key.End | Key.ShiftMask, Command.EndOfLineExtend);
  1121. AddKeyBinding (Key.K | Key.CtrlMask, Command.CutToEndLine); // kill-to-end
  1122. AddKeyBinding (Key.DeleteChar | Key.CtrlMask | Key.ShiftMask, Command.CutToEndLine); // kill-to-end
  1123. AddKeyBinding (Key.K | Key.AltMask, Command.CutToStartLine); // kill-to-start
  1124. AddKeyBinding (Key.Backspace | Key.CtrlMask | Key.ShiftMask, Command.CutToStartLine); // kill-to-start
  1125. AddKeyBinding (Key.Y | Key.CtrlMask, Command.Paste); // Control-y, yank
  1126. AddKeyBinding (Key.Space | Key.CtrlMask, Command.ToggleExtend);
  1127. AddKeyBinding (((int)'C' + Key.AltMask), Command.Copy);
  1128. AddKeyBinding (Key.C | Key.CtrlMask, Command.Copy);
  1129. AddKeyBinding (((int)'W' + Key.AltMask), Command.Cut);
  1130. AddKeyBinding (Key.W | Key.CtrlMask, Command.Cut);
  1131. AddKeyBinding (Key.X | Key.CtrlMask, Command.Cut);
  1132. AddKeyBinding (Key.CursorLeft | Key.CtrlMask, Command.WordLeft);
  1133. AddKeyBinding ((Key)((int)'B' + Key.AltMask), Command.WordLeft);
  1134. AddKeyBinding (Key.CursorLeft | Key.CtrlMask | Key.ShiftMask, Command.WordLeftExtend);
  1135. AddKeyBinding (Key.CursorRight | Key.CtrlMask, Command.WordRight);
  1136. AddKeyBinding ((Key)((int)'F' + Key.AltMask), Command.WordRight);
  1137. AddKeyBinding (Key.CursorRight | Key.CtrlMask | Key.ShiftMask, Command.WordRightExtend);
  1138. AddKeyBinding (Key.DeleteChar | Key.CtrlMask, Command.KillWordForwards); // kill-word-forwards
  1139. AddKeyBinding (Key.Backspace | Key.CtrlMask, Command.KillWordBackwards); // kill-word-backwards
  1140. AddKeyBinding (Key.Enter, Command.NewLine);
  1141. AddKeyBinding (Key.End | Key.CtrlMask, Command.BottomEnd);
  1142. AddKeyBinding (Key.End | Key.CtrlMask | Key.ShiftMask, Command.BottomEndExtend);
  1143. AddKeyBinding (Key.Home | Key.CtrlMask, Command.TopHome);
  1144. AddKeyBinding (Key.Home | Key.CtrlMask | Key.ShiftMask, Command.TopHomeExtend);
  1145. AddKeyBinding (Key.T | Key.CtrlMask, Command.SelectAll);
  1146. AddKeyBinding (Key.InsertChar, Command.ToggleOverwrite);
  1147. AddKeyBinding (Key.Tab, Command.Tab);
  1148. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.BackTab);
  1149. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextView);
  1150. AddKeyBinding (Application.AlternateForwardKey, Command.NextView);
  1151. AddKeyBinding (Key.Tab | Key.CtrlMask | Key.ShiftMask, Command.PreviousView);
  1152. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousView);
  1153. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Undo);
  1154. AddKeyBinding (Key.R | Key.CtrlMask, Command.Redo);
  1155. }
  1156. private void Model_LinesLoaded ()
  1157. {
  1158. historyText.Clear (Text);
  1159. }
  1160. private void HistoryText_ChangeText (HistoryText.HistoryTextItem obj)
  1161. {
  1162. var startLine = obj.CursorPosition.Y;
  1163. if (obj.RemovedOnAdded != null) {
  1164. int offset;
  1165. if (obj.IsUndoing) {
  1166. offset = Math.Max (obj.RemovedOnAdded.Lines.Count - obj.Lines.Count, 1);
  1167. } else {
  1168. offset = obj.RemovedOnAdded.Lines.Count - 1;
  1169. }
  1170. for (int i = 0; i < offset; i++) {
  1171. if (Lines > obj.RemovedOnAdded.CursorPosition.Y) {
  1172. model.RemoveLine (obj.RemovedOnAdded.CursorPosition.Y);
  1173. } else {
  1174. break;
  1175. }
  1176. }
  1177. }
  1178. for (int i = 0; i < obj.Lines.Count; i++) {
  1179. if (i == 0) {
  1180. model.ReplaceLine (startLine, obj.Lines [i]);
  1181. } else if ((obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Removed)
  1182. || !obj.IsUndoing && obj.LineStatus == HistoryText.LineStatus.Added) {
  1183. model.AddLine (startLine, obj.Lines [i]);
  1184. } else if (Lines > obj.CursorPosition.Y + 1) {
  1185. model.RemoveLine (obj.CursorPosition.Y + 1);
  1186. }
  1187. startLine++;
  1188. }
  1189. CursorPosition = obj.FinalCursorPosition;
  1190. Adjust ();
  1191. }
  1192. void TextView_Initialized (object sender, EventArgs e)
  1193. {
  1194. Autocomplete.HostControl = this;
  1195. Application.Top.AlternateForwardKeyChanged += Top_AlternateForwardKeyChanged;
  1196. Application.Top.AlternateBackwardKeyChanged += Top_AlternateBackwardKeyChanged;
  1197. }
  1198. void Top_AlternateBackwardKeyChanged (Key obj)
  1199. {
  1200. ReplaceKeyBinding (obj, Application.AlternateBackwardKey);
  1201. }
  1202. void Top_AlternateForwardKeyChanged (Key obj)
  1203. {
  1204. ReplaceKeyBinding (obj, Application.AlternateForwardKey);
  1205. }
  1206. /// <summary>
  1207. /// Tracks whether the text view should be considered "used", that is, that the user has moved in the entry,
  1208. /// so new input should be appended at the cursor position, rather than clearing the entry
  1209. /// </summary>
  1210. public bool Used { get; set; }
  1211. void ResetPosition ()
  1212. {
  1213. topRow = leftColumn = currentRow = currentColumn = 0;
  1214. selecting = false;
  1215. shiftSelecting = false;
  1216. ResetCursorVisibility ();
  1217. }
  1218. /// <summary>
  1219. /// Sets or gets the text in the <see cref="TextView"/>.
  1220. /// </summary>
  1221. /// <remarks>
  1222. /// </remarks>
  1223. public override ustring Text {
  1224. get {
  1225. if (wordWrap) {
  1226. return wrapManager.Model.ToString ();
  1227. } else {
  1228. return model.ToString ();
  1229. }
  1230. }
  1231. set {
  1232. ResetPosition ();
  1233. model.LoadString (value);
  1234. if (wordWrap) {
  1235. wrapManager = new WordWrapManager (model);
  1236. model = wrapManager.WrapModel (Frame.Width - 2, out _, out _, out _, out _);
  1237. }
  1238. TextChanged?.Invoke ();
  1239. SetNeedsDisplay ();
  1240. historyText.Clear (Text);
  1241. }
  1242. }
  1243. ///<inheritdoc/>
  1244. public override Rect Frame {
  1245. get => base.Frame;
  1246. set {
  1247. base.Frame = value;
  1248. WrapTextModel ();
  1249. Adjust ();
  1250. }
  1251. }
  1252. void WrapTextModel ()
  1253. {
  1254. if (wordWrap && wrapManager != null) {
  1255. model = wrapManager.WrapModel (Frame.Width - 2,
  1256. out int nRow, out int nCol,
  1257. out int nStartRow, out int nStartCol,
  1258. currentRow, currentColumn,
  1259. selectionStartRow, selectionStartColumn,
  1260. tabWidth);
  1261. currentRow = nRow;
  1262. currentColumn = nCol;
  1263. selectionStartRow = nStartRow;
  1264. selectionStartColumn = nStartCol;
  1265. SetNeedsDisplay ();
  1266. }
  1267. }
  1268. /// <summary>
  1269. /// Gets or sets the top row.
  1270. /// </summary>
  1271. public int TopRow { get => topRow; set => topRow = Math.Max (Math.Min (value, Lines - 1), 0); }
  1272. /// <summary>
  1273. /// Gets or sets the left column.
  1274. /// </summary>
  1275. public int LeftColumn { get => leftColumn; set => leftColumn = Math.Max (Math.Min (value, Maxlength - 1), 0); }
  1276. /// <summary>
  1277. /// Gets the maximum visible length line.
  1278. /// </summary>
  1279. public int Maxlength => model.GetMaxVisibleLine (topRow, topRow + Frame.Height, TabWidth);
  1280. /// <summary>
  1281. /// Gets the number of lines.
  1282. /// </summary>
  1283. public int Lines => model.Count;
  1284. /// <summary>
  1285. /// Sets or gets the current cursor position.
  1286. /// </summary>
  1287. public Point CursorPosition {
  1288. get => new Point (currentColumn, currentRow);
  1289. set {
  1290. var line = model.GetLine (Math.Max (Math.Min (value.Y, model.Count - 1), 0));
  1291. currentColumn = value.X < 0 ? 0 : value.X > line.Count ? line.Count : value.X;
  1292. currentRow = value.Y < 0 ? 0 : value.Y > model.Count - 1
  1293. ? Math.Max (model.Count - 1, 0) : value.Y;
  1294. SetNeedsDisplay ();
  1295. Adjust ();
  1296. }
  1297. }
  1298. /// <summary>
  1299. /// Start column position of the selected text.
  1300. /// </summary>
  1301. public int SelectionStartColumn {
  1302. get => selectionStartColumn;
  1303. set {
  1304. var line = model.GetLine (currentRow);
  1305. selectionStartColumn = value < 0 ? 0 : value > line.Count ? line.Count : value;
  1306. selecting = true;
  1307. SetNeedsDisplay ();
  1308. Adjust ();
  1309. }
  1310. }
  1311. /// <summary>
  1312. /// Start row position of the selected text.
  1313. /// </summary>
  1314. public int SelectionStartRow {
  1315. get => selectionStartRow;
  1316. set {
  1317. selectionStartRow = value < 0 ? 0 : value > model.Count - 1
  1318. ? Math.Max (model.Count - 1, 0) : value;
  1319. selecting = true;
  1320. SetNeedsDisplay ();
  1321. Adjust ();
  1322. }
  1323. }
  1324. /// <summary>
  1325. /// The selected text.
  1326. /// </summary>
  1327. public ustring SelectedText {
  1328. get {
  1329. if (!selecting || (model.Count == 1 && model.GetLine (0).Count == 0)) {
  1330. return ustring.Empty;
  1331. }
  1332. SetWrapModel ();
  1333. var sel = GetRegion ();
  1334. UpdateWrapModel ();
  1335. Adjust ();
  1336. return sel;
  1337. }
  1338. }
  1339. /// <summary>
  1340. /// Length of the selected text.
  1341. /// </summary>
  1342. public int SelectedLength => GetSelectedLength ();
  1343. /// <summary>
  1344. /// Get or sets the selecting.
  1345. /// </summary>
  1346. public bool Selecting {
  1347. get => selecting;
  1348. set => selecting = value;
  1349. }
  1350. /// <summary>
  1351. /// Allows word wrap the to fit the available container width.
  1352. /// </summary>
  1353. public bool WordWrap {
  1354. get => wordWrap;
  1355. set {
  1356. if (value == wordWrap) {
  1357. return;
  1358. }
  1359. if (value && !multiline) {
  1360. return;
  1361. }
  1362. wordWrap = value;
  1363. ResetPosition ();
  1364. if (wordWrap) {
  1365. wrapManager = new WordWrapManager (model);
  1366. model = wrapManager.WrapModel (Math.Max (Frame.Width - 2, 0), out _, out _, out _, out _);
  1367. } else if (!wordWrap && wrapManager != null) {
  1368. model = wrapManager.Model;
  1369. }
  1370. SetNeedsDisplay ();
  1371. }
  1372. }
  1373. /// <summary>
  1374. /// The bottom offset needed to use a horizontal scrollbar or for another reason.
  1375. /// This is only needed with the keyboard navigation.
  1376. /// </summary>
  1377. public int BottomOffset {
  1378. get => bottomOffset;
  1379. set {
  1380. if (currentRow == Lines - 1 && bottomOffset > 0 && value == 0) {
  1381. topRow = Math.Max (topRow - bottomOffset, 0);
  1382. }
  1383. bottomOffset = value;
  1384. Adjust ();
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// The right offset needed to use a vertical scrollbar or for another reason.
  1389. /// This is only needed with the keyboard navigation.
  1390. /// </summary>
  1391. public int RightOffset {
  1392. get => rightOffset;
  1393. set {
  1394. if (currentColumn == GetCurrentLine ().Count && rightOffset > 0 && value == 0) {
  1395. leftColumn = Math.Max (leftColumn - rightOffset, 0);
  1396. }
  1397. rightOffset = value;
  1398. Adjust ();
  1399. }
  1400. }
  1401. /// <summary>
  1402. /// Gets or sets a value indicating whether pressing ENTER in a <see cref="TextView"/>
  1403. /// creates a new line of text in the view or activates the default button for the toplevel.
  1404. /// </summary>
  1405. public bool AllowsReturn {
  1406. get => allowsReturn;
  1407. set {
  1408. allowsReturn = value;
  1409. if (allowsReturn && !multiline) {
  1410. Multiline = true;
  1411. }
  1412. if (!allowsReturn && multiline) {
  1413. Multiline = false;
  1414. AllowsTab = false;
  1415. }
  1416. SetNeedsDisplay ();
  1417. }
  1418. }
  1419. /// <summary>
  1420. /// Gets or sets a value indicating whether pressing the TAB key in a <see cref="TextView"/>
  1421. /// types a TAB character in the view instead of moving the focus to the next view in the tab order.
  1422. /// </summary>
  1423. public bool AllowsTab {
  1424. get => allowsTab;
  1425. set {
  1426. allowsTab = value;
  1427. if (allowsTab && tabWidth == 0) {
  1428. tabWidth = 4;
  1429. }
  1430. if (allowsTab && !multiline) {
  1431. Multiline = true;
  1432. }
  1433. if (!allowsTab && tabWidth > 0) {
  1434. tabWidth = 0;
  1435. }
  1436. SetNeedsDisplay ();
  1437. }
  1438. }
  1439. /// <summary>
  1440. /// Gets or sets a value indicating the number of whitespace when pressing the TAB key.
  1441. /// </summary>
  1442. public int TabWidth {
  1443. get => tabWidth;
  1444. set {
  1445. tabWidth = Math.Max (value, 0);
  1446. if (tabWidth > 0 && !AllowsTab) {
  1447. AllowsTab = true;
  1448. }
  1449. SetNeedsDisplay ();
  1450. }
  1451. }
  1452. Dim savedHeight = null;
  1453. /// <summary>
  1454. /// Gets or sets a value indicating whether this <see cref="TextView"/> is a multiline text view.
  1455. /// </summary>
  1456. public bool Multiline {
  1457. get => multiline;
  1458. set {
  1459. multiline = value;
  1460. if (multiline && !allowsTab) {
  1461. AllowsTab = true;
  1462. }
  1463. if (multiline && !allowsReturn) {
  1464. AllowsReturn = true;
  1465. }
  1466. if (!multiline) {
  1467. AllowsReturn = false;
  1468. AllowsTab = false;
  1469. WordWrap = false;
  1470. currentColumn = 0;
  1471. currentRow = 0;
  1472. savedHeight = Height;
  1473. var lyout = LayoutStyle;
  1474. if (LayoutStyle == LayoutStyle.Computed) {
  1475. LayoutStyle = LayoutStyle.Absolute;
  1476. }
  1477. Height = 1;
  1478. LayoutStyle = lyout;
  1479. Autocomplete.PopupInsideContainer = false;
  1480. SetNeedsDisplay ();
  1481. } else if (multiline && savedHeight != null) {
  1482. var lyout = LayoutStyle;
  1483. if (LayoutStyle == LayoutStyle.Computed) {
  1484. LayoutStyle = LayoutStyle.Absolute;
  1485. }
  1486. Height = savedHeight;
  1487. LayoutStyle = lyout;
  1488. Autocomplete.PopupInsideContainer = true;
  1489. SetNeedsDisplay ();
  1490. }
  1491. }
  1492. }
  1493. /// <summary>
  1494. /// Indicates whatever the text was changed or not.
  1495. /// <see langword="true"/> if the text was changed <see langword="false"/> otherwise.
  1496. /// </summary>
  1497. public bool IsDirty => historyText.IsDirty (Text);
  1498. /// <summary>
  1499. /// Indicates whatever the text has history changes or not.
  1500. /// <see langword="true"/> if the text has history changes <see langword="false"/> otherwise.
  1501. /// </summary>
  1502. public bool HasHistoryChanges => historyText.HasHistoryChanges;
  1503. int GetSelectedLength ()
  1504. {
  1505. return SelectedText.Length;
  1506. }
  1507. CursorVisibility savedCursorVisibility;
  1508. void SaveCursorVisibility ()
  1509. {
  1510. if (desiredCursorVisibility != CursorVisibility.Invisible) {
  1511. if (savedCursorVisibility == 0) {
  1512. savedCursorVisibility = desiredCursorVisibility;
  1513. }
  1514. DesiredCursorVisibility = CursorVisibility.Invisible;
  1515. }
  1516. }
  1517. void ResetCursorVisibility ()
  1518. {
  1519. if (savedCursorVisibility != 0) {
  1520. DesiredCursorVisibility = savedCursorVisibility;
  1521. savedCursorVisibility = 0;
  1522. }
  1523. }
  1524. /// <summary>
  1525. /// Loads the contents of the file into the <see cref="TextView"/>.
  1526. /// </summary>
  1527. /// <returns><c>true</c>, if file was loaded, <c>false</c> otherwise.</returns>
  1528. /// <param name="path">Path to the file to load.</param>
  1529. public bool LoadFile (string path)
  1530. {
  1531. var res = model.LoadFile (path);
  1532. ResetPosition ();
  1533. SetNeedsDisplay ();
  1534. return res;
  1535. }
  1536. /// <summary>
  1537. /// Loads the contents of the stream into the <see cref="TextView"/>.
  1538. /// </summary>
  1539. /// <returns><c>true</c>, if stream was loaded, <c>false</c> otherwise.</returns>
  1540. /// <param name="stream">Stream to load the contents from.</param>
  1541. public void LoadStream (Stream stream)
  1542. {
  1543. model.LoadStream (stream);
  1544. ResetPosition ();
  1545. SetNeedsDisplay ();
  1546. }
  1547. /// <summary>
  1548. /// Closes the contents of the stream into the <see cref="TextView"/>.
  1549. /// </summary>
  1550. /// <returns><c>true</c>, if stream was closed, <c>false</c> otherwise.</returns>
  1551. public bool CloseFile ()
  1552. {
  1553. var res = model.CloseFile ();
  1554. ResetPosition ();
  1555. SetNeedsDisplay ();
  1556. return res;
  1557. }
  1558. /// <summary>
  1559. /// Gets the current cursor row.
  1560. /// </summary>
  1561. public int CurrentRow => currentRow;
  1562. /// <summary>
  1563. /// Gets the cursor column.
  1564. /// </summary>
  1565. /// <value>The cursor column.</value>
  1566. public int CurrentColumn => currentColumn;
  1567. /// <summary>
  1568. /// Positions the cursor on the current row and column
  1569. /// </summary>
  1570. public override void PositionCursor ()
  1571. {
  1572. if (!CanFocus || !Enabled) {
  1573. return;
  1574. }
  1575. if (selecting) {
  1576. var minRow = Math.Min (Math.Max (Math.Min (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1577. var maxRow = Math.Min (Math.Max (Math.Max (selectionStartRow, currentRow) - topRow, 0), Frame.Height);
  1578. SetNeedsDisplay (new Rect (0, minRow, Frame.Width, maxRow));
  1579. }
  1580. var line = model.GetLine (currentRow);
  1581. var col = 0;
  1582. if (line.Count > 0) {
  1583. for (int idx = leftColumn; idx < line.Count; idx++) {
  1584. if (idx >= currentColumn)
  1585. break;
  1586. var cols = Rune.ColumnWidth (line [idx]);
  1587. if (line [idx] == '\t') {
  1588. cols += TabWidth + 1;
  1589. }
  1590. if (!TextModel.SetCol (ref col, Frame.Width, cols)) {
  1591. col = currentColumn;
  1592. break;
  1593. }
  1594. }
  1595. }
  1596. var posX = currentColumn - leftColumn;
  1597. var posY = currentRow - topRow;
  1598. if (posX > -1 && col >= posX && posX < Frame.Width - RightOffset
  1599. && topRow <= currentRow && posY < Frame.Height - BottomOffset) {
  1600. ResetCursorVisibility ();
  1601. Move (col, currentRow - topRow);
  1602. } else {
  1603. SaveCursorVisibility ();
  1604. }
  1605. }
  1606. void ClearRegion (int left, int top, int right, int bottom)
  1607. {
  1608. for (int row = top; row < bottom; row++) {
  1609. Move (left, row);
  1610. for (int col = left; col < right; col++)
  1611. AddRune (col, row, ' ');
  1612. }
  1613. }
  1614. /// <summary>
  1615. /// Sets the driver to the default color for the control where no text is being rendered. Defaults to <see cref="ColorScheme.Normal"/>.
  1616. /// </summary>
  1617. protected virtual void ColorNormal ()
  1618. {
  1619. Driver.SetAttribute (GetNormalColor ());
  1620. }
  1621. /// <summary>
  1622. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1623. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1624. /// Defaults to <see cref="ColorScheme.Normal"/>.
  1625. /// </summary>
  1626. /// <param name="line"></param>
  1627. /// <param name="idx"></param>
  1628. protected virtual void ColorNormal (List<Rune> line, int idx)
  1629. {
  1630. Driver.SetAttribute (GetNormalColor ());
  1631. }
  1632. /// <summary>
  1633. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1634. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1635. /// Defaults to <see cref="ColorScheme.Focus"/>.
  1636. /// </summary>
  1637. /// <param name="line"></param>
  1638. /// <param name="idx"></param>
  1639. protected virtual void ColorSelection (List<Rune> line, int idx)
  1640. {
  1641. Driver.SetAttribute (ColorScheme.Focus);
  1642. }
  1643. /// <summary>
  1644. /// Sets the <see cref="View.Driver"/> to an appropriate color for rendering the given <paramref name="idx"/> of the
  1645. /// current <paramref name="line"/>. Override to provide custom coloring by calling <see cref="ConsoleDriver.SetAttribute(Attribute)"/>
  1646. /// Defaults to <see cref="ColorScheme.HotFocus"/>.
  1647. /// </summary>
  1648. /// <param name="line"></param>
  1649. /// <param name="idx"></param>
  1650. protected virtual void ColorUsed (List<Rune> line, int idx)
  1651. {
  1652. Driver.SetAttribute (ColorScheme.HotFocus);
  1653. }
  1654. bool isReadOnly = false;
  1655. /// <summary>
  1656. /// Gets or sets whether the <see cref="TextView"/> is in read-only mode or not
  1657. /// </summary>
  1658. /// <value>Boolean value(Default false)</value>
  1659. public bool ReadOnly {
  1660. get => isReadOnly;
  1661. set {
  1662. isReadOnly = value;
  1663. SetNeedsDisplay ();
  1664. }
  1665. }
  1666. CursorVisibility desiredCursorVisibility = CursorVisibility.Default;
  1667. /// <summary>
  1668. /// Get / Set the wished cursor when the field is focused
  1669. /// </summary>
  1670. public CursorVisibility DesiredCursorVisibility {
  1671. get => desiredCursorVisibility;
  1672. set {
  1673. if (HasFocus) {
  1674. Application.Driver.SetCursorVisibility (value);
  1675. }
  1676. desiredCursorVisibility = value;
  1677. SetNeedsDisplay ();
  1678. }
  1679. }
  1680. ///<inheritdoc/>
  1681. public override bool OnEnter (View view)
  1682. {
  1683. //TODO: Improve it by handling read only mode of the text field
  1684. Application.Driver.SetCursorVisibility (DesiredCursorVisibility);
  1685. return base.OnEnter (view);
  1686. }
  1687. // Returns an encoded region start..end (top 32 bits are the row, low32 the column)
  1688. void GetEncodedRegionBounds (out long start, out long end)
  1689. {
  1690. long selection = ((long)(uint)selectionStartRow << 32) | (uint)selectionStartColumn;
  1691. long point = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1692. if (selection > point) {
  1693. start = point;
  1694. end = selection;
  1695. } else {
  1696. start = selection;
  1697. end = point;
  1698. }
  1699. }
  1700. bool PointInSelection (int col, int row)
  1701. {
  1702. long start, end;
  1703. GetEncodedRegionBounds (out start, out end);
  1704. var q = ((long)(uint)row << 32) | (uint)col;
  1705. return q >= start && q <= end - 1;
  1706. }
  1707. //
  1708. // Returns a ustring with the text in the selected
  1709. // region.
  1710. //
  1711. ustring GetRegion ()
  1712. {
  1713. long start, end;
  1714. GetEncodedRegionBounds (out start, out end);
  1715. if (start == end) {
  1716. return ustring.Empty;
  1717. }
  1718. int startRow = (int)(start >> 32);
  1719. var maxrow = ((int)(end >> 32));
  1720. int startCol = (int)(start & 0xffffffff);
  1721. var endCol = (int)(end & 0xffffffff);
  1722. var line = model.GetLine (startRow);
  1723. if (startRow == maxrow)
  1724. return StringFromRunes (line.GetRange (startCol, endCol - startCol));
  1725. ustring res = StringFromRunes (line.GetRange (startCol, line.Count - startCol));
  1726. for (int row = startRow + 1; row < maxrow; row++) {
  1727. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (model.GetLine (row));
  1728. }
  1729. line = model.GetLine (maxrow);
  1730. res = res + ustring.Make (Environment.NewLine) + StringFromRunes (line.GetRange (0, endCol));
  1731. return res;
  1732. }
  1733. //
  1734. // Clears the contents of the selected region
  1735. //
  1736. void ClearRegion ()
  1737. {
  1738. long start, end;
  1739. long currentEncoded = ((long)(uint)currentRow << 32) | (uint)currentColumn;
  1740. GetEncodedRegionBounds (out start, out end);
  1741. int startRow = (int)(start >> 32);
  1742. var maxrow = ((int)(end >> 32));
  1743. int startCol = (int)(start & 0xffffffff);
  1744. var endCol = (int)(end & 0xffffffff);
  1745. var line = model.GetLine (startRow);
  1746. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, new Point (startCol, startRow));
  1747. List<List<Rune>> removedLines = new List<List<Rune>> ();
  1748. if (startRow == maxrow) {
  1749. removedLines.Add (new List<Rune> (line));
  1750. line.RemoveRange (startCol, endCol - startCol);
  1751. currentColumn = startCol;
  1752. if (wordWrap) {
  1753. SetNeedsDisplay ();
  1754. } else {
  1755. SetNeedsDisplay (new Rect (0, startRow - topRow, Frame.Width, startRow - topRow + 1));
  1756. }
  1757. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition, HistoryText.LineStatus.Removed);
  1758. return;
  1759. }
  1760. removedLines.Add (new List<Rune> (line));
  1761. line.RemoveRange (startCol, line.Count - startCol);
  1762. var line2 = model.GetLine (maxrow);
  1763. line.AddRange (line2.Skip (endCol));
  1764. for (int row = startRow + 1; row <= maxrow; row++) {
  1765. removedLines.Add (new List<Rune> (model.GetLine (startRow + 1)));
  1766. model.RemoveLine (startRow + 1);
  1767. }
  1768. if (currentEncoded == end) {
  1769. currentRow -= maxrow - (startRow);
  1770. }
  1771. currentColumn = startCol;
  1772. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  1773. HistoryText.LineStatus.Removed);
  1774. SetNeedsDisplay ();
  1775. }
  1776. /// <summary>
  1777. /// Select all text.
  1778. /// </summary>
  1779. public void SelectAll ()
  1780. {
  1781. if (model.Count == 0) {
  1782. return;
  1783. }
  1784. StartSelecting ();
  1785. selectionStartColumn = 0;
  1786. selectionStartRow = 0;
  1787. currentColumn = model.GetLine (model.Count - 1).Count;
  1788. currentRow = model.Count - 1;
  1789. SetNeedsDisplay ();
  1790. }
  1791. /// <summary>
  1792. /// Find the next text based on the match case with the option to replace it.
  1793. /// </summary>
  1794. /// <param name="textToFind">The text to find.</param>
  1795. /// <param name="gaveFullTurn"><c>true</c>If all the text was forward searched.<c>false</c>otherwise.</param>
  1796. /// <param name="matchCase">The match case setting.</param>
  1797. /// <param name="matchWholeWord">The match whole word setting.</param>
  1798. /// <param name="textToReplace">The text to replace.</param>
  1799. /// <param name="replace"><c>true</c>If is replacing.<c>false</c>otherwise.</param>
  1800. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1801. public bool FindNextText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1802. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1803. {
  1804. if (model.Count == 0) {
  1805. gaveFullTurn = false;
  1806. return false;
  1807. }
  1808. SetWrapModel ();
  1809. ResetContinuousFind ();
  1810. var foundPos = model.FindNextText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1811. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1812. }
  1813. /// <summary>
  1814. /// Find the previous text based on the match case with the option to replace it.
  1815. /// </summary>
  1816. /// <param name="textToFind">The text to find.</param>
  1817. /// <param name="gaveFullTurn"><c>true</c>If all the text was backward searched.<c>false</c>otherwise.</param>
  1818. /// <param name="matchCase">The match case setting.</param>
  1819. /// <param name="matchWholeWord">The match whole word setting.</param>
  1820. /// <param name="textToReplace">The text to replace.</param>
  1821. /// <param name="replace"><c>true</c>If the text was found.<c>false</c>otherwise.</param>
  1822. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1823. public bool FindPreviousText (ustring textToFind, out bool gaveFullTurn, bool matchCase = false,
  1824. bool matchWholeWord = false, ustring textToReplace = null, bool replace = false)
  1825. {
  1826. if (model.Count == 0) {
  1827. gaveFullTurn = false;
  1828. return false;
  1829. }
  1830. SetWrapModel ();
  1831. ResetContinuousFind ();
  1832. var foundPos = model.FindPreviousText (textToFind, out gaveFullTurn, matchCase, matchWholeWord);
  1833. return SetFoundText (textToFind, foundPos, textToReplace, replace);
  1834. }
  1835. /// <summary>
  1836. /// Reset the flag to stop continuous find.
  1837. /// </summary>
  1838. public void FindTextChanged ()
  1839. {
  1840. continuousFind = false;
  1841. }
  1842. /// <summary>
  1843. /// Replaces all the text based on the match case.
  1844. /// </summary>
  1845. /// <param name="textToFind">The text to find.</param>
  1846. /// <param name="matchCase">The match case setting.</param>
  1847. /// <param name="matchWholeWord">The match whole word setting.</param>
  1848. /// <param name="textToReplace">The text to replace.</param>
  1849. /// <returns><c>true</c>If the text was found.<c>false</c>otherwise.</returns>
  1850. public bool ReplaceAllText (ustring textToFind, bool matchCase = false, bool matchWholeWord = false,
  1851. ustring textToReplace = null)
  1852. {
  1853. if (isReadOnly || model.Count == 0) {
  1854. return false;
  1855. }
  1856. SetWrapModel ();
  1857. ResetContinuousFind ();
  1858. var foundPos = model.ReplaceAllText (textToFind, matchCase, matchWholeWord, textToReplace);
  1859. return SetFoundText (textToFind, foundPos, textToReplace, false, true);
  1860. }
  1861. bool SetFoundText (ustring text, (Point current, bool found) foundPos,
  1862. ustring textToReplace = null, bool replace = false, bool replaceAll = false)
  1863. {
  1864. if (foundPos.found) {
  1865. StartSelecting ();
  1866. selectionStartColumn = foundPos.current.X;
  1867. selectionStartRow = foundPos.current.Y;
  1868. if (!replaceAll) {
  1869. currentColumn = selectionStartColumn + text.RuneCount;
  1870. } else {
  1871. currentColumn = selectionStartColumn + textToReplace.RuneCount;
  1872. }
  1873. currentRow = foundPos.current.Y;
  1874. if (!isReadOnly && replace) {
  1875. Adjust ();
  1876. ClearSelectedRegion ();
  1877. InsertText (textToReplace);
  1878. StartSelecting ();
  1879. selectionStartColumn = currentColumn - textToReplace.RuneCount;
  1880. } else {
  1881. UpdateWrapModel ();
  1882. SetNeedsDisplay ();
  1883. Adjust ();
  1884. }
  1885. continuousFind = true;
  1886. return foundPos.found;
  1887. }
  1888. UpdateWrapModel ();
  1889. continuousFind = false;
  1890. return foundPos.found;
  1891. }
  1892. void ResetContinuousFind ()
  1893. {
  1894. if (!continuousFind) {
  1895. var col = selecting ? selectionStartColumn : currentColumn;
  1896. var row = selecting ? selectionStartRow : currentRow;
  1897. model.ResetContinuousFind (new Point (col, row));
  1898. }
  1899. }
  1900. /// <summary>
  1901. /// Restore from original model.
  1902. /// </summary>
  1903. void SetWrapModel ()
  1904. {
  1905. if (wordWrap) {
  1906. currentColumn = wrapManager.GetModelColFromWrappedLines (currentRow, currentColumn);
  1907. currentRow = wrapManager.GetModelLineFromWrappedLines (currentRow);
  1908. selectionStartColumn = wrapManager.GetModelColFromWrappedLines (selectionStartRow, selectionStartColumn);
  1909. selectionStartRow = wrapManager.GetModelLineFromWrappedLines (selectionStartRow);
  1910. model = wrapManager.Model;
  1911. }
  1912. }
  1913. /// <summary>
  1914. /// Update the original model.
  1915. /// </summary>
  1916. void UpdateWrapModel ()
  1917. {
  1918. if (wordWrap) {
  1919. wrapManager.UpdateModel (model, out int nRow, out int nCol,
  1920. out int nStartRow, out int nStartCol,
  1921. currentRow, currentColumn,
  1922. selectionStartRow, selectionStartColumn);
  1923. currentRow = nRow;
  1924. currentColumn = nCol;
  1925. selectionStartRow = nStartRow;
  1926. selectionStartColumn = nStartCol;
  1927. wrapNeeded = true;
  1928. }
  1929. }
  1930. ///<inheritdoc/>
  1931. public override void Redraw (Rect bounds)
  1932. {
  1933. ColorNormal ();
  1934. var offB = OffSetBackground ();
  1935. int right = Frame.Width + offB.width + RightOffset;
  1936. int bottom = Frame.Height + offB.height + BottomOffset;
  1937. var row = 0;
  1938. for (int idxRow = topRow; idxRow < model.Count; idxRow++) {
  1939. var line = model.GetLine (idxRow);
  1940. int lineRuneCount = line.Count;
  1941. var col = 0;
  1942. Move (0, row);
  1943. for (int idxCol = leftColumn; idxCol < lineRuneCount; idxCol++) {
  1944. var rune = idxCol >= lineRuneCount ? ' ' : line [idxCol];
  1945. var cols = Rune.ColumnWidth (rune);
  1946. if (idxCol < line.Count && selecting && PointInSelection (idxCol, idxRow)) {
  1947. ColorSelection (line, idxCol);
  1948. } else if (idxCol == currentColumn && idxRow == currentRow && !selecting && !Used
  1949. && HasFocus && idxCol < lineRuneCount) {
  1950. ColorUsed (line, idxCol);
  1951. } else {
  1952. ColorNormal (line, idxCol);
  1953. }
  1954. if (rune == '\t') {
  1955. cols += TabWidth + 1;
  1956. if (col + cols > right) {
  1957. cols = right - col;
  1958. }
  1959. for (int i = 0; i < cols; i++) {
  1960. if (col + i < right) {
  1961. AddRune (col + i, row, ' ');
  1962. }
  1963. }
  1964. } else {
  1965. AddRune (col, row, rune);
  1966. }
  1967. if (!TextModel.SetCol (ref col, bounds.Right, cols)) {
  1968. break;
  1969. }
  1970. if (idxCol + 1 < lineRuneCount && col + Rune.ColumnWidth (line [idxCol + 1]) > right) {
  1971. break;
  1972. }
  1973. }
  1974. if (col < right) {
  1975. ColorNormal ();
  1976. ClearRegion (col, row, right, row + 1);
  1977. }
  1978. row++;
  1979. }
  1980. if (row < bottom) {
  1981. ColorNormal ();
  1982. ClearRegion (bounds.Left, row, right, bottom);
  1983. }
  1984. PositionCursor ();
  1985. if (SelectedLength > 0)
  1986. return;
  1987. // draw autocomplete
  1988. Autocomplete.GenerateSuggestions ();
  1989. var renderAt = new Point (
  1990. CursorPosition.X - LeftColumn,
  1991. Autocomplete.PopupInsideContainer
  1992. ? (CursorPosition.Y + 1) - TopRow
  1993. : 0);
  1994. Autocomplete.RenderOverlay (renderAt);
  1995. }
  1996. ///<inheritdoc/>
  1997. public override bool CanFocus {
  1998. get => base.CanFocus;
  1999. set { base.CanFocus = value; }
  2000. }
  2001. void SetClipboard (ustring text)
  2002. {
  2003. if (text != null) {
  2004. Clipboard.Contents = text;
  2005. }
  2006. }
  2007. void AppendClipboard (ustring text)
  2008. {
  2009. Clipboard.Contents += text;
  2010. }
  2011. /// <summary>
  2012. /// Inserts the given <paramref name="toAdd"/> text at the current cursor position
  2013. /// exactly as if the user had just typed it
  2014. /// </summary>
  2015. /// <param name="toAdd">Text to add</param>
  2016. public void InsertText (string toAdd)
  2017. {
  2018. foreach (var ch in toAdd) {
  2019. Key key;
  2020. try {
  2021. key = (Key)ch;
  2022. } catch (Exception) {
  2023. throw new ArgumentException ($"Cannot insert character '{ch}' because it does not map to a Key");
  2024. }
  2025. InsertText (new KeyEvent () { Key = key });
  2026. }
  2027. }
  2028. void Insert (Rune rune)
  2029. {
  2030. var line = GetCurrentLine ();
  2031. if (Used) {
  2032. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2033. } else {
  2034. if (currentColumn < line.Count) {
  2035. line.RemoveAt (currentColumn);
  2036. }
  2037. line.Insert (Math.Min (currentColumn, line.Count), rune);
  2038. }
  2039. if (wordWrap) {
  2040. if (Used) {
  2041. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  2042. } else {
  2043. wrapNeeded = wrapManager.RemoveAt (currentRow, currentColumn);
  2044. wrapNeeded = wrapManager.Insert (currentRow, currentColumn, rune);
  2045. }
  2046. if (wrapNeeded) {
  2047. SetNeedsDisplay ();
  2048. }
  2049. }
  2050. var prow = currentRow - topRow;
  2051. if (!wrapNeeded) {
  2052. SetNeedsDisplay (new Rect (0, prow, Frame.Width, prow + 1));
  2053. }
  2054. }
  2055. ustring StringFromRunes (List<Rune> runes)
  2056. {
  2057. if (runes == null)
  2058. throw new ArgumentNullException (nameof (runes));
  2059. int size = 0;
  2060. foreach (var rune in runes) {
  2061. size += Utf8.RuneLen (rune);
  2062. }
  2063. var encoded = new byte [size];
  2064. int offset = 0;
  2065. foreach (var rune in runes) {
  2066. offset += Utf8.EncodeRune (rune, encoded, offset);
  2067. }
  2068. return ustring.Make (encoded);
  2069. }
  2070. /// <summary>
  2071. /// Returns the characters on the current line (where the cursor is positioned).
  2072. /// Use <see cref="CurrentColumn"/> to determine the position of the cursor within
  2073. /// that line
  2074. /// </summary>
  2075. /// <returns></returns>
  2076. public List<Rune> GetCurrentLine () => model.GetLine (currentRow);
  2077. void InsertText (ustring text)
  2078. {
  2079. if (ustring.IsNullOrEmpty (text)) {
  2080. return;
  2081. }
  2082. var lines = TextModel.StringToRunes (text);
  2083. if (lines.Count == 0) {
  2084. return;
  2085. }
  2086. var line = GetCurrentLine ();
  2087. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition);
  2088. // Optimize single line
  2089. if (lines.Count == 1) {
  2090. line.InsertRange (currentColumn, lines [0]);
  2091. currentColumn += lines [0].Count;
  2092. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2093. HistoryText.LineStatus.Replaced);
  2094. if (!wordWrap && currentColumn - leftColumn > Frame.Width) {
  2095. leftColumn = Math.Max (currentColumn - Frame.Width + 1, 0);
  2096. }
  2097. if (wordWrap) {
  2098. SetNeedsDisplay ();
  2099. } else {
  2100. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Math.Max (currentRow - topRow + 1, 0)));
  2101. }
  2102. return;
  2103. }
  2104. List<Rune> rest = null;
  2105. int lastp = 0;
  2106. if (model.Count > 0 && line.Count > 0 && !copyWithoutSelection) {
  2107. // Keep a copy of the rest of the line
  2108. var restCount = line.Count - currentColumn;
  2109. rest = line.GetRange (currentColumn, restCount);
  2110. line.RemoveRange (currentColumn, restCount);
  2111. }
  2112. // First line is inserted at the current location, the rest is appended
  2113. line.InsertRange (currentColumn, lines [0]);
  2114. //model.AddLine (currentRow, lines [0]);
  2115. var addedLines = new List<List<Rune>> () { new List<Rune> (line) };
  2116. for (int i = 1; i < lines.Count; i++) {
  2117. model.AddLine (currentRow + i, lines [i]);
  2118. addedLines.Add (new List<Rune> (lines [i]));
  2119. }
  2120. if (rest != null) {
  2121. var last = model.GetLine (currentRow + lines.Count - 1);
  2122. lastp = last.Count;
  2123. last.InsertRange (last.Count, rest);
  2124. addedLines.Last ().InsertRange (addedLines.Last ().Count, rest);
  2125. }
  2126. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2127. // Now adjust column and row positions
  2128. currentRow += lines.Count - 1;
  2129. currentColumn = rest != null ? lastp : lines [lines.Count - 1].Count;
  2130. Adjust ();
  2131. historyText.Add (new List<List<Rune>> () { new List<Rune> (line) }, CursorPosition,
  2132. HistoryText.LineStatus.Replaced);
  2133. }
  2134. // The column we are tracking, or -1 if we are not tracking any column
  2135. int columnTrack = -1;
  2136. // Tries to snap the cursor to the tracking column
  2137. void TrackColumn ()
  2138. {
  2139. // Now track the column
  2140. var line = GetCurrentLine ();
  2141. if (line.Count < columnTrack)
  2142. currentColumn = line.Count;
  2143. else if (columnTrack != -1)
  2144. currentColumn = columnTrack;
  2145. else if (currentColumn > line.Count)
  2146. currentColumn = line.Count;
  2147. Adjust ();
  2148. }
  2149. void Adjust ()
  2150. {
  2151. var offB = OffSetBackground ();
  2152. var line = GetCurrentLine ();
  2153. bool need = !NeedDisplay.IsEmpty || wrapNeeded;
  2154. var tSize = TextModel.DisplaySize (line, -1, -1, false, TabWidth);
  2155. var dSize = TextModel.DisplaySize (line, leftColumn, currentColumn, true, TabWidth);
  2156. if (!wordWrap && currentColumn < leftColumn) {
  2157. leftColumn = currentColumn;
  2158. need = true;
  2159. } else if (!wordWrap && (currentColumn - leftColumn + RightOffset > Frame.Width + offB.width
  2160. || dSize.size + RightOffset >= Frame.Width + offB.width)) {
  2161. leftColumn = TextModel.CalculateLeftColumn (line, leftColumn, currentColumn,
  2162. Frame.Width + offB.width - RightOffset, TabWidth);
  2163. need = true;
  2164. } else if (dSize.size + RightOffset < Frame.Width + offB.width
  2165. && tSize.size + RightOffset < Frame.Width + offB.width) {
  2166. leftColumn = 0;
  2167. need = true;
  2168. }
  2169. if (currentRow < topRow) {
  2170. topRow = currentRow;
  2171. need = true;
  2172. } else if (currentRow - topRow + BottomOffset >= Frame.Height + offB.height) {
  2173. topRow = Math.Min (Math.Max (currentRow - Frame.Height + 1 + BottomOffset, 0), currentRow);
  2174. need = true;
  2175. } else if (topRow > 0 && currentRow == topRow) {
  2176. topRow = Math.Max (topRow - 1, 0);
  2177. }
  2178. if (need) {
  2179. if (wrapNeeded) {
  2180. WrapTextModel ();
  2181. wrapNeeded = false;
  2182. }
  2183. SetNeedsDisplay ();
  2184. } else {
  2185. PositionCursor ();
  2186. }
  2187. }
  2188. (int width, int height) OffSetBackground ()
  2189. {
  2190. int w = 0;
  2191. int h = 0;
  2192. if (SuperView?.Frame.Right - Frame.Right < 0) {
  2193. w = SuperView.Frame.Right - Frame.Right - 1;
  2194. }
  2195. if (SuperView?.Frame.Bottom - Frame.Bottom < 0) {
  2196. h = SuperView.Frame.Bottom - Frame.Bottom - 1;
  2197. }
  2198. return (w, h);
  2199. }
  2200. /// <summary>
  2201. /// Will scroll the <see cref="TextView"/> to display the specified row at the top if <paramref name="isRow"/> is true or
  2202. /// will scroll the <see cref="TextView"/> to display the specified column at the left if <paramref name="isRow"/> is false.
  2203. /// </summary>
  2204. /// <param name="idx">Row that should be displayed at the top or Column that should be displayed at the left,
  2205. /// if the value is negative it will be reset to zero</param>
  2206. /// <param name="isRow">If true (default) the <paramref name="idx"/> is a row, column otherwise.</param>
  2207. public void ScrollTo (int idx, bool isRow = true)
  2208. {
  2209. if (idx < 0) {
  2210. idx = 0;
  2211. }
  2212. if (isRow) {
  2213. topRow = Math.Max (idx > model.Count - 1 ? model.Count - 1 : idx, 0);
  2214. } else if (!wordWrap) {
  2215. var maxlength = model.GetMaxVisibleLine (topRow, topRow + Frame.Height + RightOffset, TabWidth);
  2216. leftColumn = Math.Max (idx > maxlength - 1 ? maxlength - 1 : idx, 0);
  2217. }
  2218. SetNeedsDisplay ();
  2219. }
  2220. bool lastWasKill;
  2221. bool wrapNeeded;
  2222. bool shiftSelecting;
  2223. ///<inheritdoc/>
  2224. public override bool ProcessKey (KeyEvent kb)
  2225. {
  2226. if (!CanFocus) {
  2227. return true;
  2228. }
  2229. // Give autocomplete first opportunity to respond to key presses
  2230. if (SelectedLength == 0 && Autocomplete.ProcessKey (kb)) {
  2231. return true;
  2232. }
  2233. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (kb),
  2234. new KeyModifiers () { Alt = kb.IsAlt, Ctrl = kb.IsCtrl, Shift = kb.IsShift }));
  2235. if (result != null)
  2236. return (bool)result;
  2237. ResetColumnTrack ();
  2238. // Ignore control characters and other special keys
  2239. if (kb.Key < Key.Space || kb.Key > Key.CharMask)
  2240. return false;
  2241. InsertText (kb);
  2242. DoNeededAction ();
  2243. return true;
  2244. }
  2245. void RedoChanges ()
  2246. {
  2247. if (ReadOnly || wordWrap)
  2248. return;
  2249. historyText.Redo ();
  2250. }
  2251. void UndoChanges ()
  2252. {
  2253. if (ReadOnly || wordWrap)
  2254. return;
  2255. historyText.Undo ();
  2256. }
  2257. bool ProcessMovePreviousView ()
  2258. {
  2259. ResetColumnTrack ();
  2260. return MovePreviousView ();
  2261. }
  2262. bool ProcessMoveNextView ()
  2263. {
  2264. ResetColumnTrack ();
  2265. return MoveNextView ();
  2266. }
  2267. void ProcessSetOverwrite ()
  2268. {
  2269. ResetColumnTrack ();
  2270. SetOverwrite (!Used);
  2271. }
  2272. void ProcessSelectAll ()
  2273. {
  2274. ResetColumnTrack ();
  2275. SelectAll ();
  2276. }
  2277. void MoveTopHomeExtend ()
  2278. {
  2279. ResetColumnTrack ();
  2280. StartSelecting ();
  2281. MoveHome ();
  2282. }
  2283. void MoveTopHome ()
  2284. {
  2285. ResetAllTrack ();
  2286. if (shiftSelecting && selecting) {
  2287. StopSelecting ();
  2288. }
  2289. MoveHome ();
  2290. }
  2291. void MoveBottomEndExtend ()
  2292. {
  2293. ResetAllTrack ();
  2294. StartSelecting ();
  2295. MoveEnd ();
  2296. }
  2297. void MoveBottomEnd ()
  2298. {
  2299. ResetAllTrack ();
  2300. if (shiftSelecting && selecting) {
  2301. StopSelecting ();
  2302. }
  2303. MoveEnd ();
  2304. }
  2305. void ProcessKillWordBackward ()
  2306. {
  2307. ResetColumnTrack ();
  2308. KillWordBackward ();
  2309. }
  2310. void ProcessKillWordForward ()
  2311. {
  2312. ResetColumnTrack ();
  2313. KillWordForward ();
  2314. }
  2315. void ProcessMoveWordForwardExtend ()
  2316. {
  2317. ResetAllTrack ();
  2318. StartSelecting ();
  2319. MoveWordForward ();
  2320. }
  2321. void ProcessMoveWordForward ()
  2322. {
  2323. ResetAllTrack ();
  2324. if (shiftSelecting && selecting) {
  2325. StopSelecting ();
  2326. }
  2327. MoveWordForward ();
  2328. }
  2329. void ProcessMoveWordBackwardExtend ()
  2330. {
  2331. ResetAllTrack ();
  2332. StartSelecting ();
  2333. MoveWordBackward ();
  2334. }
  2335. void ProcessMoveWordBackward ()
  2336. {
  2337. ResetAllTrack ();
  2338. if (shiftSelecting && selecting) {
  2339. StopSelecting ();
  2340. }
  2341. MoveWordBackward ();
  2342. }
  2343. void ProcessCut ()
  2344. {
  2345. ResetColumnTrack ();
  2346. Cut ();
  2347. }
  2348. void ProcessCopy ()
  2349. {
  2350. ResetColumnTrack ();
  2351. Copy ();
  2352. }
  2353. void ToggleSelecting ()
  2354. {
  2355. ResetColumnTrack ();
  2356. selecting = !selecting;
  2357. selectionStartColumn = currentColumn;
  2358. selectionStartRow = currentRow;
  2359. }
  2360. void ProcessPaste ()
  2361. {
  2362. ResetColumnTrack ();
  2363. if (isReadOnly)
  2364. return;
  2365. Paste ();
  2366. }
  2367. void ProcessMoveEndOfLineExtend ()
  2368. {
  2369. ResetAllTrack ();
  2370. StartSelecting ();
  2371. MoveEndOfLine ();
  2372. }
  2373. void ProcessMoveEndOfLine ()
  2374. {
  2375. ResetAllTrack ();
  2376. if (shiftSelecting && selecting) {
  2377. StopSelecting ();
  2378. }
  2379. MoveEndOfLine ();
  2380. }
  2381. void ProcessDeleteCharRight ()
  2382. {
  2383. ResetColumnTrack ();
  2384. DeleteCharRight ();
  2385. }
  2386. void ProcessMoveStartOfLineExtend ()
  2387. {
  2388. ResetAllTrack ();
  2389. StartSelecting ();
  2390. MoveStartOfLine ();
  2391. }
  2392. void ProcessMoveStartOfLine ()
  2393. {
  2394. ResetAllTrack ();
  2395. if (shiftSelecting && selecting) {
  2396. StopSelecting ();
  2397. }
  2398. MoveStartOfLine ();
  2399. }
  2400. void ProcessDeleteCharLeft ()
  2401. {
  2402. ResetColumnTrack ();
  2403. DeleteCharLeft ();
  2404. }
  2405. void ProcessMoveLeftExtend ()
  2406. {
  2407. ResetAllTrack ();
  2408. StartSelecting ();
  2409. MoveLeft ();
  2410. }
  2411. bool ProcessMoveLeft ()
  2412. {
  2413. // if the user presses Left (without any control keys) and they are at the start of the text
  2414. if (currentColumn == 0 && currentRow == 0) {
  2415. // do not respond (this lets the key press fall through to navigation system - which usually changes focus backward)
  2416. return false;
  2417. }
  2418. ResetAllTrack ();
  2419. if (shiftSelecting && selecting) {
  2420. StopSelecting ();
  2421. }
  2422. MoveLeft ();
  2423. return true;
  2424. }
  2425. void ProcessMoveRightExtend ()
  2426. {
  2427. ResetAllTrack ();
  2428. StartSelecting ();
  2429. MoveRight ();
  2430. }
  2431. bool ProcessMoveRight ()
  2432. {
  2433. // if the user presses Right (without any control keys)
  2434. // determine where the last cursor position in the text is
  2435. var lastRow = model.Count - 1;
  2436. var lastCol = model.GetLine (lastRow).Count;
  2437. // if they are at the very end of all the text do not respond (this lets the key press fall through to navigation system - which usually changes focus forward)
  2438. if (currentColumn == lastCol && currentRow == lastRow) {
  2439. return false;
  2440. }
  2441. ResetAllTrack ();
  2442. if (shiftSelecting && selecting) {
  2443. StopSelecting ();
  2444. }
  2445. MoveRight ();
  2446. return true;
  2447. }
  2448. void ProcessMoveUpExtend ()
  2449. {
  2450. ResetColumnTrack ();
  2451. StartSelecting ();
  2452. MoveUp ();
  2453. }
  2454. void ProcessMoveUp ()
  2455. {
  2456. ResetContinuousFindTrack ();
  2457. if (shiftSelecting && selecting) {
  2458. StopSelecting ();
  2459. }
  2460. MoveUp ();
  2461. }
  2462. void ProcessMoveDownExtend ()
  2463. {
  2464. ResetColumnTrack ();
  2465. StartSelecting ();
  2466. MoveDown ();
  2467. }
  2468. void ProcessMoveDown ()
  2469. {
  2470. ResetContinuousFindTrack ();
  2471. if (shiftSelecting && selecting) {
  2472. StopSelecting ();
  2473. }
  2474. MoveDown ();
  2475. }
  2476. void ProcessPageUpExtend ()
  2477. {
  2478. ResetColumnTrack ();
  2479. StartSelecting ();
  2480. MovePageUp ();
  2481. }
  2482. void ProcessPageUp ()
  2483. {
  2484. ResetColumnTrack ();
  2485. if (shiftSelecting && selecting) {
  2486. StopSelecting ();
  2487. }
  2488. MovePageUp ();
  2489. }
  2490. void ProcessPageDownExtend ()
  2491. {
  2492. ResetColumnTrack ();
  2493. StartSelecting ();
  2494. MovePageDown ();
  2495. }
  2496. void ProcessPageDown ()
  2497. {
  2498. ResetColumnTrack ();
  2499. if (shiftSelecting && selecting) {
  2500. StopSelecting ();
  2501. }
  2502. MovePageDown ();
  2503. }
  2504. bool MovePreviousView ()
  2505. {
  2506. if (Application.MdiTop != null) {
  2507. return SuperView?.FocusPrev () == true;
  2508. }
  2509. return false;
  2510. }
  2511. bool MoveNextView ()
  2512. {
  2513. if (Application.MdiTop != null) {
  2514. return SuperView?.FocusNext () == true;
  2515. }
  2516. return false;
  2517. }
  2518. bool ProcessBackTab ()
  2519. {
  2520. ResetColumnTrack ();
  2521. if (!AllowsTab) {
  2522. return false;
  2523. }
  2524. if (currentColumn > 0) {
  2525. var currentLine = GetCurrentLine ();
  2526. if (currentLine.Count > 0 && currentLine [currentColumn - 1] == '\t') {
  2527. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2528. currentLine.RemoveAt (currentColumn - 1);
  2529. currentColumn--;
  2530. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2531. HistoryText.LineStatus.Replaced);
  2532. }
  2533. }
  2534. DoNeededAction ();
  2535. return true;
  2536. }
  2537. bool ProcessTab ()
  2538. {
  2539. ResetColumnTrack ();
  2540. if (!AllowsTab) {
  2541. return false;
  2542. }
  2543. InsertText (new KeyEvent ((Key)'\t', null));
  2544. DoNeededAction ();
  2545. return true;
  2546. }
  2547. void SetOverwrite (bool overwrite)
  2548. {
  2549. Used = overwrite;
  2550. SetNeedsDisplay ();
  2551. DoNeededAction ();
  2552. }
  2553. bool ProcessReturn ()
  2554. {
  2555. ResetColumnTrack ();
  2556. if (!AllowsReturn) {
  2557. return false;
  2558. }
  2559. if (isReadOnly)
  2560. return true;
  2561. var currentLine = GetCurrentLine ();
  2562. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2563. if (selecting) {
  2564. ClearSelectedRegion ();
  2565. currentLine = GetCurrentLine ();
  2566. }
  2567. var restCount = currentLine.Count - currentColumn;
  2568. var rest = currentLine.GetRange (currentColumn, restCount);
  2569. currentLine.RemoveRange (currentColumn, restCount);
  2570. var addedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2571. model.AddLine (currentRow + 1, rest);
  2572. addedLines.Add (new List<Rune> (model.GetLine (currentRow + 1)));
  2573. historyText.Add (addedLines, CursorPosition, HistoryText.LineStatus.Added);
  2574. if (wordWrap) {
  2575. wrapManager.AddLine (currentRow, currentColumn);
  2576. wrapNeeded = true;
  2577. }
  2578. currentRow++;
  2579. bool fullNeedsDisplay = false;
  2580. if (currentRow >= topRow + Frame.Height) {
  2581. topRow++;
  2582. fullNeedsDisplay = true;
  2583. }
  2584. currentColumn = 0;
  2585. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2586. HistoryText.LineStatus.Replaced);
  2587. if (!wordWrap && currentColumn < leftColumn) {
  2588. fullNeedsDisplay = true;
  2589. leftColumn = 0;
  2590. }
  2591. if (fullNeedsDisplay)
  2592. SetNeedsDisplay ();
  2593. else
  2594. SetNeedsDisplay (new Rect (0, currentRow - topRow, 2, Frame.Height));
  2595. DoNeededAction ();
  2596. return true;
  2597. }
  2598. void KillWordBackward ()
  2599. {
  2600. if (isReadOnly)
  2601. return;
  2602. var currentLine = GetCurrentLine ();
  2603. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2604. if (currentColumn == 0) {
  2605. DeleteTextBackwards ();
  2606. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2607. HistoryText.LineStatus.Replaced);
  2608. return;
  2609. }
  2610. var newPos = WordBackward (currentColumn, currentRow);
  2611. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2612. var restCount = currentColumn - newPos.Value.col;
  2613. currentLine.RemoveRange (newPos.Value.col, restCount);
  2614. if (wordWrap && wrapManager.RemoveRange (currentRow, newPos.Value.col, restCount)) {
  2615. wrapNeeded = true;
  2616. }
  2617. currentColumn = newPos.Value.col;
  2618. } else if (newPos.HasValue) {
  2619. var restCount = currentLine.Count - currentColumn;
  2620. currentLine.RemoveRange (currentColumn, restCount);
  2621. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2622. wrapNeeded = true;
  2623. }
  2624. currentColumn = newPos.Value.col;
  2625. currentRow = newPos.Value.row;
  2626. }
  2627. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2628. HistoryText.LineStatus.Replaced);
  2629. if (wrapNeeded) {
  2630. SetNeedsDisplay ();
  2631. } else {
  2632. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2633. }
  2634. DoNeededAction ();
  2635. }
  2636. void KillWordForward ()
  2637. {
  2638. if (isReadOnly)
  2639. return;
  2640. var currentLine = GetCurrentLine ();
  2641. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2642. if (currentLine.Count == 0 || currentColumn == currentLine.Count) {
  2643. DeleteTextForwards ();
  2644. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2645. HistoryText.LineStatus.Replaced);
  2646. return;
  2647. }
  2648. var newPos = WordForward (currentColumn, currentRow);
  2649. var restCount = 0;
  2650. if (newPos.HasValue && currentRow == newPos.Value.row) {
  2651. restCount = newPos.Value.col - currentColumn;
  2652. currentLine.RemoveRange (currentColumn, restCount);
  2653. } else if (newPos.HasValue) {
  2654. restCount = currentLine.Count - currentColumn;
  2655. currentLine.RemoveRange (currentColumn, restCount);
  2656. }
  2657. if (wordWrap && wrapManager.RemoveRange (currentRow, currentColumn, restCount)) {
  2658. wrapNeeded = true;
  2659. }
  2660. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2661. HistoryText.LineStatus.Replaced);
  2662. if (wrapNeeded) {
  2663. SetNeedsDisplay ();
  2664. } else {
  2665. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2666. }
  2667. DoNeededAction ();
  2668. }
  2669. void MoveWordForward ()
  2670. {
  2671. var newPos = WordForward (currentColumn, currentRow);
  2672. if (newPos.HasValue) {
  2673. currentColumn = newPos.Value.col;
  2674. currentRow = newPos.Value.row;
  2675. }
  2676. Adjust ();
  2677. DoNeededAction ();
  2678. }
  2679. void MoveWordBackward ()
  2680. {
  2681. var newPos = WordBackward (currentColumn, currentRow);
  2682. if (newPos.HasValue) {
  2683. currentColumn = newPos.Value.col;
  2684. currentRow = newPos.Value.row;
  2685. }
  2686. Adjust ();
  2687. DoNeededAction ();
  2688. }
  2689. void KillToStartOfLine ()
  2690. {
  2691. if (isReadOnly)
  2692. return;
  2693. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2694. // Prevents from adding line feeds if there is no more lines.
  2695. return;
  2696. }
  2697. var currentLine = GetCurrentLine ();
  2698. var setLastWasKill = true;
  2699. if (currentLine.Count > 0 && currentColumn == 0) {
  2700. DeleteTextBackwards ();
  2701. return;
  2702. }
  2703. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2704. if (currentLine.Count == 0) {
  2705. if (currentRow > 0) {
  2706. model.RemoveLine (currentRow);
  2707. if (model.Count > 0 || lastWasKill) {
  2708. var val = ustring.Make (Environment.NewLine);
  2709. if (lastWasKill) {
  2710. AppendClipboard (val);
  2711. } else {
  2712. SetClipboard (val);
  2713. }
  2714. }
  2715. if (model.Count == 0) {
  2716. // Prevents from adding line feeds if there is no more lines.
  2717. setLastWasKill = false;
  2718. }
  2719. currentRow--;
  2720. currentLine = model.GetLine (currentRow);
  2721. var removedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2722. removedLine.Add (new List<Rune> ());
  2723. historyText.Add (new List<List<Rune>> (removedLine), CursorPosition, HistoryText.LineStatus.Removed);
  2724. currentColumn = currentLine.Count;
  2725. }
  2726. } else {
  2727. var restCount = currentColumn;
  2728. var rest = currentLine.GetRange (0, restCount);
  2729. var val = ustring.Empty;
  2730. val += StringFromRunes (rest);
  2731. if (lastWasKill) {
  2732. AppendClipboard (val);
  2733. } else {
  2734. SetClipboard (val);
  2735. }
  2736. currentLine.RemoveRange (0, restCount);
  2737. currentColumn = 0;
  2738. }
  2739. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2740. HistoryText.LineStatus.Replaced);
  2741. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2742. lastWasKill = setLastWasKill;
  2743. DoNeededAction ();
  2744. }
  2745. void KillToEndOfLine ()
  2746. {
  2747. if (isReadOnly)
  2748. return;
  2749. if (model.Count == 1 && GetCurrentLine ().Count == 0) {
  2750. // Prevents from adding line feeds if there is no more lines.
  2751. return;
  2752. }
  2753. var currentLine = GetCurrentLine ();
  2754. var setLastWasKill = true;
  2755. if (currentLine.Count > 0 && currentColumn == currentLine.Count) {
  2756. DeleteTextForwards ();
  2757. return;
  2758. }
  2759. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2760. if (currentLine.Count == 0) {
  2761. if (currentRow < model.Count - 1) {
  2762. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2763. model.RemoveLine (currentRow);
  2764. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  2765. historyText.Add (new List<List<Rune>> (removedLines), CursorPosition,
  2766. HistoryText.LineStatus.Removed);
  2767. }
  2768. if (model.Count > 0 || lastWasKill) {
  2769. var val = ustring.Make (Environment.NewLine);
  2770. if (lastWasKill) {
  2771. AppendClipboard (val);
  2772. } else {
  2773. SetClipboard (val);
  2774. }
  2775. }
  2776. if (model.Count == 0) {
  2777. // Prevents from adding line feeds if there is no more lines.
  2778. setLastWasKill = false;
  2779. }
  2780. } else {
  2781. var restCount = currentLine.Count - currentColumn;
  2782. var rest = currentLine.GetRange (currentColumn, restCount);
  2783. var val = ustring.Empty;
  2784. val += StringFromRunes (rest);
  2785. if (lastWasKill) {
  2786. AppendClipboard (val);
  2787. } else {
  2788. SetClipboard (val);
  2789. }
  2790. currentLine.RemoveRange (currentColumn, restCount);
  2791. }
  2792. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2793. HistoryText.LineStatus.Replaced);
  2794. SetNeedsDisplay (new Rect (0, currentRow - topRow, Frame.Width, Frame.Height));
  2795. lastWasKill = setLastWasKill;
  2796. DoNeededAction ();
  2797. }
  2798. void MoveEndOfLine ()
  2799. {
  2800. var currentLine = GetCurrentLine ();
  2801. currentColumn = currentLine.Count;
  2802. Adjust ();
  2803. DoNeededAction ();
  2804. }
  2805. void MoveStartOfLine ()
  2806. {
  2807. currentColumn = 0;
  2808. leftColumn = 0;
  2809. Adjust ();
  2810. DoNeededAction ();
  2811. }
  2812. /// <summary>
  2813. /// Deletes all the selected or a single character at right from the position of the cursor.
  2814. /// </summary>
  2815. public void DeleteCharRight ()
  2816. {
  2817. if (isReadOnly)
  2818. return;
  2819. if (selecting) {
  2820. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2821. HistoryText.LineStatus.Original);
  2822. ClearSelectedRegion ();
  2823. var currentLine = GetCurrentLine ();
  2824. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2825. HistoryText.LineStatus.Replaced);
  2826. return;
  2827. }
  2828. if (DeleteTextForwards ()) {
  2829. return;
  2830. }
  2831. DoNeededAction ();
  2832. }
  2833. /// <summary>
  2834. /// Deletes all the selected or a single character at left from the position of the cursor.
  2835. /// </summary>
  2836. public void DeleteCharLeft ()
  2837. {
  2838. if (isReadOnly)
  2839. return;
  2840. if (selecting) {
  2841. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2842. HistoryText.LineStatus.Original);
  2843. ClearSelectedRegion ();
  2844. var currentLine = GetCurrentLine ();
  2845. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  2846. HistoryText.LineStatus.Replaced);
  2847. return;
  2848. }
  2849. if (DeleteTextBackwards ()) {
  2850. return;
  2851. }
  2852. DoNeededAction ();
  2853. }
  2854. void MoveLeft ()
  2855. {
  2856. if (currentColumn > 0) {
  2857. currentColumn--;
  2858. } else {
  2859. if (currentRow > 0) {
  2860. currentRow--;
  2861. if (currentRow < topRow) {
  2862. topRow--;
  2863. SetNeedsDisplay ();
  2864. }
  2865. var currentLine = GetCurrentLine ();
  2866. currentColumn = currentLine.Count;
  2867. }
  2868. }
  2869. Adjust ();
  2870. DoNeededAction ();
  2871. }
  2872. void MoveRight ()
  2873. {
  2874. var currentLine = GetCurrentLine ();
  2875. if (currentColumn < currentLine.Count) {
  2876. currentColumn++;
  2877. } else {
  2878. if (currentRow + 1 < model.Count) {
  2879. currentRow++;
  2880. currentColumn = 0;
  2881. if (currentRow >= topRow + Frame.Height) {
  2882. topRow++;
  2883. SetNeedsDisplay ();
  2884. }
  2885. }
  2886. }
  2887. Adjust ();
  2888. DoNeededAction ();
  2889. }
  2890. void MovePageUp ()
  2891. {
  2892. int nPageUpShift = Frame.Height - 1;
  2893. if (currentRow > 0) {
  2894. if (columnTrack == -1)
  2895. columnTrack = currentColumn;
  2896. currentRow = currentRow - nPageUpShift < 0 ? 0 : currentRow - nPageUpShift;
  2897. if (currentRow < topRow) {
  2898. topRow = topRow - nPageUpShift < 0 ? 0 : topRow - nPageUpShift;
  2899. SetNeedsDisplay ();
  2900. }
  2901. TrackColumn ();
  2902. PositionCursor ();
  2903. }
  2904. DoNeededAction ();
  2905. }
  2906. void MovePageDown ()
  2907. {
  2908. int nPageDnShift = Frame.Height - 1;
  2909. if (currentRow >= 0 && currentRow < model.Count) {
  2910. if (columnTrack == -1)
  2911. columnTrack = currentColumn;
  2912. currentRow = (currentRow + nPageDnShift) > model.Count
  2913. ? model.Count > 0 ? model.Count - 1 : 0
  2914. : currentRow + nPageDnShift;
  2915. if (topRow < currentRow - nPageDnShift) {
  2916. topRow = currentRow >= model.Count ? currentRow - nPageDnShift : topRow + nPageDnShift;
  2917. SetNeedsDisplay ();
  2918. }
  2919. TrackColumn ();
  2920. PositionCursor ();
  2921. }
  2922. DoNeededAction ();
  2923. }
  2924. void ResetContinuousFindTrack ()
  2925. {
  2926. // Handle some state here - whether the last command was a kill
  2927. // operation and the column tracking (up/down)
  2928. lastWasKill = false;
  2929. continuousFind = false;
  2930. }
  2931. void ResetColumnTrack ()
  2932. {
  2933. // Handle some state here - whether the last command was a kill
  2934. // operation and the column tracking (up/down)
  2935. lastWasKill = false;
  2936. columnTrack = -1;
  2937. }
  2938. void ResetAllTrack ()
  2939. {
  2940. // Handle some state here - whether the last command was a kill
  2941. // operation and the column tracking (up/down)
  2942. lastWasKill = false;
  2943. columnTrack = -1;
  2944. continuousFind = false;
  2945. }
  2946. bool InsertText (KeyEvent kb)
  2947. {
  2948. //So that special keys like tab can be processed
  2949. if (isReadOnly)
  2950. return true;
  2951. var curPos = CursorPosition;
  2952. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition);
  2953. if (selecting) {
  2954. ClearSelectedRegion ();
  2955. }
  2956. if (Used) {
  2957. Insert ((uint)kb.Key);
  2958. currentColumn++;
  2959. if (currentColumn >= leftColumn + Frame.Width) {
  2960. leftColumn++;
  2961. SetNeedsDisplay ();
  2962. }
  2963. } else {
  2964. Insert ((uint)kb.Key);
  2965. currentColumn++;
  2966. }
  2967. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  2968. HistoryText.LineStatus.Replaced);
  2969. return true;
  2970. }
  2971. ///<inheritdoc/>
  2972. public override bool OnKeyUp (KeyEvent kb)
  2973. {
  2974. switch (kb.Key) {
  2975. case Key.Space | Key.CtrlMask:
  2976. return true;
  2977. }
  2978. return false;
  2979. }
  2980. void DoNeededAction ()
  2981. {
  2982. if (NeedDisplay.IsEmpty) {
  2983. PositionCursor ();
  2984. } else {
  2985. Adjust ();
  2986. }
  2987. }
  2988. bool DeleteTextForwards ()
  2989. {
  2990. var currentLine = GetCurrentLine ();
  2991. if (currentColumn == currentLine.Count) {
  2992. if (currentRow + 1 == model.Count)
  2993. return true;
  2994. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  2995. var removedLines = new List<List<Rune>> () { new List<Rune> (currentLine) };
  2996. var nextLine = model.GetLine (currentRow + 1);
  2997. removedLines.Add (new List<Rune> (nextLine));
  2998. historyText.Add (removedLines, CursorPosition, HistoryText.LineStatus.Removed);
  2999. currentLine.AddRange (nextLine);
  3000. model.RemoveLine (currentRow + 1);
  3001. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3002. HistoryText.LineStatus.Replaced);
  3003. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out _)) {
  3004. wrapNeeded = true;
  3005. }
  3006. var sr = currentRow - topRow;
  3007. SetNeedsDisplay (new Rect (0, sr, Frame.Width, sr + 1));
  3008. } else {
  3009. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3010. currentLine.RemoveAt (currentColumn);
  3011. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3012. HistoryText.LineStatus.Replaced);
  3013. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn)) {
  3014. wrapNeeded = true;
  3015. }
  3016. var r = currentRow - topRow;
  3017. SetNeedsDisplay (new Rect (currentColumn - leftColumn, r, Frame.Width, r + 1));
  3018. }
  3019. return false;
  3020. }
  3021. bool DeleteTextBackwards ()
  3022. {
  3023. if (currentColumn > 0) {
  3024. // Delete backwards
  3025. var currentLine = GetCurrentLine ();
  3026. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3027. currentLine.RemoveAt (currentColumn - 1);
  3028. if (wordWrap && wrapManager.RemoveAt (currentRow, currentColumn - 1)) {
  3029. wrapNeeded = true;
  3030. }
  3031. currentColumn--;
  3032. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition,
  3033. HistoryText.LineStatus.Replaced);
  3034. if (currentColumn < leftColumn) {
  3035. leftColumn--;
  3036. SetNeedsDisplay ();
  3037. } else
  3038. SetNeedsDisplay (new Rect (0, currentRow - topRow, 1, Frame.Width));
  3039. } else {
  3040. // Merges the current line with the previous one.
  3041. if (currentRow == 0)
  3042. return true;
  3043. var prowIdx = currentRow - 1;
  3044. var prevRow = model.GetLine (prowIdx);
  3045. historyText.Add (new List<List<Rune>> () { new List<Rune> (prevRow) }, CursorPosition);
  3046. List<List<Rune>> removedLines = new List<List<Rune>> () { new List<Rune> (prevRow) };
  3047. removedLines.Add (new List<Rune> (GetCurrentLine ()));
  3048. historyText.Add (removedLines, new Point (currentColumn, prowIdx),
  3049. HistoryText.LineStatus.Removed);
  3050. var prevCount = prevRow.Count;
  3051. model.GetLine (prowIdx).AddRange (GetCurrentLine ());
  3052. model.RemoveLine (currentRow);
  3053. bool lineRemoved = false;
  3054. if (wordWrap && wrapManager.RemoveLine (currentRow, currentColumn, out lineRemoved, false)) {
  3055. wrapNeeded = true;
  3056. }
  3057. currentRow--;
  3058. historyText.Add (new List<List<Rune>> () { GetCurrentLine () }, new Point (currentColumn, prowIdx),
  3059. HistoryText.LineStatus.Replaced);
  3060. if (wrapNeeded && !lineRemoved) {
  3061. currentColumn = Math.Max (prevCount - 1, 0);
  3062. } else {
  3063. currentColumn = prevCount;
  3064. }
  3065. SetNeedsDisplay ();
  3066. }
  3067. return false;
  3068. }
  3069. bool copyWithoutSelection;
  3070. /// <summary>
  3071. /// Copy the selected text to the clipboard contents.
  3072. /// </summary>
  3073. public void Copy ()
  3074. {
  3075. SetWrapModel ();
  3076. if (selecting) {
  3077. SetClipboard (GetRegion ());
  3078. copyWithoutSelection = false;
  3079. } else {
  3080. var currentLine = GetCurrentLine ();
  3081. SetClipboard (ustring.Make (currentLine));
  3082. copyWithoutSelection = true;
  3083. }
  3084. UpdateWrapModel ();
  3085. DoNeededAction ();
  3086. }
  3087. /// <summary>
  3088. /// Cut the selected text to the clipboard contents.
  3089. /// </summary>
  3090. public void Cut ()
  3091. {
  3092. SetWrapModel ();
  3093. SetClipboard (GetRegion ());
  3094. if (!isReadOnly) {
  3095. ClearRegion ();
  3096. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3097. HistoryText.LineStatus.Replaced);
  3098. }
  3099. UpdateWrapModel ();
  3100. selecting = false;
  3101. DoNeededAction ();
  3102. }
  3103. /// <summary>
  3104. /// Paste the clipboard contents into the current selected position.
  3105. /// </summary>
  3106. public void Paste ()
  3107. {
  3108. if (isReadOnly) {
  3109. return;
  3110. }
  3111. SetWrapModel ();
  3112. var contents = Clipboard.Contents;
  3113. if (copyWithoutSelection && contents.FirstOrDefault (x => x == '\n' || x == '\r') == 0) {
  3114. var runeList = contents == null ? new List<Rune> () : contents.ToRuneList ();
  3115. var currentLine = GetCurrentLine ();
  3116. historyText.Add (new List<List<Rune>> () { new List<Rune> (currentLine) }, CursorPosition);
  3117. var addedLine = new List<List<Rune>> () { new List<Rune> (currentLine) };
  3118. addedLine.Add (runeList);
  3119. historyText.Add (new List<List<Rune>> (addedLine), CursorPosition, HistoryText.LineStatus.Added);
  3120. model.AddLine (currentRow, runeList);
  3121. currentRow++;
  3122. historyText.Add (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3123. HistoryText.LineStatus.Replaced);
  3124. } else {
  3125. if (selecting) {
  3126. ClearRegion ();
  3127. }
  3128. copyWithoutSelection = false;
  3129. InsertText (contents);
  3130. if (selecting) {
  3131. historyText.ReplaceLast (new List<List<Rune>> () { new List<Rune> (GetCurrentLine ()) }, CursorPosition,
  3132. HistoryText.LineStatus.Original);
  3133. }
  3134. }
  3135. UpdateWrapModel ();
  3136. selecting = false;
  3137. DoNeededAction ();
  3138. }
  3139. void StartSelecting ()
  3140. {
  3141. if (shiftSelecting && selecting) {
  3142. return;
  3143. }
  3144. shiftSelecting = true;
  3145. selecting = true;
  3146. selectionStartColumn = currentColumn;
  3147. selectionStartRow = currentRow;
  3148. }
  3149. void StopSelecting ()
  3150. {
  3151. shiftSelecting = false;
  3152. selecting = false;
  3153. }
  3154. void ClearSelectedRegion ()
  3155. {
  3156. SetWrapModel ();
  3157. if (!isReadOnly) {
  3158. ClearRegion ();
  3159. }
  3160. UpdateWrapModel ();
  3161. selecting = false;
  3162. DoNeededAction ();
  3163. }
  3164. void MoveUp ()
  3165. {
  3166. if (currentRow > 0) {
  3167. if (columnTrack == -1) {
  3168. columnTrack = currentColumn;
  3169. }
  3170. currentRow--;
  3171. if (currentRow < topRow) {
  3172. topRow--;
  3173. SetNeedsDisplay ();
  3174. }
  3175. TrackColumn ();
  3176. PositionCursor ();
  3177. }
  3178. DoNeededAction ();
  3179. }
  3180. void MoveDown ()
  3181. {
  3182. if (currentRow + 1 < model.Count) {
  3183. if (columnTrack == -1) {
  3184. columnTrack = currentColumn;
  3185. }
  3186. currentRow++;
  3187. if (currentRow + BottomOffset >= topRow + Frame.Height) {
  3188. topRow++;
  3189. SetNeedsDisplay ();
  3190. }
  3191. TrackColumn ();
  3192. PositionCursor ();
  3193. } else if (currentRow > Frame.Height) {
  3194. Adjust ();
  3195. }
  3196. DoNeededAction ();
  3197. }
  3198. IEnumerable<(int col, int row, Rune rune)> ForwardIterator (int col, int row)
  3199. {
  3200. if (col < 0 || row < 0)
  3201. yield break;
  3202. if (row >= model.Count)
  3203. yield break;
  3204. var line = GetCurrentLine ();
  3205. if (col >= line.Count)
  3206. yield break;
  3207. while (row < model.Count) {
  3208. for (int c = col; c < line.Count; c++) {
  3209. yield return (c, row, line [c]);
  3210. }
  3211. col = 0;
  3212. row++;
  3213. line = GetCurrentLine ();
  3214. }
  3215. }
  3216. Rune RuneAt (int col, int row)
  3217. {
  3218. var line = model.GetLine (row);
  3219. if (line.Count > 0) {
  3220. return line [col > line.Count - 1 ? line.Count - 1 : col];
  3221. } else {
  3222. return 0;
  3223. }
  3224. }
  3225. /// <summary>
  3226. /// Will scroll the <see cref="TextView"/> to the last line and position the cursor there.
  3227. /// </summary>
  3228. public void MoveEnd ()
  3229. {
  3230. currentRow = model.Count - 1;
  3231. var line = GetCurrentLine ();
  3232. currentColumn = line.Count;
  3233. TrackColumn ();
  3234. PositionCursor ();
  3235. }
  3236. /// <summary>
  3237. /// Will scroll the <see cref="TextView"/> to the first line and position the cursor there.
  3238. /// </summary>
  3239. public void MoveHome ()
  3240. {
  3241. currentRow = 0;
  3242. topRow = 0;
  3243. currentColumn = 0;
  3244. leftColumn = 0;
  3245. TrackColumn ();
  3246. PositionCursor ();
  3247. }
  3248. bool MoveNext (ref int col, ref int row, out Rune rune)
  3249. {
  3250. var line = model.GetLine (row);
  3251. if (col + 1 < line.Count) {
  3252. col++;
  3253. rune = line [col];
  3254. if (col + 1 == line.Count && !Rune.IsLetterOrDigit (rune)
  3255. && !Rune.IsWhiteSpace (line [col - 1])) {
  3256. col++;
  3257. }
  3258. return true;
  3259. } else if (col + 1 == line.Count) {
  3260. col++;
  3261. }
  3262. while (row + 1 < model.Count) {
  3263. col = 0;
  3264. row++;
  3265. line = model.GetLine (row);
  3266. if (line.Count > 0) {
  3267. rune = line [0];
  3268. return true;
  3269. }
  3270. }
  3271. rune = 0;
  3272. return false;
  3273. }
  3274. bool MovePrev (ref int col, ref int row, out Rune rune)
  3275. {
  3276. var line = model.GetLine (row);
  3277. if (col > 0) {
  3278. col--;
  3279. rune = line [col];
  3280. return true;
  3281. }
  3282. if (row == 0) {
  3283. rune = 0;
  3284. return false;
  3285. }
  3286. while (row > 0) {
  3287. row--;
  3288. line = model.GetLine (row);
  3289. col = line.Count - 1;
  3290. if (col >= 0) {
  3291. rune = line [col];
  3292. return true;
  3293. }
  3294. }
  3295. rune = 0;
  3296. return false;
  3297. }
  3298. (int col, int row)? WordForward (int fromCol, int fromRow)
  3299. {
  3300. var col = fromCol;
  3301. var row = fromRow;
  3302. try {
  3303. var rune = RuneAt (col, row);
  3304. void ProcMoveNext (ref int nCol, ref int nRow, Rune nRune)
  3305. {
  3306. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3307. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3308. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))
  3309. return;
  3310. }
  3311. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3312. return;
  3313. }
  3314. while (MoveNext (ref nCol, ref nRow, out nRune)) {
  3315. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3316. break;
  3317. }
  3318. } else {
  3319. if (!MoveNext (ref nCol, ref nRow, out nRune)) {
  3320. return;
  3321. }
  3322. var line = model.GetLine (fromRow);
  3323. if ((nRow != fromRow && fromCol < line.Count)
  3324. || (nRow == fromRow && nCol == line.Count - 1)) {
  3325. nCol = line.Count;
  3326. nRow = fromRow;
  3327. return;
  3328. } else if (nRow != fromRow && fromCol == line.Count) {
  3329. line = model.GetLine (nRow);
  3330. if (Rune.IsLetterOrDigit (line [nCol]) || Rune.IsPunctuation (line [nCol])) {
  3331. return;
  3332. }
  3333. }
  3334. ProcMoveNext (ref nCol, ref nRow, nRune);
  3335. }
  3336. }
  3337. ProcMoveNext (ref col, ref row, rune);
  3338. if (fromCol != col || fromRow != row)
  3339. return (col, row);
  3340. return null;
  3341. } catch (Exception) {
  3342. return null;
  3343. }
  3344. }
  3345. (int col, int row)? WordBackward (int fromCol, int fromRow)
  3346. {
  3347. if (fromRow == 0 && fromCol == 0)
  3348. return null;
  3349. var col = Math.Max (fromCol - 1, 0);
  3350. var row = fromRow;
  3351. try {
  3352. var rune = RuneAt (col, row);
  3353. int lastValidCol = Rune.IsLetterOrDigit (rune) || Rune.IsPunctuation (rune) ? col : -1;
  3354. void ProcMovePrev (ref int nCol, ref int nRow, Rune nRune)
  3355. {
  3356. if (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune)) {
  3357. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3358. if (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune)) {
  3359. lastValidCol = nCol;
  3360. break;
  3361. }
  3362. }
  3363. if (nRow != fromRow && (Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune))) {
  3364. if (lastValidCol > -1) {
  3365. nCol = lastValidCol;
  3366. }
  3367. return;
  3368. }
  3369. while (MovePrev (ref nCol, ref nRow, out nRune)) {
  3370. if (!Rune.IsLetterOrDigit (nRune) && !Rune.IsPunctuation (nRune))
  3371. break;
  3372. if (nRow != fromRow) {
  3373. break;
  3374. }
  3375. lastValidCol = nCol;
  3376. }
  3377. if (lastValidCol > -1) {
  3378. nCol = lastValidCol;
  3379. nRow = fromRow;
  3380. }
  3381. } else {
  3382. if (!MovePrev (ref nCol, ref nRow, out nRune)) {
  3383. return;
  3384. }
  3385. var line = model.GetLine (nRow);
  3386. if (nCol == 0 && nRow == fromRow && (Rune.IsLetterOrDigit (line [0]) || Rune.IsPunctuation (line [0]))) {
  3387. return;
  3388. }
  3389. lastValidCol = Rune.IsLetterOrDigit (nRune) || Rune.IsPunctuation (nRune) ? nCol : lastValidCol;
  3390. if (lastValidCol > -1 && (Rune.IsSymbol (nRune) || Rune.IsWhiteSpace (nRune))) {
  3391. nCol = lastValidCol;
  3392. return;
  3393. }
  3394. if (fromRow != nRow) {
  3395. nCol = line.Count;
  3396. return;
  3397. }
  3398. ProcMovePrev (ref nCol, ref nRow, nRune);
  3399. }
  3400. }
  3401. ProcMovePrev (ref col, ref row, rune);
  3402. if (fromCol != col || fromRow != row)
  3403. return (col, row);
  3404. return null;
  3405. } catch (Exception) {
  3406. return null;
  3407. }
  3408. }
  3409. ///<inheritdoc/>
  3410. public override bool MouseEvent (MouseEvent ev)
  3411. {
  3412. if (!ev.Flags.HasFlag (MouseFlags.Button1Clicked) && !ev.Flags.HasFlag (MouseFlags.Button1Pressed)
  3413. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)
  3414. && !ev.Flags.HasFlag (MouseFlags.Button1Released)
  3415. && !ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)
  3416. && !ev.Flags.HasFlag (MouseFlags.WheeledDown) && !ev.Flags.HasFlag (MouseFlags.WheeledUp)
  3417. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)
  3418. && !ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked | MouseFlags.ButtonShift)
  3419. && !ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3420. return false;
  3421. }
  3422. if (!CanFocus) {
  3423. return true;
  3424. }
  3425. if (!HasFocus) {
  3426. SetFocus ();
  3427. }
  3428. continuousFind = false;
  3429. // Give autocomplete first opportunity to respond to mouse clicks
  3430. if (SelectedLength == 0 && Autocomplete.MouseEvent (ev, true)) {
  3431. return true;
  3432. }
  3433. if (ev.Flags == MouseFlags.Button1Clicked) {
  3434. if (shiftSelecting) {
  3435. shiftSelecting = false;
  3436. selecting = false;
  3437. }
  3438. ProcessMouseClick (ev, out _);
  3439. PositionCursor ();
  3440. lastWasKill = false;
  3441. columnTrack = currentColumn;
  3442. } else if (ev.Flags == MouseFlags.WheeledDown) {
  3443. lastWasKill = false;
  3444. columnTrack = currentColumn;
  3445. ScrollTo (topRow + 1);
  3446. } else if (ev.Flags == MouseFlags.WheeledUp) {
  3447. lastWasKill = false;
  3448. columnTrack = currentColumn;
  3449. ScrollTo (topRow - 1);
  3450. } else if (ev.Flags == MouseFlags.WheeledRight) {
  3451. lastWasKill = false;
  3452. columnTrack = currentColumn;
  3453. ScrollTo (leftColumn + 1, false);
  3454. } else if (ev.Flags == MouseFlags.WheeledLeft) {
  3455. lastWasKill = false;
  3456. columnTrack = currentColumn;
  3457. ScrollTo (leftColumn - 1, false);
  3458. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition)) {
  3459. ProcessMouseClick (ev, out List<Rune> line);
  3460. PositionCursor ();
  3461. if (model.Count > 0 && shiftSelecting && selecting) {
  3462. if (currentRow - topRow + BottomOffset >= Frame.Height - 1
  3463. && model.Count + BottomOffset > topRow + currentRow) {
  3464. ScrollTo (topRow + Frame.Height);
  3465. } else if (topRow > 0 && currentRow <= topRow) {
  3466. ScrollTo (topRow - Frame.Height);
  3467. } else if (ev.Y >= Frame.Height) {
  3468. ScrollTo (model.Count + BottomOffset);
  3469. } else if (ev.Y < 0 && topRow > 0) {
  3470. ScrollTo (0);
  3471. }
  3472. if (currentColumn - leftColumn + RightOffset >= Frame.Width - 1
  3473. && line.Count + RightOffset > leftColumn + currentColumn) {
  3474. ScrollTo (leftColumn + Frame.Width, false);
  3475. } else if (leftColumn > 0 && currentColumn <= leftColumn) {
  3476. ScrollTo (leftColumn - Frame.Width, false);
  3477. } else if (ev.X >= Frame.Width) {
  3478. ScrollTo (line.Count + RightOffset, false);
  3479. } else if (ev.X < 0 && leftColumn > 0) {
  3480. ScrollTo (0, false);
  3481. }
  3482. }
  3483. lastWasKill = false;
  3484. columnTrack = currentColumn;
  3485. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed | MouseFlags.ButtonShift)) {
  3486. if (!shiftSelecting) {
  3487. StartSelecting ();
  3488. }
  3489. ProcessMouseClick (ev, out _);
  3490. PositionCursor ();
  3491. lastWasKill = false;
  3492. columnTrack = currentColumn;
  3493. } else if (ev.Flags.HasFlag (MouseFlags.Button1Pressed)) {
  3494. if (shiftSelecting) {
  3495. shiftSelecting = false;
  3496. selecting = false;
  3497. }
  3498. ProcessMouseClick (ev, out _);
  3499. PositionCursor ();
  3500. if (!selecting) {
  3501. StartSelecting ();
  3502. }
  3503. lastWasKill = false;
  3504. columnTrack = currentColumn;
  3505. if (Application.mouseGrabView == null) {
  3506. Application.GrabMouse (this);
  3507. }
  3508. } else if (ev.Flags.HasFlag (MouseFlags.Button1Released)) {
  3509. Application.UngrabMouse ();
  3510. } else if (ev.Flags.HasFlag (MouseFlags.Button1DoubleClicked)) {
  3511. if (ev.Flags.HasFlag (MouseFlags.ButtonShift)) {
  3512. if (!selecting) {
  3513. StartSelecting ();
  3514. }
  3515. } else if (selecting) {
  3516. StopSelecting ();
  3517. }
  3518. ProcessMouseClick (ev, out List<Rune> line);
  3519. (int col, int row)? newPos;
  3520. if (currentColumn == line.Count || (currentColumn > 0 && (line [currentColumn - 1] != ' '
  3521. || line [currentColumn] == ' '))) {
  3522. newPos = WordBackward (currentColumn, currentRow);
  3523. if (newPos.HasValue) {
  3524. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : 0;
  3525. }
  3526. }
  3527. if (!selecting) {
  3528. StartSelecting ();
  3529. }
  3530. newPos = WordForward (currentColumn, currentRow);
  3531. if (newPos != null && newPos.HasValue) {
  3532. currentColumn = currentRow == newPos.Value.row ? newPos.Value.col : line.Count;
  3533. }
  3534. PositionCursor ();
  3535. lastWasKill = false;
  3536. columnTrack = currentColumn;
  3537. } else if (ev.Flags.HasFlag (MouseFlags.Button1TripleClicked)) {
  3538. if (selecting) {
  3539. StopSelecting ();
  3540. }
  3541. ProcessMouseClick (ev, out List<Rune> line);
  3542. currentColumn = 0;
  3543. if (!selecting) {
  3544. StartSelecting ();
  3545. }
  3546. currentColumn = line.Count;
  3547. PositionCursor ();
  3548. lastWasKill = false;
  3549. columnTrack = currentColumn;
  3550. }
  3551. return true;
  3552. }
  3553. void ProcessMouseClick (MouseEvent ev, out List<Rune> line)
  3554. {
  3555. List<Rune> r = null;
  3556. if (model.Count > 0) {
  3557. var maxCursorPositionableLine = Math.Max ((model.Count - 1) - topRow, 0);
  3558. if (Math.Max (ev.Y, 0) > maxCursorPositionableLine) {
  3559. currentRow = maxCursorPositionableLine + topRow;
  3560. } else {
  3561. currentRow = Math.Max (ev.Y + topRow, 0);
  3562. }
  3563. r = GetCurrentLine ();
  3564. var idx = TextModel.GetColFromX (r, leftColumn, Math.Max (ev.X, 0), TabWidth);
  3565. if (idx - leftColumn >= r.Count + RightOffset) {
  3566. currentColumn = Math.Max (r.Count - leftColumn + RightOffset, 0);
  3567. } else {
  3568. currentColumn = idx + leftColumn;
  3569. }
  3570. }
  3571. line = r;
  3572. }
  3573. ///<inheritdoc/>
  3574. public override bool OnLeave (View view)
  3575. {
  3576. if (Application.mouseGrabView != null && Application.mouseGrabView == this) {
  3577. Application.UngrabMouse ();
  3578. }
  3579. return base.OnLeave (view);
  3580. }
  3581. /// <summary>
  3582. /// Allows clearing the <see cref="HistoryText.HistoryTextItem"/> items updating the original text.
  3583. /// </summary>
  3584. public void ClearHistoryChanges ()
  3585. {
  3586. historyText.Clear (Text);
  3587. }
  3588. }
  3589. /// <summary>
  3590. /// Renders an overlay on another view at a given point that allows selecting
  3591. /// from a range of 'autocomplete' options.
  3592. /// An implementation on a TextView.
  3593. /// </summary>
  3594. public class TextViewAutocomplete : Autocomplete {
  3595. ///<inheritdoc/>
  3596. protected override string GetCurrentWord ()
  3597. {
  3598. var host = (TextView)HostControl;
  3599. var currentLine = host.GetCurrentLine ();
  3600. var cursorPosition = Math.Min (host.CurrentColumn, currentLine.Count);
  3601. return IdxToWord (currentLine, cursorPosition);
  3602. }
  3603. /// <inheritdoc/>
  3604. protected override void DeleteTextBackwards ()
  3605. {
  3606. ((TextView)HostControl).DeleteCharLeft ();
  3607. }
  3608. /// <inheritdoc/>
  3609. protected override void InsertText (string accepted)
  3610. {
  3611. ((TextView)HostControl).InsertText (accepted);
  3612. }
  3613. }
  3614. }