TextView.cs 126 KB

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