TextView.cs 117 KB

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