TextView.cs 123 KB

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