TextView.cs 141 KB

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