TextView.cs 135 KB

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