TextView.cs 118 KB

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