bim.c 228 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. *
  3. * Copyright (C) 2012-2019 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. * bim - Text editor
  18. *
  19. * Bim is inspired by vim, and its name is short for "Bad IMitation".
  20. *
  21. * Bim supports syntax highlighting, extensive editing, line selection
  22. * and copy-paste, undo/redo stack, forward and backward search, and can
  23. * be built for ToaruOS, Sortix, Linux, macOS, and BSDs.
  24. */
  25. #define _XOPEN_SOURCE
  26. #define _DEFAULT_SOURCE
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <termios.h>
  34. #include <signal.h>
  35. #include <locale.h>
  36. #include <wchar.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <poll.h>
  40. #include <limits.h>
  41. #include <sys/types.h>
  42. #include <sys/ioctl.h>
  43. #include <sys/stat.h>
  44. #define BIM_VERSION "1.5.2"
  45. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  46. #define BLOCK_SIZE 4096
  47. #define ENTER_KEY '\r'
  48. #define LINE_FEED '\n'
  49. #define BACKSPACE_KEY 0x08
  50. #define DELETE_KEY 0x7F
  51. /**
  52. * Theming data
  53. *
  54. * This is all overridden by a load_colorscheme_ method.
  55. * The default is to load_colorscheme_ansi, but config
  56. * files can be used to set a different default theme.
  57. */
  58. const char * COLOR_FG = "@17";
  59. const char * COLOR_BG = "@0";
  60. const char * COLOR_ALT_FG = "@17";
  61. const char * COLOR_ALT_BG = "@0";
  62. const char * COLOR_NUMBER_FG = "@17";
  63. const char * COLOR_NUMBER_BG = "@0";
  64. const char * COLOR_STATUS_FG = "@17";
  65. const char * COLOR_STATUS_BG = "@0";
  66. const char * COLOR_TABBAR_BG = "@0";
  67. const char * COLOR_TAB_BG = "@0";
  68. const char * COLOR_ERROR_FG = "@17";
  69. const char * COLOR_ERROR_BG = "@0";
  70. const char * COLOR_SEARCH_FG = "@17";
  71. const char * COLOR_SEARCH_BG = "@0";
  72. const char * COLOR_KEYWORD = "@17";
  73. const char * COLOR_STRING = "@17";
  74. const char * COLOR_COMMENT = "@17";
  75. const char * COLOR_TYPE = "@17";
  76. const char * COLOR_PRAGMA = "@17";
  77. const char * COLOR_NUMERAL = "@17";
  78. const char * COLOR_SELECTFG = "@0";
  79. const char * COLOR_SELECTBG = "@17";
  80. const char * COLOR_RED = "@1";
  81. const char * COLOR_GREEN = "@2";
  82. const char * COLOR_BOLD = "@17";
  83. const char * COLOR_LINK = "@17";
  84. const char * COLOR_ESCAPE = "@17";
  85. const char * current_theme = "none";
  86. /**
  87. * Syntax highlighting flags.
  88. */
  89. #define FLAG_NONE 0
  90. #define FLAG_KEYWORD 1
  91. #define FLAG_STRING 2
  92. #define FLAG_COMMENT 3
  93. #define FLAG_TYPE 4
  94. #define FLAG_PRAGMA 5
  95. #define FLAG_NUMERAL 6
  96. #define FLAG_STRING2 7
  97. #define FLAG_DIFFPLUS 8
  98. #define FLAG_DIFFMINUS 9
  99. #define FLAG_NOTICE 10
  100. #define FLAG_BOLD 11
  101. #define FLAG_LINK 12
  102. #define FLAG_ESCAPE 13
  103. #define FLAG_SELECT (1 << 5)
  104. #define FLAG_SEARCH (1 << 6)
  105. /**
  106. * Convert syntax hilighting flag to color code
  107. */
  108. const char * flag_to_color(int _flag) {
  109. int flag = _flag & 0xF;
  110. switch (flag) {
  111. case FLAG_KEYWORD:
  112. return COLOR_KEYWORD;
  113. case FLAG_STRING:
  114. case FLAG_STRING2: /* allows python to differentiate " and ' */
  115. return COLOR_STRING;
  116. case FLAG_COMMENT:
  117. return COLOR_COMMENT;
  118. case FLAG_TYPE:
  119. return COLOR_TYPE;
  120. case FLAG_NUMERAL:
  121. return COLOR_NUMERAL;
  122. case FLAG_PRAGMA:
  123. return COLOR_PRAGMA;
  124. case FLAG_DIFFPLUS:
  125. return COLOR_GREEN;
  126. case FLAG_DIFFMINUS:
  127. return COLOR_RED;
  128. case FLAG_SELECT:
  129. return COLOR_FG;
  130. case FLAG_BOLD:
  131. return COLOR_BOLD;
  132. case FLAG_LINK:
  133. return COLOR_LINK;
  134. case FLAG_ESCAPE:
  135. return COLOR_ESCAPE;
  136. default:
  137. return COLOR_FG;
  138. }
  139. }
  140. /**
  141. * Line buffer definitions
  142. *
  143. * Lines are essentially resizable vectors of char_t structs,
  144. * which represent single codepoints in the file.
  145. */
  146. typedef struct {
  147. uint32_t display_width:4;
  148. uint32_t flags:7;
  149. uint32_t codepoint:21;
  150. } __attribute__((packed)) char_t;
  151. /**
  152. * Lines have available and actual lengths, describing
  153. * how much space was allocated vs. how much is being
  154. * used at the moment.
  155. */
  156. typedef struct {
  157. int available;
  158. int actual;
  159. int istate;
  160. int is_current;
  161. int rev_status;
  162. char_t text[];
  163. } line_t;
  164. /**
  165. * Global configuration state
  166. */
  167. struct {
  168. /* Terminal size */
  169. int term_width, term_height;
  170. int bottom_size;
  171. line_t ** yanks;
  172. size_t yank_count;
  173. int yank_is_full_lines;
  174. int tty_in;
  175. const char * bimrc_path;
  176. unsigned int hilight_on_open:1;
  177. unsigned int initial_file_is_read_only:1;
  178. unsigned int can_scroll:1;
  179. unsigned int can_hideshow:1;
  180. unsigned int can_altscreen:1;
  181. unsigned int can_mouse:1;
  182. unsigned int can_unicode:1;
  183. unsigned int can_bright:1;
  184. unsigned int can_title:1;
  185. unsigned int can_bce:1;
  186. unsigned int history_enabled:1;
  187. unsigned int highlight_parens:1;
  188. unsigned int smart_case:1;
  189. unsigned int can_24bit:1;
  190. unsigned int can_256color:1;
  191. unsigned int can_italic:1;
  192. unsigned int go_to_line:1;
  193. unsigned int hilight_current_line:1;
  194. unsigned int shift_scrolling:1;
  195. unsigned int check_git:1;
  196. unsigned int color_gutter:1;
  197. int cursor_padding;
  198. int split_percent;
  199. int scroll_amount;
  200. } global_config = {
  201. 0, /* term_width */
  202. 0, /* term_height */
  203. 2, /* bottom_size */
  204. NULL, /* yanks */
  205. 0, /* yank_count */
  206. 0, /* yank is full lines */
  207. STDIN_FILENO, /* tty_in */
  208. "~/.bimrc", /* bimrc_path */
  209. 1, /* hilight_on_open */
  210. 0, /* initial_file_is_read_only */
  211. 1, /* can scroll */
  212. 1, /* can hide/show cursor */
  213. 1, /* can use alternate screen */
  214. 1, /* can mouse */
  215. 1, /* can unicode */
  216. 1, /* can use bright colors */
  217. 1, /* can set title */
  218. 1, /* can bce */
  219. 1, /* history enabled */
  220. 1, /* highlight parens/braces when cursor moves */
  221. 1, /* smart case */
  222. 1, /* can use 24-bit color */
  223. 1, /* can use 265 colors */
  224. 1, /* can use italics (without inverting) */
  225. 1, /* should go to line when opening file */
  226. 1, /* hilight the current line */
  227. 1, /* shift scrolling (shifts view rather than moving cursor) */
  228. 0, /* check git on open and on save */
  229. 1, /* color the gutter for modified lines */
  230. 4, /* cursor padding */
  231. 50, /* split percentage */
  232. 5, /* how many lines to scroll on mouse wheel */
  233. };
  234. void redraw_line(int j, int x);
  235. int git_examine(char * filename);
  236. void search_next(void);
  237. void set_preferred_column(void);
  238. /**
  239. * Special implementation of getch with a timeout
  240. */
  241. int _bim_unget = -1;
  242. void bim_unget(int c) {
  243. _bim_unget = c;
  244. }
  245. #define bim_getch() bim_getch_timeout(200)
  246. int bim_getch_timeout(int timeout) {
  247. if (_bim_unget != -1) {
  248. int out = _bim_unget;
  249. _bim_unget = -1;
  250. return out;
  251. }
  252. struct pollfd fds[1];
  253. fds[0].fd = global_config.tty_in;
  254. fds[0].events = POLLIN;
  255. int ret = poll(fds,1,timeout);
  256. if (ret > 0 && fds[0].revents & POLLIN) {
  257. unsigned char buf[1];
  258. read(global_config.tty_in, buf, 1);
  259. return buf[0];
  260. } else {
  261. return -1;
  262. }
  263. }
  264. #define HISTORY_SENTINEL 0
  265. #define HISTORY_INSERT 1
  266. #define HISTORY_DELETE 2
  267. #define HISTORY_REPLACE 3
  268. #define HISTORY_REMOVE_LINE 4
  269. #define HISTORY_ADD_LINE 5
  270. #define HISTORY_REPLACE_LINE 6
  271. #define HISTORY_MERGE_LINES 7
  272. #define HISTORY_SPLIT_LINE 8
  273. #define HISTORY_BREAK 10
  274. typedef struct history {
  275. struct history * previous;
  276. struct history * next;
  277. int type;
  278. union {
  279. struct {
  280. int lineno;
  281. int offset;
  282. int codepoint;
  283. int old_codepoint;
  284. } insert_delete_replace;
  285. struct {
  286. int lineno;
  287. line_t * contents;
  288. line_t * old_contents;
  289. } remove_replace_line;
  290. struct {
  291. int lineno;
  292. int split;
  293. } add_merge_split_lines;
  294. } contents;
  295. } history_t;
  296. /**
  297. * Buffer data
  298. *
  299. * A buffer describes a file, and stores
  300. * its name as well as the editor state
  301. * (cursor offsets, etc.) and the actual
  302. * line buffers.
  303. */
  304. typedef struct _env {
  305. unsigned short loading:1;
  306. unsigned short tabs:1;
  307. unsigned short modified:1;
  308. unsigned short readonly:1;
  309. unsigned short indent:1;
  310. unsigned short highlighting_paren:1;
  311. unsigned short checkgitstatusonwrite:1;
  312. short mode;
  313. short tabstop;
  314. char * file_name;
  315. int offset;
  316. int coffset;
  317. int line_no;
  318. int line_count;
  319. int line_avail;
  320. int col_no;
  321. int preferred_column;
  322. uint32_t * search;
  323. struct syntax_definition * syntax;
  324. line_t ** lines;
  325. history_t * history;
  326. history_t * last_save_history;
  327. int width;
  328. int left;
  329. int start_line;
  330. int sel_col;
  331. } buffer_t;
  332. /**
  333. * Pointer to current active buffer
  334. */
  335. buffer_t * env;
  336. buffer_t * left_buffer;
  337. buffer_t * right_buffer;
  338. /**
  339. * Editor modes (like in vim)
  340. */
  341. #define MODE_NORMAL 0
  342. #define MODE_INSERT 1
  343. #define MODE_LINE_SELECTION 2
  344. #define MODE_REPLACE 3
  345. #define MODE_CHAR_SELECTION 4
  346. #define MODE_COL_SELECTION 5
  347. #define MODE_COL_INSERT 6
  348. /**
  349. * Available buffers
  350. */
  351. int buffers_len;
  352. int buffers_avail;
  353. buffer_t ** buffers;
  354. /**
  355. * Create a new buffer
  356. */
  357. buffer_t * buffer_new(void) {
  358. if (buffers_len == buffers_avail) {
  359. /* If we are out of buffer space, expand the buffers vector */
  360. buffers_avail *= 2;
  361. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  362. }
  363. /* TODO: Support having split buffers with more than two buffers open */
  364. if (left_buffer) {
  365. left_buffer->left = 0;
  366. left_buffer->width = global_config.term_width;
  367. right_buffer->left = 0;
  368. right_buffer->width = global_config.term_width;
  369. left_buffer = NULL;
  370. right_buffer = NULL;
  371. }
  372. /* Allocate a new buffer */
  373. buffers[buffers_len] = malloc(sizeof(buffer_t));
  374. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  375. buffers[buffers_len]->left = 0;
  376. buffers[buffers_len]->width = global_config.term_width;
  377. buffers_len++;
  378. return buffers[buffers_len-1];
  379. }
  380. /**
  381. * Open the biminfo file.
  382. */
  383. FILE * open_biminfo(void) {
  384. /* TODO This should probably be configurable line bimrc */
  385. char * home = getenv("HOME");
  386. if (!home) {
  387. /* Since it's not, we need HOME */
  388. return NULL;
  389. }
  390. /* biminfo lives at ~/.biminfo */
  391. char biminfo_path[PATH_MAX+1] = {0};
  392. sprintf(biminfo_path,"%s/.biminfo",home);
  393. /* Try to open normally first... */
  394. FILE * biminfo = fopen(biminfo_path,"r+");
  395. if (!biminfo) {
  396. /* Otherwise, try to create it. */
  397. biminfo = fopen(biminfo_path,"w+");
  398. }
  399. return biminfo;
  400. }
  401. /**
  402. * Fetch the cursor position from a biminfo file
  403. */
  404. int fetch_from_biminfo(buffer_t * buf) {
  405. /* Can't fetch if we don't have a filename */
  406. if (!buf->file_name) return 1;
  407. /* Get the absolute name of the file */
  408. char tmp_path[PATH_MAX+2];
  409. if (!realpath(buf->file_name, tmp_path)) {
  410. return 1;
  411. }
  412. strcat(tmp_path," ");
  413. FILE * biminfo = open_biminfo();
  414. if (!biminfo) return 1;
  415. /* Scan */
  416. char line[PATH_MAX+64];
  417. while (!feof(biminfo)) {
  418. fpos_t start_of_line;
  419. fgetpos(biminfo, &start_of_line);
  420. fgets(line, PATH_MAX+63, biminfo);
  421. if (line[0] != '>') {
  422. continue;
  423. }
  424. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  425. /* Read */
  426. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  427. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  428. return 0;
  429. }
  430. }
  431. return 0;
  432. }
  433. /**
  434. * Write a file containing the last cursor position of a buffer.
  435. */
  436. int update_biminfo(buffer_t * buf) {
  437. if (!buf->file_name) return 1;
  438. /* Get the absolute name of the file */
  439. char tmp_path[PATH_MAX+1];
  440. if (!realpath(buf->file_name, tmp_path)) {
  441. return 1;
  442. }
  443. strcat(tmp_path," ");
  444. FILE * biminfo = open_biminfo();
  445. if (!biminfo) return 1;
  446. /* Scan */
  447. char line[PATH_MAX+64];
  448. while (!feof(biminfo)) {
  449. fpos_t start_of_line;
  450. fgetpos(biminfo, &start_of_line);
  451. fgets(line, PATH_MAX+63, biminfo);
  452. if (line[0] != '>') {
  453. continue;
  454. }
  455. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  456. /* Update */
  457. fsetpos(biminfo, &start_of_line);
  458. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  459. goto _done;
  460. }
  461. }
  462. if (ftell(biminfo) == 0) {
  463. /* New biminfo */
  464. fprintf(biminfo, "# This is a biminfo file.\n");
  465. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  466. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  467. }
  468. /* Haven't found what we're looking for, should be at end of file */
  469. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  470. _done:
  471. fclose(biminfo);
  472. return 0;
  473. }
  474. /**
  475. * Close a buffer
  476. */
  477. buffer_t * buffer_close(buffer_t * buf) {
  478. int i;
  479. /* Locate the buffer in the buffer pointer vector */
  480. for (i = 0; i < buffers_len; i++) {
  481. if (buf == buffers[i])
  482. break;
  483. }
  484. /* Invalid buffer? */
  485. if (i == buffers_len) {
  486. return env; /* wtf */
  487. }
  488. update_biminfo(buf);
  489. /* Clean up lines used by old buffer */
  490. for (int i = 0; i < buf->line_count; ++i) {
  491. free(buf->lines[i]);
  492. }
  493. free(buf->lines);
  494. if (buf->search) {
  495. free(buf->search);
  496. }
  497. if (buf->file_name) {
  498. free(buf->file_name);
  499. }
  500. history_t * h = buf->history;
  501. while (h->next) {
  502. h = h->next;
  503. }
  504. while (h) {
  505. history_t * x = h->previous;
  506. free(h);
  507. h = x;
  508. }
  509. /* Clean up the old buffer */
  510. free(buf);
  511. /* Remove the buffer from the vector, moving others up */
  512. if (i != buffers_len - 1) {
  513. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  514. }
  515. /* There is one less buffer */
  516. buffers_len--;
  517. if (!buffers_len) {
  518. /* There are no more buffers. */
  519. return NULL;
  520. }
  521. /* If this was the last buffer, return the previous last buffer */
  522. if (i == buffers_len) {
  523. return buffers[buffers_len-1];
  524. }
  525. /* Otherwise return the new last buffer */
  526. return buffers[i];
  527. }
  528. /**
  529. * Themes
  530. */
  531. /* 16-color theme, default */
  532. void load_colorscheme_ansi(void) {
  533. COLOR_FG = global_config.can_bright ? "@17" : "@7";
  534. COLOR_BG = global_config.can_bright ? "@9" : "@0";
  535. COLOR_ALT_FG = global_config.can_bright ? "@10" : "@5";
  536. COLOR_ALT_BG = "@9";
  537. COLOR_NUMBER_FG = "@3";
  538. COLOR_NUMBER_BG = "@9";
  539. COLOR_STATUS_FG = global_config.can_bright ? "@17" : "@7";
  540. COLOR_STATUS_BG = "@4";
  541. COLOR_TABBAR_BG = "@4";
  542. COLOR_TAB_BG = "@4";
  543. COLOR_KEYWORD = global_config.can_bright ? "@14" : "@4";
  544. COLOR_STRING = "@2";
  545. COLOR_COMMENT = global_config.can_bright ? "@10" : "@5";
  546. COLOR_TYPE = "@3";
  547. COLOR_PRAGMA = "@1";
  548. COLOR_NUMERAL = "@1";
  549. COLOR_ERROR_FG = global_config.can_bright ? "@17" : "@7";
  550. COLOR_ERROR_BG = "@1";
  551. COLOR_SEARCH_FG = "@0";
  552. COLOR_SEARCH_BG = global_config.can_bright ? "@13" : "@3";
  553. COLOR_SELECTBG = global_config.can_bright ? "@17" : "@7";
  554. COLOR_SELECTFG = "@0";
  555. COLOR_RED = "@1";
  556. COLOR_GREEN = "@2";
  557. COLOR_BOLD = COLOR_FG; /* @ doesn't support extra args; FIXME */
  558. COLOR_LINK = global_config.can_bright ? "@14" : "@4";
  559. COLOR_ESCAPE = global_config.can_bright ? "@12" : "@2";
  560. current_theme = "ansi";
  561. }
  562. /* Based on the wombat256 theme for vim */
  563. void load_colorscheme_wombat(void) {
  564. if (!global_config.can_256color) return;
  565. COLOR_FG = "5;230";
  566. COLOR_BG = "5;235";
  567. COLOR_ALT_FG = "5;244";
  568. COLOR_ALT_BG = "5;236";
  569. COLOR_NUMBER_BG = "5;232";
  570. COLOR_NUMBER_FG = "5;101";
  571. COLOR_STATUS_FG = "5;230";
  572. COLOR_STATUS_BG = "5;238";
  573. COLOR_TABBAR_BG = "5;230";
  574. COLOR_TAB_BG = "5;248";
  575. COLOR_KEYWORD = "5;117";
  576. COLOR_STRING = "5;113";
  577. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  578. COLOR_TYPE = "5;186";
  579. COLOR_PRAGMA = "5;173";
  580. COLOR_NUMERAL = COLOR_PRAGMA;
  581. COLOR_ERROR_FG = "5;15";
  582. COLOR_ERROR_BG = "5;196";
  583. COLOR_SEARCH_FG = "5;234";
  584. COLOR_SEARCH_BG = "5;226";
  585. COLOR_SELECTFG = "5;235";
  586. COLOR_SELECTBG = "5;230";
  587. COLOR_RED = "@1";
  588. COLOR_GREEN = "@2";
  589. COLOR_BOLD = "5;230;1";
  590. COLOR_LINK = "5;117;4";
  591. COLOR_ESCAPE = "5;194";
  592. current_theme = "wombat";
  593. }
  594. /* "City Lights" based on citylights.xyz */
  595. void load_colorscheme_citylights(void) {
  596. if (!global_config.can_24bit) return;
  597. COLOR_FG = "2;151;178;198";
  598. COLOR_BG = "2;29;37;44";
  599. COLOR_ALT_FG = "2;45;55;65";
  600. COLOR_ALT_BG = "2;33;42;50";
  601. COLOR_NUMBER_FG = "2;71;89;103";
  602. COLOR_NUMBER_BG = "2;37;47;56";
  603. COLOR_STATUS_FG = "2;116;144;166";
  604. COLOR_STATUS_BG = "2;53;67;78";
  605. COLOR_TABBAR_BG = "2;37;47;56";
  606. COLOR_TAB_BG = "2;29;37;44";
  607. COLOR_KEYWORD = "2;94;196;255";
  608. COLOR_STRING = "2;83;154;252";
  609. COLOR_COMMENT = "2;107;133;153;3";
  610. COLOR_TYPE = "2;139;212;156";
  611. COLOR_PRAGMA = "2;0;139;148";
  612. COLOR_NUMERAL = "2;207;118;132";
  613. COLOR_ERROR_FG = "5;15";
  614. COLOR_ERROR_BG = "5;196";
  615. COLOR_SEARCH_FG = "5;234";
  616. COLOR_SEARCH_BG = "5;226";
  617. COLOR_SELECTFG = "2;29;37;44";
  618. COLOR_SELECTBG = "2;151;178;198";
  619. COLOR_RED = "2;222;53;53";
  620. COLOR_GREEN = "2;55;167;0";
  621. COLOR_BOLD = "2;151;178;198;1";
  622. COLOR_LINK = "2;94;196;255;4";
  623. COLOR_ESCAPE = "2;133;182;249";
  624. current_theme = "citylights";
  625. }
  626. /* Solarized Dark, popular theme */
  627. void load_colorscheme_solarized_dark(void) {
  628. if (!global_config.can_24bit) return;
  629. COLOR_FG = "2;147;161;161";
  630. COLOR_BG = "2;0;43;54";
  631. COLOR_ALT_FG = "2;147;161;161";
  632. COLOR_ALT_BG = "2;7;54;66";
  633. COLOR_NUMBER_FG = "2;131;148;149";
  634. COLOR_NUMBER_BG = "2;7;54;66";
  635. COLOR_STATUS_FG = "2;131;148;150";
  636. COLOR_STATUS_BG = "2;7;54;66";
  637. COLOR_TABBAR_BG = "2;7;54;66";
  638. COLOR_TAB_BG = "2;131;148;150";
  639. COLOR_KEYWORD = "2;133;153;0";
  640. COLOR_STRING = "2;42;161;152";
  641. COLOR_COMMENT = "2;101;123;131";
  642. COLOR_TYPE = "2;181;137;0";
  643. COLOR_PRAGMA = "2;203;75;22";
  644. COLOR_NUMERAL = "2;220;50;47";
  645. COLOR_ERROR_FG = "5;15";
  646. COLOR_ERROR_BG = "5;196";
  647. COLOR_SEARCH_FG = "5;234";
  648. COLOR_SEARCH_BG = "5;226";
  649. COLOR_SELECTFG = "2;0;43;54";
  650. COLOR_SELECTBG = "2;147;161;161";
  651. COLOR_RED = "2;222;53;53";
  652. COLOR_GREEN = "2;55;167;0";
  653. COLOR_BOLD = "2;147;161;161;1";
  654. COLOR_LINK = "2;42;161;152;4";
  655. COLOR_ESCAPE = "2;133;153;0";
  656. current_theme = "solarized-dark";
  657. }
  658. void load_colorscheme_sunsmoke256(void) {
  659. if (!global_config.can_256color) return;
  660. COLOR_FG = "5;188";
  661. COLOR_BG = "5;234";
  662. COLOR_ALT_FG = "5;244";
  663. COLOR_ALT_BG = "5;236";
  664. COLOR_NUMBER_FG = "5;101";
  665. COLOR_NUMBER_BG = "5;232";
  666. COLOR_STATUS_FG = "5;188";
  667. COLOR_STATUS_BG = "5;59";
  668. COLOR_TABBAR_BG = "5;59";
  669. COLOR_TAB_BG = "5;59";
  670. COLOR_KEYWORD = "5;74";
  671. COLOR_STRING = "5;71";
  672. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  673. COLOR_TYPE = "5;221";
  674. COLOR_PRAGMA = "5;160";
  675. COLOR_NUMERAL = "5;161";
  676. COLOR_ERROR_FG = "5;15";
  677. COLOR_ERROR_BG = "5;196";
  678. COLOR_SEARCH_FG = "5;234";
  679. COLOR_SEARCH_BG = "5;226";
  680. COLOR_SELECTFG = "5;17";
  681. COLOR_SELECTBG = "5;109";
  682. COLOR_RED = "@1";
  683. COLOR_GREEN = "@2";
  684. COLOR_BOLD = "5;188;1";
  685. COLOR_LINK = "5;74;4";
  686. COLOR_ESCAPE = "5;79";
  687. current_theme = "sunsmoke256";
  688. }
  689. /* Custom theme */
  690. void load_colorscheme_sunsmoke(void) {
  691. if (!global_config.can_24bit) {
  692. load_colorscheme_sunsmoke256();
  693. return;
  694. }
  695. COLOR_FG = "2;230;230;230";
  696. COLOR_BG = "2;31;31;31";
  697. COLOR_ALT_FG = "2;122;122;122";
  698. COLOR_ALT_BG = "2;46;43;46";
  699. COLOR_NUMBER_FG = "2;150;139;57";
  700. COLOR_NUMBER_BG = "2;0;0;0";
  701. COLOR_STATUS_FG = "2;230;230;230";
  702. COLOR_STATUS_BG = "2;71;64;58";
  703. COLOR_TABBAR_BG = "2;71;64;58";
  704. COLOR_TAB_BG = "2;71;64;58";
  705. COLOR_KEYWORD = "2;51;162;230";
  706. COLOR_STRING = "2;72;176;72";
  707. COLOR_COMMENT = "2;158;153;129;3";
  708. COLOR_TYPE = "2;230;206;110";
  709. COLOR_PRAGMA = "2;194;70;54";
  710. COLOR_NUMERAL = "2;230;43;127";
  711. COLOR_ERROR_FG = "5;15";
  712. COLOR_ERROR_BG = "5;196";
  713. COLOR_SEARCH_FG = "5;234";
  714. COLOR_SEARCH_BG = "5;226";
  715. COLOR_SELECTFG = "2;0;43;54";
  716. COLOR_SELECTBG = "2;147;161;161";
  717. COLOR_RED = "2;222;53;53";
  718. COLOR_GREEN = "2;55;167;0";
  719. COLOR_BOLD = "2;230;230;230;1";
  720. COLOR_LINK = "2;51;162;230;4";
  721. COLOR_ESCAPE = "2;113;203;173";
  722. current_theme = "sunsmoke";
  723. }
  724. struct theme_def {
  725. const char * name;
  726. void (*load)(void);
  727. } themes[] = {
  728. {"wombat", load_colorscheme_wombat},
  729. {"citylights", load_colorscheme_citylights},
  730. {"solarized-dark", load_colorscheme_solarized_dark},
  731. {"ansi", load_colorscheme_ansi},
  732. {"sunsmoke", load_colorscheme_sunsmoke},
  733. {"sunsmoke256", load_colorscheme_sunsmoke256},
  734. {NULL, NULL}
  735. };
  736. struct syntax_state {
  737. line_t * line;
  738. int line_no;
  739. int state;
  740. int i;
  741. };
  742. #define paint(length, flag) do { for (int i = 0; i < (length) && state->i < state->line->actual; i++, state->i++) { state->line->text[state->i].flags = (flag); } } while (0)
  743. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  744. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  745. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  746. #define skip() (state->i++)
  747. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  748. /**
  749. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  750. * Returns 1 if a keyword from the last was found, otherwise 0.
  751. */
  752. static int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  753. if (keyword_qualifier(lastchar())) return 0;
  754. if (!keyword_qualifier(charat())) return 0;
  755. for (char ** keyword = keywords; *keyword; ++keyword) {
  756. int d = 0;
  757. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  758. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  759. paint((int)strlen(*keyword), flag);
  760. return 1;
  761. }
  762. }
  763. return 0;
  764. }
  765. /**
  766. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  767. * so it can be used for prefix checking for things that need further special handling.
  768. */
  769. static int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  770. if (keyword_qualifier(lastchar())) return 0;
  771. if (!keyword_qualifier(charat())) return 0;
  772. int i = state->i;
  773. int slen = 0;
  774. while (i < state->line->actual || *keyword == '\0') {
  775. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  776. for (int j = 0; j < slen; ++j) {
  777. paint(1, flag);
  778. }
  779. return 1;
  780. }
  781. if (*keyword != state->line->text[i].codepoint) return 0;
  782. i++;
  783. keyword++;
  784. slen++;
  785. }
  786. return 0;
  787. }
  788. /**
  789. * Syntax definition for C
  790. */
  791. static char * syn_c_keywords[] = {
  792. "while","if","for","continue","return","break","switch","case","sizeof",
  793. "struct","union","typedef","do","default","else","goto",
  794. "alignas","alignof","offsetof","asm","__asm__",
  795. /* C++ stuff */
  796. "public","private","class","using","namespace","virtual","override","protected",
  797. "template","typename","static_cast","throw",
  798. NULL
  799. };
  800. static char * syn_c_types[] = {
  801. "static","int","char","short","float","double","void","unsigned","volatile","const",
  802. "register","long","inline","restrict","enum","auto","extern","bool","complex",
  803. "uint8_t","uint16_t","uint32_t","uint64_t",
  804. "int8_t","int16_t","int32_t","int64_t","FILE",
  805. "ssize_t","size_t","uintptr_t","intptr_t","__volatile__",
  806. "constexpr",
  807. NULL
  808. };
  809. static char * syn_c_special[] = {
  810. "NULL",
  811. "stdin","stdout","stderr",
  812. "STDIN_FILENO","STDOUT_FILENO","STDERR_FILENO",
  813. NULL
  814. };
  815. static int c_keyword_qualifier(int c) {
  816. return isalnum(c) || (c == '_');
  817. }
  818. /**
  819. * Paints a basic C-style quoted string.
  820. */
  821. static void paint_c_string(struct syntax_state * state) {
  822. /* Assumes you came in from a check of charat() == '"' */
  823. paint(1, FLAG_STRING);
  824. int last = -1;
  825. while (charat() != -1) {
  826. if (last != '\\' && charat() == '"') {
  827. paint(1, FLAG_STRING);
  828. return;
  829. } else if (charat() == '\\' && (nextchar() == '\\' || nextchar() == 'n' || nextchar() == 'r')) {
  830. paint(2, FLAG_ESCAPE);
  831. last = -1;
  832. } else if (charat() == '\\' && nextchar() >= '0' && nextchar() <= '7') {
  833. paint(2, FLAG_ESCAPE);
  834. if (charat() >= '0' && charat() <= '7') {
  835. paint(1, FLAG_ESCAPE);
  836. if (charat() >= '0' && charat() <= '7') {
  837. paint(1, FLAG_ESCAPE);
  838. }
  839. }
  840. last = -1;
  841. } else if (charat() == '\\' && nextchar() == 'x') {
  842. paint(2, FLAG_ESCAPE);
  843. while (isxdigit(charat())) paint(1, FLAG_ESCAPE);
  844. } else {
  845. last = charat();
  846. paint(1, FLAG_STRING);
  847. }
  848. }
  849. }
  850. static void paint_simple_string(struct syntax_state * state) {
  851. /* Assumes you came in from a check of charat() == '"' */
  852. paint(1, FLAG_STRING);
  853. int last = -1;
  854. while (charat() != -1) {
  855. if (last != '\\' && charat() == '"') {
  856. paint(1, FLAG_STRING);
  857. return;
  858. } else if (last == '\\' && charat() == '\\') {
  859. paint(1, FLAG_STRING);
  860. last = -1;
  861. } else {
  862. last = charat();
  863. paint(1, FLAG_STRING);
  864. }
  865. }
  866. }
  867. /**
  868. * Paint a C character numeral. Can be arbitrarily large, so
  869. * it supports multibyte chars for things like defining weird
  870. * ASCII multibyte integer constants.
  871. */
  872. static void paint_c_char(struct syntax_state * state) {
  873. /* Assumes you came in from a check of charat() == '\'' */
  874. paint(1, FLAG_NUMERAL);
  875. int last = -1;
  876. while (charat() != -1) {
  877. if (last != '\\' && charat() == '\'') {
  878. paint(1, FLAG_NUMERAL);
  879. return;
  880. } else if (last == '\\' && charat() == '\\') {
  881. paint(1, FLAG_NUMERAL);
  882. last = -1;
  883. } else {
  884. last = charat();
  885. paint(1, FLAG_NUMERAL);
  886. }
  887. }
  888. }
  889. /**
  890. * Paint a generic C pragma, eg. a #define statement.
  891. */
  892. static int paint_c_pragma(struct syntax_state * state) {
  893. while (state->i < state->line->actual) {
  894. if (charat() == '"') {
  895. /* Paint C string */
  896. paint_c_string(state);
  897. } else if (charat() == '\'') {
  898. paint_c_char(state);
  899. } else if (charat() == '\\' && state->i == state->line->actual - 1) {
  900. paint(1, FLAG_PRAGMA);
  901. return 2;
  902. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  903. continue;
  904. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  905. continue;
  906. } else {
  907. paint(1, FLAG_PRAGMA);
  908. }
  909. }
  910. return 0;
  911. }
  912. /**
  913. * Paint a comment until end of line, assumes this comment can not continue.
  914. * (Some languages have comments that can continue with a \ - don't use this!)
  915. * Assumes you've already painted your comment start characters.
  916. */
  917. static int paint_comment(struct syntax_state * state) {
  918. while (charat() != -1) {
  919. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  920. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  921. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  922. else { paint(1, FLAG_COMMENT); }
  923. }
  924. return -1;
  925. }
  926. /**
  927. * Paint a classic C comment which continues until terminated.
  928. * Assumes you've already painted the starting / and *.
  929. */
  930. static int paint_c_comment(struct syntax_state * state) {
  931. int last = -1;
  932. while (charat() != -1) {
  933. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  934. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  935. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  936. else if (last == '*' && charat() == '/') {
  937. paint(1, FLAG_COMMENT);
  938. return 0;
  939. } else {
  940. last = charat();
  941. paint(1, FLAG_COMMENT);
  942. }
  943. }
  944. return 1;
  945. }
  946. /**
  947. * Paint integers and floating point values with some handling for suffixes.
  948. */
  949. static int paint_c_numeral(struct syntax_state * state) {
  950. if (charat() == '0' && (nextchar() == 'x' || nextchar() == 'X')) {
  951. paint(2, FLAG_NUMERAL);
  952. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  953. } else if (charat() == '0' && nextchar() == '.') {
  954. paint(2, FLAG_NUMERAL);
  955. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  956. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  957. return 0;
  958. } else if (charat() == '0') {
  959. paint(1, FLAG_NUMERAL);
  960. while (charat() >= '0' && charat() <= '7') paint(1, FLAG_NUMERAL);
  961. } else {
  962. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  963. if (charat() == '.') {
  964. paint(1, FLAG_NUMERAL);
  965. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  966. if (charat() == 'f') paint(1, FLAG_NUMERAL);
  967. return 0;
  968. }
  969. }
  970. while (charat() == 'u' || charat() == 'U' || charat() == 'l' || charat() == 'L') paint(1, FLAG_NUMERAL);
  971. return 0;
  972. }
  973. static int syn_c_calculate(struct syntax_state * state) {
  974. switch (state->state) {
  975. case -1:
  976. case 0:
  977. if (charat() == '#') {
  978. /* Must be first thing on line, but can have spaces before */
  979. for (int i = 0; i < state->i; ++i) {
  980. if (state->line->text[i].codepoint != ' ' && state->line->text[i].codepoint != '\t') {
  981. skip();
  982. return 0;
  983. }
  984. }
  985. /* Handle preprocessor functions */
  986. paint(1, FLAG_PRAGMA);
  987. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  988. if (match_and_paint(state, "include", FLAG_PRAGMA, c_keyword_qualifier)) {
  989. /* Put quotes around <includes> */
  990. while (charat() == ' ') paint(1, FLAG_PRAGMA);
  991. if (charat() == '<') {
  992. paint(1, FLAG_STRING);
  993. while (charat() != '>' && state->i < state->line->actual) {
  994. paint(1, FLAG_STRING);
  995. }
  996. if (charat() != -1) {
  997. paint(1, FLAG_STRING);
  998. }
  999. }
  1000. /* (for "includes", normal pragma highlighting covers that. */
  1001. } else if (match_and_paint(state, "if", FLAG_PRAGMA, c_keyword_qualifier)) {
  1002. /* These are to prevent #if and #else from being highlighted as keywords */
  1003. } else if (match_and_paint(state, "else", FLAG_PRAGMA, c_keyword_qualifier)) {
  1004. /* ... */
  1005. }
  1006. return paint_c_pragma(state);
  1007. } else if (charat() == '/' && nextchar() == '/') {
  1008. /* C++-style comments */
  1009. paint_comment(state);
  1010. } else if (charat() == '/' && nextchar() == '*') {
  1011. /* C-style comments */
  1012. if (paint_c_comment(state) == 1) return 1;
  1013. return 0;
  1014. } else if (find_keywords(state, syn_c_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1015. return 0;
  1016. } else if (find_keywords(state, syn_c_types, FLAG_TYPE, c_keyword_qualifier)) {
  1017. return 0;
  1018. } else if (find_keywords(state, syn_c_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1019. return 0;
  1020. } else if (charat() == '\"') {
  1021. paint_c_string(state);
  1022. return 0;
  1023. } else if (charat() == '\'') {
  1024. paint_c_char(state);
  1025. return 0;
  1026. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1027. paint_c_numeral(state);
  1028. return 0;
  1029. } else if (charat() != -1) {
  1030. skip();
  1031. return 0;
  1032. }
  1033. break;
  1034. case 1:
  1035. /* In a block comment */
  1036. if (paint_c_comment(state) == 1) return 1;
  1037. return 0;
  1038. case 2:
  1039. /* In an unclosed preprocessor statement */
  1040. return paint_c_pragma(state);
  1041. }
  1042. return -1;
  1043. }
  1044. static char * c_ext[] = {".c",".h",".cpp",".hpp",".c++",".h++",".cc",".hh",NULL};
  1045. static char * syn_py_keywords[] = {
  1046. "class","def","return","del","if","else","elif","for","while","continue",
  1047. "break","assert","as","and","or","except","finally","from","global",
  1048. "import","in","is","lambda","with","nonlocal","not","pass","raise","try","yield",
  1049. NULL
  1050. };
  1051. static char * syn_py_types[] = {
  1052. "object","set","dict","int","str","bytes",
  1053. NULL
  1054. };
  1055. static char * syn_py_special[] = {
  1056. "True","False","None",
  1057. NULL
  1058. };
  1059. static int paint_py_triple_double(struct syntax_state * state) {
  1060. while (charat() != -1) {
  1061. if (charat() == '"') {
  1062. paint(1, FLAG_STRING);
  1063. if (charat() == '"' && nextchar() == '"') {
  1064. paint(2, FLAG_STRING);
  1065. return 0;
  1066. }
  1067. } else {
  1068. paint(1, FLAG_STRING);
  1069. }
  1070. }
  1071. return 1; /* continues */
  1072. }
  1073. static int paint_py_triple_single(struct syntax_state * state) {
  1074. while (charat() != -1) {
  1075. if (charat() == '\'') {
  1076. paint(1, FLAG_STRING);
  1077. if (charat() == '\'' && nextchar() == '\'') {
  1078. paint(2, FLAG_STRING);
  1079. return 0;
  1080. }
  1081. } else {
  1082. paint(1, FLAG_STRING);
  1083. }
  1084. }
  1085. return 2; /* continues */
  1086. }
  1087. static int paint_py_single_string(struct syntax_state * state) {
  1088. paint(1, FLAG_STRING);
  1089. int last = -1;
  1090. while (charat() != -1) {
  1091. if (last != '\\' && charat() == '\'') {
  1092. paint(1, FLAG_STRING);
  1093. return 0;
  1094. } else if (last == '\\' && charat() == '\\') {
  1095. paint(1, FLAG_STRING);
  1096. last = -1;
  1097. /* TODO check for \0, \r, \n, \0xxx, etc. */
  1098. } else {
  1099. last = charat();
  1100. paint(1, FLAG_STRING);
  1101. }
  1102. }
  1103. return 0;
  1104. }
  1105. static int paint_py_numeral(struct syntax_state * state) {
  1106. if (charat() == '0' && (nextchar() == 'x' || nextchar() == 'X')) {
  1107. paint(2, FLAG_NUMERAL);
  1108. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  1109. } else if (charat() == '0' && nextchar() == '.') {
  1110. paint(2, FLAG_NUMERAL);
  1111. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1112. if ((charat() == '+' || charat() == '-') && (nextchar() == 'e' || nextchar() == 'E')) {
  1113. paint(2, FLAG_NUMERAL);
  1114. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1115. } else if (charat() == 'e' || charat() == 'E') {
  1116. paint(1, FLAG_NUMERAL);
  1117. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1118. }
  1119. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1120. return 0;
  1121. } else {
  1122. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1123. if (charat() == '.') {
  1124. paint(1, FLAG_NUMERAL);
  1125. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1126. if ((charat() == '+' || charat() == '-') && (nextchar() == 'e' || nextchar() == 'E')) {
  1127. paint(2, FLAG_NUMERAL);
  1128. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1129. } else if (charat() == 'e' || charat() == 'E') {
  1130. paint(1, FLAG_NUMERAL);
  1131. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1132. }
  1133. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1134. return 0;
  1135. }
  1136. if (charat() == 'j') paint(1, FLAG_NUMERAL);
  1137. }
  1138. while (charat() == 'l' || charat() == 'L') paint(1, FLAG_NUMERAL);
  1139. return 0;
  1140. }
  1141. static int syn_py_calculate(struct syntax_state * state) {
  1142. switch (state->state) {
  1143. case -1:
  1144. case 0:
  1145. if (charat() == '#') {
  1146. paint_comment(state);
  1147. } else if (state->i == 0 && match_and_paint(state, "import", FLAG_PRAGMA, c_keyword_qualifier)) {
  1148. return 0;
  1149. } else if (charat() == '@') {
  1150. paint(1, FLAG_PRAGMA);
  1151. while (c_keyword_qualifier(charat())) paint(1, FLAG_PRAGMA);
  1152. return 0;
  1153. } else if (charat() == '"') {
  1154. if (nextchar() == '"' && charrel(2) == '"') {
  1155. paint(3, FLAG_STRING);
  1156. return paint_py_triple_double(state);
  1157. } else {
  1158. paint_simple_string(state);
  1159. return 0;
  1160. }
  1161. } else if (find_keywords(state, syn_py_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1162. return 0;
  1163. } else if (find_keywords(state, syn_py_types, FLAG_TYPE, c_keyword_qualifier)) {
  1164. return 0;
  1165. } else if (find_keywords(state, syn_py_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1166. return 0;
  1167. } else if (charat() == '\'') {
  1168. if (nextchar() == '\'' && charrel(2) == '\'') {
  1169. paint(3, FLAG_STRING);
  1170. return paint_py_triple_single(state);
  1171. } else {
  1172. paint_py_single_string(state);
  1173. return 0;
  1174. }
  1175. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1176. paint_py_numeral(state);
  1177. return 0;
  1178. } else if (charat() != -1) {
  1179. skip();
  1180. return 0;
  1181. }
  1182. break;
  1183. case 1: /* multiline """ string */
  1184. return paint_py_triple_double(state);
  1185. case 2: /* multiline ''' string */
  1186. return paint_py_triple_single(state);
  1187. }
  1188. return -1;
  1189. }
  1190. static char * py_ext[] = {".py",NULL};
  1191. static char * syn_java_keywords[] = {
  1192. "assert","break","case","catch","class","continue",
  1193. "default","do","else","enum","exports","extends","finally",
  1194. "for","if","implements","instanceof","interface","module","native",
  1195. "new","requires","return","throws",
  1196. "strictfp","super","switch","synchronized","this","throw","try","while",
  1197. NULL
  1198. };
  1199. static char * syn_java_types[] = {
  1200. "var","boolean","void","short","long","int","double","float","enum","char",
  1201. "private","protected","public","static","final","transient","volatile","abstract",
  1202. NULL
  1203. };
  1204. static char * syn_java_special[] = {
  1205. "true","false","import","package","null",
  1206. NULL
  1207. };
  1208. static char * syn_java_at_comments[] = {
  1209. "@author","@see","@since","@param","@return","@throws",
  1210. "@version","@exception","@deprecated",
  1211. NULL
  1212. };
  1213. static int at_keyword_qualifier(int c) {
  1214. return isalnum(c) || (c == '_') || (c == '@');
  1215. }
  1216. static char * syn_java_brace_comments[] = {
  1217. "{@docRoot","{@inheritDoc","{@link","{@linkplain",
  1218. "{@value","{@code","{@literal","{@serial",
  1219. "{@serialData","{@serialField",
  1220. NULL
  1221. };
  1222. static int brace_keyword_qualifier(int c) {
  1223. return isalnum(c) || (c == '{') || (c == '@');
  1224. }
  1225. static int paint_java_comment(struct syntax_state * state) {
  1226. int last = -1;
  1227. while (charat() != -1) {
  1228. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1229. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1230. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1231. else if (charat() == '@') {
  1232. if (!find_keywords(state, syn_java_at_comments, FLAG_ESCAPE, at_keyword_qualifier)) {
  1233. /* Paint the @ */
  1234. paint(1, FLAG_COMMENT);
  1235. }
  1236. } else if (charat() == '{') {
  1237. /* see if this terminates */
  1238. if (find_keywords(state, syn_java_brace_comments, FLAG_ESCAPE, brace_keyword_qualifier)) {
  1239. while (charat() != '}' && charat() != -1) {
  1240. paint(1, FLAG_ESCAPE);
  1241. }
  1242. if (charat() == '}') paint(1, FLAG_ESCAPE);
  1243. } else {
  1244. paint(1, FLAG_COMMENT);
  1245. }
  1246. } else if (charat() == '<') {
  1247. int is_tag = 0;
  1248. for (int i = 1; charrel(i) != -1; ++i) {
  1249. if (charrel(i) == '>') {
  1250. is_tag = 1;
  1251. break;
  1252. }
  1253. if (!isalnum(charrel(i)) && charrel(i) != '/') {
  1254. is_tag = 0;
  1255. break;
  1256. }
  1257. }
  1258. if (is_tag) {
  1259. paint(1, FLAG_TYPE);
  1260. while (charat() != -1 && charat() != '>') {
  1261. if (charat() == '/') paint(1, FLAG_TYPE);
  1262. else paint(1, FLAG_KEYWORD);
  1263. }
  1264. if (charat() == '>') paint(1, FLAG_TYPE);
  1265. } else {
  1266. /* Paint the < */
  1267. paint(1, FLAG_COMMENT);
  1268. }
  1269. } else if (last == '*' && charat() == '/') {
  1270. paint(1, FLAG_COMMENT);
  1271. return 0;
  1272. } else {
  1273. last = charat();
  1274. paint(1, FLAG_COMMENT);
  1275. }
  1276. }
  1277. return 1;
  1278. }
  1279. static int syn_java_calculate(struct syntax_state * state) {
  1280. switch (state->state) {
  1281. case -1:
  1282. case 0:
  1283. if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1284. paint_c_numeral(state);
  1285. return 0;
  1286. } else if (charat() == '/' && nextchar() == '/') {
  1287. /* C++-style comments */
  1288. paint_comment(state);
  1289. } else if (charat() == '/' && nextchar() == '*') {
  1290. /* C-style comments; TODO: Needs special stuff for @author; <html>; etc. */
  1291. if (paint_java_comment(state) == 1) return 1;
  1292. } else if (find_keywords(state, syn_java_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1293. return 0;
  1294. } else if (find_keywords(state, syn_java_types, FLAG_TYPE, c_keyword_qualifier)) {
  1295. return 0;
  1296. } else if (find_keywords(state, syn_java_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1297. return 0;
  1298. } else if (charat() == '\"') {
  1299. paint_simple_string(state);
  1300. return 0;
  1301. } else if (charat() == '\'') {
  1302. paint_c_char(state);
  1303. return 0;
  1304. } else if (charat() == '@') {
  1305. paint(1, FLAG_PRAGMA);
  1306. while (c_keyword_qualifier(charat())) paint(1, FLAG_PRAGMA);
  1307. } else if (charat() != -1) {
  1308. skip();
  1309. return 0;
  1310. }
  1311. break;
  1312. case 1:
  1313. if (paint_java_comment(state) == 1) return 1;
  1314. return 0;
  1315. }
  1316. return -1;
  1317. }
  1318. static char * java_ext[] = {".java",NULL};
  1319. static int syn_diff_calculate(struct syntax_state * state) {
  1320. /* No states to worry about */
  1321. if (state->i == 0) {
  1322. int flag = 0;
  1323. if (charat() == '+') {
  1324. flag = FLAG_DIFFPLUS;
  1325. } else if (charat() == '-') {
  1326. flag = FLAG_DIFFMINUS;
  1327. } else if (charat() == '@') {
  1328. flag = FLAG_TYPE;
  1329. } else if (charat() != ' ') {
  1330. flag = FLAG_KEYWORD;
  1331. } else {
  1332. return -1;
  1333. }
  1334. while (charat() != -1) paint(1, flag);
  1335. }
  1336. return -1;
  1337. }
  1338. static char * diff_ext[] = {".patch",".diff",NULL};
  1339. static int syn_conf_calculate(struct syntax_state * state) {
  1340. if (state->i == 0) {
  1341. if (charat() == ';') {
  1342. while (charat() != -1) paint(1, FLAG_COMMENT);
  1343. } else if (charat() == '#') {
  1344. while (charat() != -1) paint(1, FLAG_COMMENT);
  1345. } else if (charat() == '[') {
  1346. paint(1, FLAG_KEYWORD);
  1347. while (charat() != ']' && charat() != -1) paint(1, FLAG_KEYWORD);
  1348. if (charat() == ']') paint(1, FLAG_KEYWORD);
  1349. } else {
  1350. while (charat() != '=' && charat() != -1) paint(1, FLAG_TYPE);
  1351. }
  1352. }
  1353. return -1;
  1354. }
  1355. static char * conf_ext[] = {".conf",".ini",".git/config",NULL};
  1356. static char * syn_rust_keywords[] = {
  1357. "as","break","const","continue","crate","else","enum","extern",
  1358. "false","fn","for","if","impl","in","let","loop","match","mod",
  1359. "move","mut","pub","ref","return","Self","self","static","struct",
  1360. "super","trait","true","type","unsafe","use","where","while",
  1361. NULL,
  1362. };
  1363. static char * syn_rust_types[] = {
  1364. "bool","char","str",
  1365. "i8","i16","i32","i64",
  1366. "u8","u16","u32","u64",
  1367. "isize","usize",
  1368. "f32","f64",
  1369. NULL,
  1370. };
  1371. static int paint_rs_comment(struct syntax_state * state) {
  1372. while (charat() != -1) {
  1373. if (match_and_paint(state, "TODO", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1374. else if (match_and_paint(state, "XXX", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1375. else if (match_and_paint(state, "FIXME", FLAG_NOTICE, c_keyword_qualifier)) { continue; }
  1376. else if (charat() == '*' && nextchar() == '/') {
  1377. paint(2, FLAG_COMMENT);
  1378. state->state--;
  1379. if (state->state == 0) return 0;
  1380. } else if (charat() == '/' && nextchar() == '*') {
  1381. state->state++;
  1382. paint(2, FLAG_COMMENT);
  1383. } else {
  1384. paint(1, FLAG_COMMENT);
  1385. }
  1386. }
  1387. return state->state;
  1388. }
  1389. static int paint_rust_numeral(struct syntax_state * state) {
  1390. if (charat() == '0' && nextchar() == 'b') {
  1391. paint(2, FLAG_NUMERAL);
  1392. while (charat() == '0' || charat() == '1' || charat() == '_') paint(1, FLAG_NUMERAL);
  1393. } else if (charat() == '0' && nextchar() == 'o') {
  1394. paint(2, FLAG_NUMERAL);
  1395. while ((charat() >= '0' && charat() <= '7') || charat() == '_') paint(1, FLAG_NUMERAL);
  1396. } else if (charat() == '0' && nextchar() == 'x') {
  1397. paint(2, FLAG_NUMERAL);
  1398. while (isxdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1399. } else if (charat() == '0' && nextchar() == '.') {
  1400. paint(2, FLAG_NUMERAL);
  1401. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1402. } else {
  1403. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1404. if (charat() == '.') {
  1405. paint(1, FLAG_NUMERAL);
  1406. while (isdigit(charat()) || charat() == '_') paint(1, FLAG_NUMERAL);
  1407. }
  1408. }
  1409. return 0;
  1410. }
  1411. static int syn_rust_calculate(struct syntax_state * state) {
  1412. switch (state->state) {
  1413. case -1:
  1414. case 0:
  1415. if (charat() == '/' && nextchar() == '/') {
  1416. /* C++-style comments */
  1417. paint_comment(state);
  1418. } else if (charat() == '/' && nextchar() == '*') {
  1419. paint(2, FLAG_COMMENT);
  1420. state->state = 1;
  1421. return paint_rs_comment(state);
  1422. } else if (find_keywords(state, syn_rust_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1423. return 0;
  1424. } else if (find_keywords(state, syn_rust_types, FLAG_TYPE, c_keyword_qualifier)) {
  1425. return 0;
  1426. } else if (charat() == '\"') {
  1427. paint_simple_string(state);
  1428. return 0;
  1429. } else if (charat() == '\'') {
  1430. paint_c_char(state);
  1431. return 0;
  1432. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1433. paint_rust_numeral(state);
  1434. return 0;
  1435. } else if (charat() != -1) {
  1436. skip();
  1437. return 0;
  1438. }
  1439. break;
  1440. default: /* Nested comments */
  1441. return paint_rs_comment(state);
  1442. }
  1443. return -1;
  1444. }
  1445. static char * rust_ext[] = {".rs",NULL};
  1446. static char * syn_bimrc_keywords[] = {
  1447. "history","padding","hlparen","hlcurrent","splitpercent",
  1448. "shiftscrolling","scrollamount","git","colorgutter",
  1449. NULL
  1450. };
  1451. static int syn_bimrc_calculate(struct syntax_state * state) {
  1452. /* No states */
  1453. if (state->i == 0) {
  1454. if (charat() == '#') {
  1455. while (charat() != -1) paint(1, FLAG_COMMENT);
  1456. } else if (match_and_paint(state, "theme", FLAG_KEYWORD, c_keyword_qualifier)) {
  1457. if (charat() == '=') {
  1458. skip();
  1459. for (struct theme_def * s = themes; s->name; ++s) {
  1460. if (match_and_paint(state, s->name, FLAG_TYPE, c_keyword_qualifier)) break;
  1461. }
  1462. }
  1463. } else if (find_keywords(state, syn_bimrc_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1464. return -1;
  1465. }
  1466. }
  1467. return -1;
  1468. }
  1469. static char * bimrc_ext[] = {".bimrc",NULL};
  1470. static int syn_biminfo_calculate(struct syntax_state * state) {
  1471. if (state->i == 0) {
  1472. if (charat() == '#') {
  1473. while (charat() != -1) paint(1, FLAG_COMMENT);
  1474. } else if (charat() == '>') {
  1475. paint(1, FLAG_KEYWORD);
  1476. while (charat() != ' ') paint(1, FLAG_TYPE);
  1477. skip();
  1478. while (charat() != -1) paint(1, FLAG_NUMERAL);
  1479. } else {
  1480. while (charat() != -1) paint(1, FLAG_DIFFMINUS); /* Add a FLAG_ERROR maybe? */
  1481. }
  1482. }
  1483. return -1;
  1484. }
  1485. static char * biminfo_ext[] = {".biminfo",NULL};
  1486. static int syn_gitcommit_calculate(struct syntax_state * state) {
  1487. if (state->i == 0 && charat() == '#') {
  1488. while (charat() != -1) paint(1, FLAG_COMMENT);
  1489. } else if (state->line_no == 0) {
  1490. /* First line is special */
  1491. while (charat() != -1 && state->i < 50) paint(1, FLAG_KEYWORD);
  1492. while (charat() != -1) paint(1, FLAG_DIFFMINUS);
  1493. } else if (state->line_no == 1) {
  1494. /* No text on second line */
  1495. while (charat() != -1) paint(1, FLAG_DIFFMINUS);
  1496. } else if (charat() != -1) {
  1497. skip();
  1498. return 0;
  1499. }
  1500. return -1;
  1501. }
  1502. static char * gitcommit_ext[] = {"COMMIT_EDITMSG", NULL};
  1503. static char * syn_gitrebase_commands[] = {
  1504. "p","r","e","s","f","x","d",
  1505. "pick","reword","edit","squash","fixup",
  1506. "exec","drop",
  1507. NULL
  1508. };
  1509. static int syn_gitrebase_calculate(struct syntax_state * state) {
  1510. if (state->i == 0 && charat() == '#') {
  1511. while (charat() != -1) paint(1, FLAG_COMMENT);
  1512. } else if (state->i == 0 && find_keywords(state, syn_gitrebase_commands, FLAG_KEYWORD, c_keyword_qualifier)) {
  1513. while (charat() == ' ') skip();
  1514. while (isxdigit(charat())) paint(1, FLAG_NUMERAL);
  1515. return -1;
  1516. }
  1517. return -1;
  1518. }
  1519. static char * gitrebase_ext[] = {"git-rebase-todo",NULL};
  1520. static int make_command_qualifier(int c) {
  1521. return isalnum(c) || c == '_' || c == '-' || c == '.';
  1522. }
  1523. static char * syn_make_commands[] = {
  1524. "define","endef","undefine","ifdef","ifndef","ifeq","ifneq","else","endif",
  1525. "include","sinclude","override","export","unexport","private","vpath",
  1526. "-include",
  1527. NULL
  1528. };
  1529. static char * syn_make_functions[] = {
  1530. "subst","patsubst","findstring","filter","filter-out",
  1531. "sort","word","words","wordlist","firstword","lastword",
  1532. "dir","notdir","suffix","basename","addsuffix","addprefix",
  1533. "join","wildcard","realpath","abspath","error","warning",
  1534. "shell","origin","flavor","foreach","if","or","and",
  1535. "call","eval","file","value",
  1536. NULL
  1537. };
  1538. static char * syn_make_special_targets[] = {
  1539. "all", /* Not really special, but highlight it 'cause I feel like it. */
  1540. ".PHONY", ".SUFFIXES", ".DEFAULT", ".PRECIOUS", ".INTERMEDIATE",
  1541. ".SECONDARY", ".SECONDEXPANSION", ".DELETE_ON_ERROR", ".IGNORE",
  1542. ".LOW_RESOLUTION_TIME", ".SILENT", ".EXPORT_ALL_VARIABLES",
  1543. ".NOTPARALLEL", ".ONESHELL", ".POSIX",
  1544. NULL
  1545. };
  1546. static int make_close_paren(struct syntax_state * state) {
  1547. paint(2, FLAG_TYPE);
  1548. find_keywords(state, syn_make_functions, FLAG_KEYWORD, c_keyword_qualifier);
  1549. int i = 1;
  1550. while (charat() != -1) {
  1551. if (charat() == '(') {
  1552. i++;
  1553. } else if (charat() == ')') {
  1554. i--;
  1555. if (i == 0) {
  1556. paint(1,FLAG_TYPE);
  1557. return 0;
  1558. }
  1559. } else if (charat() == '"') {
  1560. paint_simple_string(state);
  1561. }
  1562. paint(1,FLAG_TYPE);
  1563. }
  1564. return 0;
  1565. }
  1566. static int make_close_brace(struct syntax_state * state) {
  1567. paint(2, FLAG_TYPE);
  1568. while (charat() != -1) {
  1569. if (charat() == '}') {
  1570. paint(1, FLAG_TYPE);
  1571. return 0;
  1572. }
  1573. paint(1, FLAG_TYPE);
  1574. }
  1575. return 0;
  1576. }
  1577. static int make_variable_or_comment(struct syntax_state * state, int flag) {
  1578. while (charat() != -1) {
  1579. if (charat() == '$') {
  1580. switch (nextchar()) {
  1581. case '(':
  1582. make_close_paren(state);
  1583. break;
  1584. case '{':
  1585. make_close_brace(state);
  1586. break;
  1587. default:
  1588. paint(2, FLAG_TYPE);
  1589. break;
  1590. }
  1591. } else if (charat() == '#') {
  1592. while (charat() != -1) paint(1, FLAG_COMMENT);
  1593. } else {
  1594. paint(1, flag);
  1595. }
  1596. }
  1597. return 0;
  1598. }
  1599. static int syn_make_calculate(struct syntax_state * state) {
  1600. if (state->i == 0 && charat() == '\t') {
  1601. make_variable_or_comment(state, FLAG_NUMERAL);
  1602. } else {
  1603. while (charat() == ' ') { skip(); }
  1604. /* Peek forward to see if this is a rule or a variable */
  1605. int whatisit = 0;
  1606. for (int i = 0; charrel(i) != -1; ++i) {
  1607. if (charrel(i) == ':' && charrel(i+1) != '=') {
  1608. whatisit = 1;
  1609. break;
  1610. } else if (charrel(i) == '=') {
  1611. whatisit = 2;
  1612. break;
  1613. } else if (charrel(i) == '#') {
  1614. break;
  1615. }
  1616. }
  1617. if (!whatisit) {
  1618. /* Check for functions */
  1619. while (charat() != -1) {
  1620. if (charat() == '#') {
  1621. while (charat() != -1) paint(1, FLAG_COMMENT);
  1622. } else if (find_keywords(state, syn_make_commands, FLAG_KEYWORD, make_command_qualifier)) {
  1623. continue;
  1624. } else if (charat() == '$') {
  1625. make_variable_or_comment(state, FLAG_NONE);
  1626. } else {
  1627. skip();
  1628. }
  1629. }
  1630. } else if (whatisit == 1) {
  1631. /* It's a rule */
  1632. while (charat() != -1) {
  1633. if (charat() == '#') {
  1634. while (charat() != -1) paint(1, FLAG_COMMENT);
  1635. } else if (charat() == ':') {
  1636. paint(1, FLAG_TYPE);
  1637. make_variable_or_comment(state, FLAG_NONE);
  1638. } else if (find_keywords(state, syn_make_special_targets, FLAG_KEYWORD, make_command_qualifier)) {
  1639. continue;
  1640. } else {
  1641. paint(1, FLAG_TYPE);
  1642. }
  1643. }
  1644. } else if (whatisit == 2) {
  1645. /* It's a variable definition */
  1646. match_and_paint(state, "export", FLAG_KEYWORD, c_keyword_qualifier);
  1647. while (charat() != -1 && charat() != '+' && charat() != '=' && charat() != ':' && charat() != '?') {
  1648. paint(1, FLAG_TYPE);
  1649. }
  1650. while (charat() != -1 && charat() != '=') skip();
  1651. /* Highlight variable expansions */
  1652. make_variable_or_comment(state, FLAG_NONE);
  1653. }
  1654. }
  1655. return -1;
  1656. }
  1657. static char * make_ext[] = {"Makefile","makefile","GNUmakefile",".mak",NULL};
  1658. #define nest(lang, low) \
  1659. do { \
  1660. state->state = (state->state < 1 ? 0 : state->state - low); \
  1661. do { state->state = lang(state); } while (state->state == 0); \
  1662. if (state->state == -1) return low; \
  1663. return state->state + low; \
  1664. } while (0)
  1665. static int match_forward(struct syntax_state * state, char * c) {
  1666. int i = 0;
  1667. while (1) {
  1668. if (charrel(i) == -1 && !*c) return 1;
  1669. if (charrel(i) != *c) return 0;
  1670. c++;
  1671. i++;
  1672. }
  1673. return 0;
  1674. }
  1675. static int syn_json_calculate(struct syntax_state * state);
  1676. static int syn_xml_calculate(struct syntax_state * state);
  1677. static int syn_markdown_calculate(struct syntax_state * state) {
  1678. if (state->state < 1) {
  1679. while (charat() != -1) {
  1680. if (state->i == 0 && charat() == '#') {
  1681. while (charat() == '#') paint(1, FLAG_KEYWORD);
  1682. while (charat() != -1) paint(1, FLAG_BOLD);
  1683. return -1;
  1684. } else if (state->i == 0) {
  1685. while (charat() == ' ') skip();
  1686. if (charat() == '`' && nextchar() == '`' && charrel(2) == '`') {
  1687. paint(3, FLAG_STRING);
  1688. if (match_forward(state, "c")) {
  1689. nest(syn_c_calculate, 2);
  1690. } else if (match_forward(state,"c++")) {
  1691. nest(syn_c_calculate, 2);
  1692. } else if (match_forward(state,"py") || match_forward(state,"python")) {
  1693. nest(syn_py_calculate, 5);
  1694. } else if (match_forward(state, "java")) {
  1695. nest(syn_java_calculate, 8);
  1696. } else if (match_forward(state,"json")) {
  1697. nest(syn_json_calculate, 10);
  1698. } else if (match_forward(state,"xml")) {
  1699. nest(syn_xml_calculate, 11);
  1700. } else if (match_forward(state,"html")) {
  1701. nest(syn_xml_calculate, 11); // TODO this will be a different highlighter later
  1702. } else if (match_forward(state,"make")) {
  1703. nest(syn_make_calculate, 16);
  1704. } else if (match_forward(state, "diff")) {
  1705. nest(syn_diff_calculate, 17);
  1706. } else if (match_forward(state, "rust")) {
  1707. nest(syn_rust_calculate, 18); /* Keep this at the end for now */
  1708. }
  1709. return 1;
  1710. }
  1711. }
  1712. if (charat() == ' ' && charrel(1) == ' ' && charrel(2) == ' ' && charrel(3) == ' ') {
  1713. return -1;
  1714. } else if (charat() == '`') {
  1715. paint(1, FLAG_STRING);
  1716. while (charat() != -1) {
  1717. if (charat() == '`') {
  1718. paint(1, FLAG_STRING);
  1719. return 0;
  1720. }
  1721. paint(1, FLAG_STRING);
  1722. }
  1723. } else if (charat() == '[') {
  1724. skip();
  1725. while (charat() != -1 && charat() != ']') {
  1726. paint(1, FLAG_LINK);
  1727. }
  1728. if (charat() == ']') skip();
  1729. if (charat() == '(') {
  1730. skip();
  1731. while (charat() != -1 && charat() != ')') {
  1732. paint(1, FLAG_NUMERAL);
  1733. }
  1734. }
  1735. } else {
  1736. skip();
  1737. return 0;
  1738. }
  1739. }
  1740. return -1;
  1741. } else if (state->state >= 1) {
  1742. /* Continuing generic triple-` */
  1743. if (state->i == 0) {
  1744. /* Go backwards until we find the source ``` */
  1745. int count = 0;
  1746. for (int i = state->line_no; i > 0; i--) {
  1747. if (env->lines[i]->istate < 1) {
  1748. while (env->lines[i]->text[count].codepoint == ' ') {
  1749. if (charrel(count) != ' ') goto _nope;
  1750. count++;
  1751. }
  1752. break;
  1753. }
  1754. }
  1755. if (charrel(count) == '`' && charrel(count+1) == '`' && charrel(count+2) == '`' && charrel(count+3) == -1) {
  1756. paint(count+3,FLAG_STRING);
  1757. return -1;
  1758. }
  1759. }
  1760. _nope:
  1761. if (state->state == 1) {
  1762. while (charat() != -1) paint(1, FLAG_STRING);
  1763. return 1;
  1764. } else if (state->state < 5) {
  1765. nest(syn_c_calculate, 2);
  1766. } else if (state->state < 8) {
  1767. nest(syn_py_calculate, 5);
  1768. } else if (state->state < 10) {
  1769. nest(syn_java_calculate, 8);
  1770. } else if (state->state < 11) {
  1771. nest(syn_json_calculate, 10);
  1772. } else if (state->state < 16) {
  1773. nest(syn_xml_calculate, 11);
  1774. } else if (state->state < 17) {
  1775. nest(syn_make_calculate, 16);
  1776. } else if (state->state < 18) {
  1777. nest(syn_diff_calculate, 17);
  1778. } else {
  1779. nest(syn_rust_calculate, 18);
  1780. }
  1781. }
  1782. return -1;
  1783. }
  1784. static char * markdown_ext[] = {".md",".markdown",NULL};
  1785. static char * syn_json_keywords[] = {
  1786. "true","false","null",
  1787. NULL
  1788. };
  1789. static int syn_json_calculate(struct syntax_state * state) {
  1790. while (charat() != -1) {
  1791. if (charat() == '"') {
  1792. int backtrack = state->i;
  1793. paint_simple_string(state);
  1794. int backtrack_end = state->i;
  1795. while (charat() == ' ') skip();
  1796. if (charat() == ':') {
  1797. /* This is dumb. */
  1798. state->i = backtrack;
  1799. paint(1, FLAG_ESCAPE);
  1800. while (state->i < backtrack_end-1) {
  1801. paint(1, FLAG_KEYWORD);
  1802. }
  1803. if (charat() == '"') {
  1804. paint(1, FLAG_ESCAPE);
  1805. }
  1806. }
  1807. return 0;
  1808. } else if (charat() == '-' || isdigit(charat())) {
  1809. if (charat() == '-') paint(1, FLAG_NUMERAL);
  1810. if (charat() == '0') {
  1811. paint(1, FLAG_NUMERAL);
  1812. } else {
  1813. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1814. }
  1815. if (charat() == '.') {
  1816. paint(1, FLAG_NUMERAL);
  1817. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1818. }
  1819. if (charat() == 'e' || charat() == 'E') {
  1820. paint(1, FLAG_NUMERAL);
  1821. if (charat() == '+' || charat() == '-') {
  1822. paint(1, FLAG_NUMERAL);
  1823. }
  1824. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  1825. }
  1826. } else if (find_keywords(state,syn_json_keywords,FLAG_NUMERAL,c_keyword_qualifier)) {
  1827. /* ... */
  1828. } else {
  1829. skip();
  1830. return 0;
  1831. }
  1832. }
  1833. return -1;
  1834. }
  1835. static char * json_ext[] = {".json",NULL}; // TODO other stuff that uses json
  1836. static int syn_xml_calculate(struct syntax_state * state) {
  1837. switch (state->state) {
  1838. case -1:
  1839. case 0:
  1840. if (charat() == -1) return -1;
  1841. if (charat() != '<') {
  1842. skip();
  1843. return 0;
  1844. }
  1845. /* Opening brace */
  1846. if (charat() == '<' && nextchar() == '!' && charrel(2) == '-' && charrel(3) == '-') {
  1847. paint(4, FLAG_COMMENT);
  1848. goto _comment;
  1849. }
  1850. paint(1, FLAG_TYPE);
  1851. /* Fall through */
  1852. case 1:
  1853. /* State 1: We saw an opening brace. */
  1854. while (charat() != -1) {
  1855. if (charat() == '/') paint(1, FLAG_TYPE);
  1856. if (charat() == '?') paint(1, FLAG_TYPE);
  1857. if (charat() == ' ' || charat() == '\t') skip();
  1858. if (isalnum(charat())) {
  1859. while (isalnum(charat()) || charat() == '-') paint(1, FLAG_KEYWORD);
  1860. if (charat() == -1) return 2;
  1861. goto _in_tag;
  1862. } else {
  1863. paint(1, FLAG_TYPE);
  1864. }
  1865. }
  1866. return -1;
  1867. _in_tag:
  1868. case 2:
  1869. while (charat() != -1) {
  1870. if (charat() == '>') {
  1871. paint(1, FLAG_TYPE);
  1872. return 0;
  1873. } else if (charat() == '"') {
  1874. paint_simple_string(state);
  1875. if (charat() == -1 && lastchar() != '"') {
  1876. return 3;
  1877. }
  1878. } else {
  1879. paint(1, FLAG_TYPE);
  1880. }
  1881. }
  1882. return 2;
  1883. case 3:
  1884. /* In a string in tag */
  1885. if (charat() == '"') {
  1886. paint(1, FLAG_STRING);
  1887. return 2;
  1888. } else {
  1889. paint_simple_string(state);
  1890. if (charat() == -1 && lastchar() != '"') {
  1891. return 3;
  1892. }
  1893. }
  1894. break;
  1895. _comment:
  1896. case 4:
  1897. while (charat() != -1) {
  1898. if (charat() == '-' && nextchar() == '-' && charrel(2) == '>') {
  1899. paint(3, FLAG_COMMENT);
  1900. return 0;
  1901. } else {
  1902. paint(1, FLAG_COMMENT);
  1903. }
  1904. }
  1905. return 4;
  1906. }
  1907. return -1;
  1908. }
  1909. static char * xml_ext[] = {".xml",".htm",".html",NULL}; // TODO other stuff that uses xml (it's a lot!); FIXME htm/html are temporary; make dedicated SGML ones for this
  1910. static char * syn_proto_keywords[] = {
  1911. "syntax","import","option","package","message","group","oneof",
  1912. "optional","required","repeated","default","extend","extensions","to","max","reserved",
  1913. "service","rpc","returns","stream",
  1914. NULL
  1915. };
  1916. static char * syn_proto_types[] = {
  1917. "int32","int64","uint32","uint64","sint32","sint64",
  1918. "fixed32","fixed64","sfixed32","sfixed64",
  1919. "float","double","bool","string","bytes",
  1920. "enum",
  1921. NULL
  1922. };
  1923. static char * syn_proto_special[] = {
  1924. "true","false",
  1925. NULL
  1926. };
  1927. static int syn_proto_calculate(struct syntax_state * state) {
  1928. if (state->state < 1) {
  1929. if (charat() == '/' && nextchar() == '/') {
  1930. paint_comment(state);
  1931. } else if (charat() == '/' && nextchar() == '*') {
  1932. if (paint_c_comment(state) == 1) return 1;
  1933. return 0;
  1934. } else if (find_keywords(state, syn_proto_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  1935. return 0;
  1936. } else if (find_keywords(state, syn_proto_types, FLAG_TYPE, c_keyword_qualifier)) {
  1937. return 0;
  1938. } else if (find_keywords(state, syn_proto_special, FLAG_NUMERAL, c_keyword_qualifier)) {
  1939. return 0;
  1940. } else if (charat() == '"') {
  1941. paint_simple_string(state);
  1942. return 0;
  1943. } else if (!c_keyword_qualifier(lastchar()) && isdigit(charat())) {
  1944. paint_c_numeral(state);
  1945. return 0;
  1946. } else if (charat() != -1) {
  1947. skip();
  1948. return 0;
  1949. }
  1950. return -1;
  1951. } else {
  1952. if (paint_c_comment(state) == 1) return 1;
  1953. return 0;
  1954. }
  1955. }
  1956. static char * proto_ext[] = {".proto",NULL};
  1957. static int esh_variable_qualifier(int c) {
  1958. return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '_');
  1959. }
  1960. static int paint_esh_variable(struct syntax_state * state) {
  1961. if (charat() == '{') {
  1962. paint(1, FLAG_TYPE);
  1963. while (charat() != '}') paint(1, FLAG_TYPE);
  1964. if (charat() == '}') paint(1, FLAG_TYPE);
  1965. } else {
  1966. if (charat() == '?' || charat() == '$' || charat() == '#') {
  1967. paint(1, FLAG_TYPE);
  1968. } else {
  1969. while (esh_variable_qualifier(charat())) paint(1, FLAG_TYPE);
  1970. }
  1971. }
  1972. return 0;
  1973. }
  1974. static int paint_esh_string(struct syntax_state * state) {
  1975. int last = -1;
  1976. while (charat() != -1) {
  1977. if (last != '\\' && charat() == '"') {
  1978. paint(1, FLAG_STRING);
  1979. return 0;
  1980. } else if (charat() == '$') {
  1981. paint(1, FLAG_TYPE);
  1982. paint_esh_variable(state);
  1983. last = -1;
  1984. } else if (charat() != -1) {
  1985. last = charat();
  1986. paint(1, FLAG_STRING);
  1987. }
  1988. }
  1989. return 2;
  1990. }
  1991. static int paint_esh_single_string(struct syntax_state * state) {
  1992. int last = -1;
  1993. while (charat() != -1) {
  1994. if (last != '\\' && charat() == '\'') {
  1995. paint(1, FLAG_STRING);
  1996. return 0;
  1997. } else if (charat() != -1) {
  1998. last = charat();
  1999. paint(1, FLAG_STRING);
  2000. }
  2001. }
  2002. return 1;
  2003. }
  2004. static int esh_keyword_qualifier(int c) {
  2005. return (isalnum(c) || c == '?' || c == '_' || c == '-'); /* technically anything that isn't a space should qualify... */
  2006. }
  2007. static char * esh_keywords[] = {
  2008. "cd","exit","export","help","history","if","empty?",
  2009. "equals?","return","export-cmd","source","exec","not","while",
  2010. "then","else","echo",
  2011. NULL
  2012. };
  2013. static int syn_esh_calculate(struct syntax_state * state) {
  2014. if (state->state == 1) {
  2015. return paint_esh_single_string(state);
  2016. } else if (state->state == 2) {
  2017. return paint_esh_string(state);
  2018. }
  2019. if (charat() == '#') {
  2020. while (charat() != -1) paint(1, FLAG_COMMENT);
  2021. return -1;
  2022. } else if (charat() == '$') {
  2023. paint(1, FLAG_TYPE);
  2024. paint_esh_variable(state);
  2025. return 0;
  2026. } else if (charat() == '\'') {
  2027. paint(1, FLAG_STRING);
  2028. return paint_esh_single_string(state);
  2029. } else if (charat() == '"') {
  2030. paint(1, FLAG_STRING);
  2031. return paint_esh_string(state);
  2032. } else if (match_and_paint(state, "export", FLAG_KEYWORD, esh_keyword_qualifier)) {
  2033. while (charat() == ' ') skip();
  2034. while (esh_keyword_qualifier(charat())) paint(1, FLAG_TYPE);
  2035. return 0;
  2036. } else if (match_and_paint(state, "export-cmd", FLAG_KEYWORD, esh_keyword_qualifier)) {
  2037. while (charat() == ' ') skip();
  2038. while (esh_keyword_qualifier(charat())) paint(1, FLAG_TYPE);
  2039. return 0;
  2040. } else if (find_keywords(state, esh_keywords, FLAG_KEYWORD, esh_keyword_qualifier)) {
  2041. return 0;
  2042. } else if (isdigit(charat())) {
  2043. while (isdigit(charat())) paint(1, FLAG_NUMERAL);
  2044. return 0;
  2045. } else if (charat() != -1) {
  2046. skip();
  2047. return 0;
  2048. }
  2049. return -1;
  2050. }
  2051. /* Only enable esh highlighting by default on ToaruOS */
  2052. static char * esh_ext[] = {
  2053. #ifdef __toaru__
  2054. ".sh",
  2055. #endif
  2056. ".eshrc",".yutanirc",
  2057. NULL
  2058. };
  2059. static char * syn_bash_keywords[] = {
  2060. /* Actual bash keywords */
  2061. "if","then","else","elif","fi","case","esac","for","coproc",
  2062. "select","while","until","do","done","in","function","time",
  2063. /* Other keywords */
  2064. "exit","return","source","function","export","alias","complete","shopt","local","eval",
  2065. /* Common Unix utilities */
  2066. "echo","cd","pushd","popd","printf","sed","rm","mv",
  2067. NULL
  2068. };
  2069. static int bash_pop_state(int state) {
  2070. int new_state = state / 100;
  2071. return new_state * 10;
  2072. }
  2073. static int bash_push_state(int state, int new) {
  2074. return state * 10 + new;
  2075. }
  2076. static int bash_paint_tick(struct syntax_state * state, int out_state) {
  2077. int last = -1;
  2078. while (charat() != -1) {
  2079. if (last != '\\' && charat() == '\'') {
  2080. paint(1, FLAG_STRING);
  2081. return bash_pop_state(out_state);
  2082. } else if (last == '\\') {
  2083. paint(1, FLAG_STRING);
  2084. last = -1;
  2085. } else if (charat() != -1) {
  2086. last = charat();
  2087. paint(1, FLAG_STRING);
  2088. }
  2089. }
  2090. return out_state;
  2091. }
  2092. static int bash_paint_braced_variable(struct syntax_state * state) {
  2093. while (charat() != -1) {
  2094. if (charat() == '}') {
  2095. paint(1, FLAG_NUMERAL);
  2096. return 0;
  2097. }
  2098. paint(1, FLAG_NUMERAL);
  2099. }
  2100. return 0;
  2101. }
  2102. static int bash_special_variable(int c) {
  2103. return (c == '@' || c == '?');
  2104. }
  2105. static int bash_paint_string(struct syntax_state * state, char terminator, int out_state, int color) {
  2106. int last = -1;
  2107. state->state = out_state;
  2108. while (charat() != -1) {
  2109. if (last != '\\' && charat() == terminator) {
  2110. paint(1, color);
  2111. return bash_pop_state(state->state);
  2112. } else if (last == '\\') {
  2113. paint(1, color);
  2114. last = -1;
  2115. } else if (terminator != '`' && charat() == '`') {
  2116. paint(1, FLAG_ESCAPE);
  2117. state->state = bash_paint_string(state,'`',bash_push_state(out_state, 20),FLAG_ESCAPE);
  2118. } else if (terminator != ')' && charat() == '$' && nextchar() == '(') {
  2119. paint(2, FLAG_TYPE);
  2120. state->state = bash_paint_string(state,')',bash_push_state(out_state, 30),FLAG_TYPE);
  2121. } else if (charat() == '$' && nextchar() == '{') {
  2122. paint(2, FLAG_NUMERAL);
  2123. bash_paint_braced_variable(state);
  2124. } else if (charat() == '$') {
  2125. paint(1, FLAG_NUMERAL);
  2126. if (bash_special_variable(charat())) { paint(1, FLAG_NUMERAL); continue; }
  2127. while (c_keyword_qualifier(charat())) paint(1, FLAG_NUMERAL);
  2128. } else if (terminator != '"' && charat() == '"') {
  2129. paint(1, FLAG_STRING);
  2130. state->state = bash_paint_string(state,'"',bash_push_state(out_state, 40),FLAG_STRING);
  2131. } else if (terminator != '"' && charat() == '\'') { /* No single quotes in regular quotes */
  2132. paint(1, FLAG_STRING);
  2133. state->state = bash_paint_tick(state, out_state);
  2134. } else if (charat() != -1) {
  2135. last = charat();
  2136. paint(1, color);
  2137. }
  2138. }
  2139. return state->state;
  2140. }
  2141. static int syn_bash_calculate(struct syntax_state * state) {
  2142. if (state->state < 1) {
  2143. if (charat() == '#') {
  2144. while (charat() != -1) paint(1, FLAG_COMMENT);
  2145. return -1;
  2146. } else if (charat() == '\'') {
  2147. paint(1, FLAG_STRING);
  2148. return bash_paint_tick(state, 10);
  2149. } else if (charat() == '`') {
  2150. paint(1, FLAG_ESCAPE);
  2151. return bash_paint_string(state,'`',20,FLAG_ESCAPE);
  2152. } else if (charat() == '$' && nextchar() == '(') {
  2153. paint(2, FLAG_TYPE);
  2154. return bash_paint_string(state,')',30,FLAG_TYPE);
  2155. } else if (charat() == '"') {
  2156. paint(1, FLAG_STRING);
  2157. return bash_paint_string(state,'"',40,FLAG_STRING);
  2158. } else if (charat() == '$' && nextchar() == '{') {
  2159. paint(2, FLAG_NUMERAL);
  2160. bash_paint_braced_variable(state);
  2161. return 0;
  2162. } else if (charat() == '$') {
  2163. paint(1, FLAG_NUMERAL);
  2164. if (bash_special_variable(charat())) { paint(1, FLAG_NUMERAL); return 0; }
  2165. while (c_keyword_qualifier(charat())) paint(1, FLAG_NUMERAL);
  2166. return 0;
  2167. } else if (find_keywords(state, syn_bash_keywords, FLAG_KEYWORD, c_keyword_qualifier)) {
  2168. return 0;
  2169. } else if (charat() == ';') {
  2170. paint(1, FLAG_KEYWORD);
  2171. return 0;
  2172. } else if (c_keyword_qualifier(charat())) {
  2173. for (int i = 0; charrel(i) != -1; ++i) {
  2174. if (charrel(i) == ' ') break;
  2175. if (charrel(i) == '=') {
  2176. for (int j = 0; j < i; ++j) {
  2177. paint(1, FLAG_TYPE);
  2178. }
  2179. skip(); /* equals sign */
  2180. return 0;
  2181. }
  2182. }
  2183. for (int i = 0; charrel(i) != -1; ++i) {
  2184. if (charrel(i) == '(') {
  2185. for (int j = 0; j < i; ++j) {
  2186. paint(1, FLAG_TYPE);
  2187. }
  2188. return 0;
  2189. }
  2190. if (!c_keyword_qualifier(charrel(i)) && charrel(i) != '-' && charrel(i) != ' ') break;
  2191. }
  2192. skip();
  2193. return 0;
  2194. } else if (charat() != -1) {
  2195. skip();
  2196. return 0;
  2197. }
  2198. } else if (state->state < 10) {
  2199. /*
  2200. * TODO: I have an idea of how to do up to `n` (here... 8?) heredocs
  2201. * by storing them in a static table and using the index into that table
  2202. * for the state, but it's iffy. It would work well in situations where
  2203. * someoen used the same heredoc repeatedly throughout their document.
  2204. */
  2205. } else if (state->state >= 10) {
  2206. /* Nested string states */
  2207. while (charat() != -1) {
  2208. int s = (state->state / 10) % 10;
  2209. if (s == 1) {
  2210. state->state = bash_paint_string(state,'\'',state->state,FLAG_STRING);
  2211. } else if (s == 2) {
  2212. state->state = bash_paint_string(state,'`',state->state,FLAG_ESCAPE);
  2213. } else if (s == 3) {
  2214. state->state = bash_paint_string(state,')',state->state,FLAG_TYPE);
  2215. } else if (s == 4) {
  2216. state->state = bash_paint_string(state,'"',state->state,FLAG_STRING);
  2217. }
  2218. }
  2219. return state->state;
  2220. }
  2221. return -1;
  2222. }
  2223. static char * bash_ext[] = {
  2224. #ifndef __toaru__
  2225. ".sh",
  2226. #endif
  2227. ".bash",".bashrc",
  2228. NULL
  2229. };
  2230. struct syntax_definition {
  2231. char * name;
  2232. char ** ext;
  2233. int (*calculate)(struct syntax_state *);
  2234. int prefers_spaces;
  2235. } syntaxes[] = {
  2236. {"c",c_ext,syn_c_calculate,0},
  2237. {"python",py_ext,syn_py_calculate,1},
  2238. {"java",java_ext,syn_java_calculate,1},
  2239. {"diff",diff_ext,syn_diff_calculate,0},
  2240. {"conf",conf_ext,syn_conf_calculate,0},
  2241. {"rust",rust_ext,syn_rust_calculate,1},
  2242. {"bimrc",bimrc_ext,syn_bimrc_calculate,0},
  2243. {"biminfo",biminfo_ext,syn_biminfo_calculate,0},
  2244. {"gitcommit",gitcommit_ext,syn_gitcommit_calculate,0},
  2245. {"gitrebase",gitrebase_ext,syn_gitrebase_calculate,0},
  2246. {"make",make_ext,syn_make_calculate,0}, /* Definitely don't use spaces for Make */
  2247. {"markdown",markdown_ext,syn_markdown_calculate,1},
  2248. {"json",json_ext,syn_json_calculate,1},
  2249. {"xml",xml_ext,syn_xml_calculate,1},
  2250. {"protobuf",proto_ext,syn_proto_calculate,1},
  2251. {"toarush",esh_ext,syn_esh_calculate,0},
  2252. {"bash",bash_ext,syn_bash_calculate,0},
  2253. {NULL,NULL,NULL,0},
  2254. };
  2255. /**
  2256. * Calculate syntax hilighting for the given line.
  2257. */
  2258. void recalculate_syntax(line_t * line, int line_no) {
  2259. /* Clear syntax for this line first */
  2260. for (int i = 0; i < line->actual; ++i) {
  2261. line->text[i].flags = 0;
  2262. }
  2263. if (!env->syntax) return;
  2264. /* Start from the line's stored in initial state */
  2265. struct syntax_state state;
  2266. state.line = line;
  2267. state.line_no = line_no;
  2268. state.state = line->istate;
  2269. state.i = 0;
  2270. while (1) {
  2271. state.state = env->syntax->calculate(&state);
  2272. if (state.state != 0) {
  2273. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  2274. env->lines[line_no+1]->istate = state.state;
  2275. if (env->loading) return;
  2276. recalculate_syntax(env->lines[line_no+1], line_no+1);
  2277. if (line_no + 1 >= env->offset && line_no + 1 < env->offset + global_config.term_height - global_config.bottom_size - 1) {
  2278. redraw_line(line_no + 1 - env->offset, line_no + 1);
  2279. }
  2280. }
  2281. break;
  2282. }
  2283. }
  2284. }
  2285. /**
  2286. * Recalculate tab widths.
  2287. */
  2288. void recalculate_tabs(line_t * line) {
  2289. if (env->loading) return;
  2290. int j = 0;
  2291. for (int i = 0; i < line->actual; ++i) {
  2292. if (line->text[i].codepoint == '\t') {
  2293. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  2294. }
  2295. j += line->text[i].display_width;
  2296. }
  2297. }
  2298. /**
  2299. * TODO:
  2300. *
  2301. * The line editing functions should probably take a buffer_t *
  2302. * so that they can act on buffers other than the active one.
  2303. */
  2304. void recursive_history_free(history_t * root) {
  2305. if (!root->next) return;
  2306. history_t * n = root->next;
  2307. recursive_history_free(n);
  2308. switch (n->type) {
  2309. case HISTORY_REPLACE_LINE:
  2310. free(n->contents.remove_replace_line.contents);
  2311. /* fall-through */
  2312. case HISTORY_REMOVE_LINE:
  2313. free(n->contents.remove_replace_line.old_contents);
  2314. break;
  2315. default:
  2316. /* Nothing extra to free */
  2317. break;
  2318. }
  2319. free(n);
  2320. root->next = NULL;
  2321. }
  2322. #define HIST_APPEND(e) do { \
  2323. if (env->history) { \
  2324. e->previous = env->history; \
  2325. recursive_history_free(env->history); \
  2326. env->history->next = e; \
  2327. e->next = NULL; \
  2328. } \
  2329. env->history = e; \
  2330. } while (0)
  2331. /**
  2332. * Mark a point where a complete set of actions has ended.
  2333. */
  2334. void set_history_break(void) {
  2335. if (!global_config.history_enabled) return;
  2336. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  2337. history_t * e = malloc(sizeof(history_t));
  2338. e->type = HISTORY_BREAK;
  2339. HIST_APPEND(e);
  2340. }
  2341. }
  2342. /**
  2343. * Insert a character into an existing line.
  2344. */
  2345. line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  2346. if (!env->loading && global_config.history_enabled) {
  2347. history_t * e = malloc(sizeof(history_t));
  2348. e->type = HISTORY_INSERT;
  2349. e->contents.insert_delete_replace.lineno = lineno;
  2350. e->contents.insert_delete_replace.offset = offset;
  2351. e->contents.insert_delete_replace.codepoint = c.codepoint;
  2352. HIST_APPEND(e);
  2353. }
  2354. /* If there is not enough space... */
  2355. if (line->actual == line->available) {
  2356. /* Expand the line buffer */
  2357. if (line->available == 0) {
  2358. line->available = 8;
  2359. } else {
  2360. line->available *= 2;
  2361. }
  2362. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  2363. }
  2364. /* If this was not the last character, then shift remaining characters forward. */
  2365. if (offset < line->actual) {
  2366. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  2367. }
  2368. /* Insert the new character */
  2369. line->text[offset] = c;
  2370. /* There is one new character in the line */
  2371. line->actual += 1;
  2372. if (!env->loading) {
  2373. line->rev_status = 2; /* Modified */
  2374. recalculate_tabs(line);
  2375. recalculate_syntax(line, lineno);
  2376. }
  2377. return line;
  2378. }
  2379. /**
  2380. * Delete a character from a line
  2381. */
  2382. void line_delete(line_t * line, int offset, int lineno) {
  2383. /* Can't delete character before start of line. */
  2384. if (offset == 0) return;
  2385. if (!env->loading && global_config.history_enabled) {
  2386. history_t * e = malloc(sizeof(history_t));
  2387. e->type = HISTORY_DELETE;
  2388. e->contents.insert_delete_replace.lineno = lineno;
  2389. e->contents.insert_delete_replace.offset = offset;
  2390. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  2391. HIST_APPEND(e);
  2392. }
  2393. /* If this isn't the last character, we need to move all subsequent characters backwards */
  2394. if (offset < line->actual) {
  2395. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  2396. }
  2397. /* The line is one character shorter */
  2398. line->actual -= 1;
  2399. line->rev_status = 2;
  2400. recalculate_tabs(line);
  2401. recalculate_syntax(line, lineno);
  2402. }
  2403. /**
  2404. * Replace a character in a line
  2405. */
  2406. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  2407. if (!env->loading && global_config.history_enabled) {
  2408. history_t * e = malloc(sizeof(history_t));
  2409. e->type = HISTORY_REPLACE;
  2410. e->contents.insert_delete_replace.lineno = lineno;
  2411. e->contents.insert_delete_replace.offset = offset;
  2412. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  2413. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  2414. HIST_APPEND(e);
  2415. }
  2416. line->text[offset] = _c;
  2417. if (!env->loading) {
  2418. line->rev_status = 2; /* Modified */
  2419. recalculate_tabs(line);
  2420. recalculate_syntax(line, lineno);
  2421. }
  2422. }
  2423. /**
  2424. * Remove a line from the active buffer
  2425. */
  2426. line_t ** remove_line(line_t ** lines, int offset) {
  2427. /* If there is only one line, clear it instead of removing it. */
  2428. if (env->line_count == 1) {
  2429. while (lines[offset]->actual > 0) {
  2430. line_delete(lines[offset], lines[offset]->actual, offset);
  2431. }
  2432. return lines;
  2433. }
  2434. if (!env->loading && global_config.history_enabled) {
  2435. history_t * e = malloc(sizeof(history_t));
  2436. e->type = HISTORY_REMOVE_LINE;
  2437. e->contents.remove_replace_line.lineno = offset;
  2438. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2439. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2440. HIST_APPEND(e);
  2441. }
  2442. /* Otherwise, free the data used by the line */
  2443. free(lines[offset]);
  2444. /* Move other lines up */
  2445. if (offset < env->line_count-1) {
  2446. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  2447. lines[env->line_count-1] = NULL;
  2448. }
  2449. /* There is one less line */
  2450. env->line_count -= 1;
  2451. return lines;
  2452. }
  2453. /**
  2454. * Add a new line to the active buffer.
  2455. */
  2456. line_t ** add_line(line_t ** lines, int offset) {
  2457. /* Invalid offset? */
  2458. if (offset > env->line_count) return lines;
  2459. if (!env->loading && global_config.history_enabled) {
  2460. history_t * e = malloc(sizeof(history_t));
  2461. e->type = HISTORY_ADD_LINE;
  2462. e->contents.add_merge_split_lines.lineno = offset;
  2463. HIST_APPEND(e);
  2464. }
  2465. /* Not enough space */
  2466. if (env->line_count == env->line_avail) {
  2467. /* Allocate more space */
  2468. env->line_avail *= 2;
  2469. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  2470. }
  2471. /* If this isn't the last line, move other lines down */
  2472. if (offset < env->line_count) {
  2473. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  2474. }
  2475. /* Allocate the new line */
  2476. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  2477. lines[offset]->available = 32;
  2478. /* There is one new line */
  2479. env->line_count += 1;
  2480. env->lines = lines;
  2481. if (!env->loading) {
  2482. lines[offset]->rev_status = 2; /* Modified */
  2483. }
  2484. if (offset > 0 && !env->loading) {
  2485. recalculate_syntax(lines[offset-1],offset-1);
  2486. }
  2487. return lines;
  2488. }
  2489. /**
  2490. * Replace a line with data from another line (used by paste to paste yanked lines)
  2491. */
  2492. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  2493. if (!env->loading && global_config.history_enabled) {
  2494. history_t * e = malloc(sizeof(history_t));
  2495. e->type = HISTORY_REPLACE_LINE;
  2496. e->contents.remove_replace_line.lineno = offset;
  2497. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2498. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  2499. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  2500. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  2501. HIST_APPEND(e);
  2502. }
  2503. if (lines[offset]->available < replacement->actual) {
  2504. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  2505. lines[offset]->available = replacement->available;
  2506. }
  2507. lines[offset]->actual = replacement->actual;
  2508. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  2509. if (!env->loading) {
  2510. lines[offset]->rev_status = 2;
  2511. recalculate_syntax(lines[offset],offset);
  2512. }
  2513. }
  2514. /**
  2515. * Merge two consecutive lines.
  2516. * lineb is the offset of the second line.
  2517. */
  2518. line_t ** merge_lines(line_t ** lines, int lineb) {
  2519. /* linea is the line immediately before lineb */
  2520. int linea = lineb - 1;
  2521. if (!env->loading && global_config.history_enabled) {
  2522. history_t * e = malloc(sizeof(history_t));
  2523. e->type = HISTORY_MERGE_LINES;
  2524. e->contents.add_merge_split_lines.lineno = lineb;
  2525. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  2526. HIST_APPEND(e);
  2527. }
  2528. /* If there isn't enough space in linea hold both... */
  2529. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  2530. /* ... allocate more space until it fits */
  2531. if (lines[linea]->available == 0) {
  2532. lines[linea]->available = 8;
  2533. } else {
  2534. lines[linea]->available *= 2;
  2535. }
  2536. /* XXX why not just do this once after calculating appropriate size */
  2537. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  2538. }
  2539. /* Copy the second line into the first line */
  2540. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  2541. /* The first line is now longer */
  2542. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  2543. if (!env->loading) {
  2544. lines[linea]->rev_status = 2;
  2545. recalculate_tabs(lines[linea]);
  2546. recalculate_syntax(lines[linea], linea);
  2547. }
  2548. /* Remove the second line */
  2549. free(lines[lineb]);
  2550. /* Move other lines up */
  2551. if (lineb < env->line_count) {
  2552. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  2553. lines[env->line_count-1] = NULL;
  2554. }
  2555. /* There is one less line */
  2556. env->line_count -= 1;
  2557. return lines;
  2558. }
  2559. /**
  2560. * Split a line into two lines at the given column
  2561. */
  2562. line_t ** split_line(line_t ** lines, int line, int split) {
  2563. /* If we're trying to split from the start, just add a new blank line before */
  2564. if (split == 0) {
  2565. return add_line(lines, line);
  2566. }
  2567. if (!env->loading && global_config.history_enabled) {
  2568. history_t * e = malloc(sizeof(history_t));
  2569. e->type = HISTORY_SPLIT_LINE;
  2570. e->contents.add_merge_split_lines.lineno = line;
  2571. e->contents.add_merge_split_lines.split = split;
  2572. HIST_APPEND(e);
  2573. }
  2574. /* Allocate more space as needed */
  2575. if (env->line_count == env->line_avail) {
  2576. env->line_avail *= 2;
  2577. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  2578. }
  2579. /* Shift later lines down */
  2580. if (line < env->line_count) {
  2581. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  2582. }
  2583. /* I have no idea what this is doing */
  2584. int remaining = lines[line]->actual - split;
  2585. int v = remaining;
  2586. v--;
  2587. v |= v >> 1;
  2588. v |= v >> 2;
  2589. v |= v >> 4;
  2590. v |= v >> 8;
  2591. v |= v >> 16;
  2592. v++;
  2593. /* Allocate space for the new line */
  2594. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  2595. lines[line+1]->available = v;
  2596. lines[line+1]->actual = remaining;
  2597. /* Move the data from the old line into the new line */
  2598. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  2599. lines[line]->actual = split;
  2600. if (!env->loading) {
  2601. lines[line]->rev_status = 2;
  2602. lines[line+1]->rev_status = 2;
  2603. recalculate_tabs(lines[line]);
  2604. recalculate_tabs(lines[line+1]);
  2605. recalculate_syntax(lines[line], line);
  2606. recalculate_syntax(lines[line+1], line+1);
  2607. }
  2608. /* There is one new line */
  2609. env->line_count += 1;
  2610. /* We may have reallocated lines */
  2611. return lines;
  2612. }
  2613. /**
  2614. * Understand spaces and comments and check if the previous line
  2615. * ended with a brace or a colon.
  2616. */
  2617. int line_ends_with_brace(line_t * line) {
  2618. int i = line->actual-1;
  2619. while (i >= 0) {
  2620. if ((line->text[i].flags & 0xF) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  2621. i--;
  2622. } else {
  2623. break;
  2624. }
  2625. }
  2626. if (i < 0) return 0;
  2627. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':');
  2628. }
  2629. int line_is_comment(line_t * line) {
  2630. if (!env->syntax) return 0;
  2631. if (!strcmp(env->syntax->name,"c")) {
  2632. if (line->istate == 1) return 1;
  2633. } else if (!strcmp(env->syntax->name,"java")) {
  2634. if (line->istate == 1) return 1;
  2635. } else if (!strcmp(env->syntax->name,"rust")) {
  2636. if (line->istate > 0) return 1;
  2637. }
  2638. return 0;
  2639. }
  2640. /**
  2641. * Add indentation from the previous (temporally) line
  2642. */
  2643. void add_indent(int new_line, int old_line, int ignore_brace) {
  2644. if (env->indent) {
  2645. int changed = 0;
  2646. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  2647. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2648. if (env->lines[old_line]->text[i].codepoint == '/') {
  2649. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  2650. /* Insert ' * ' */
  2651. char_t space = {1,FLAG_COMMENT,' '};
  2652. char_t asterisk = {1,FLAG_COMMENT,'*'};
  2653. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  2654. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  2655. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  2656. env->col_no += 3;
  2657. }
  2658. break;
  2659. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  2660. /* Insert ' * ' */
  2661. char_t space = {1,FLAG_COMMENT,' '};
  2662. char_t asterisk = {1,FLAG_COMMENT,'*'};
  2663. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  2664. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  2665. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  2666. env->col_no += 3;
  2667. break;
  2668. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  2669. env->lines[old_line]->text[i].codepoint == '\t' ||
  2670. env->lines[old_line]->text[i].codepoint == '*') {
  2671. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  2672. env->col_no++;
  2673. changed = 1;
  2674. } else {
  2675. break;
  2676. }
  2677. }
  2678. } else {
  2679. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2680. if (old_line < new_line && i == env->lines[old_line]->actual - 3 &&
  2681. env->lines[old_line]->text[i].codepoint == ' ' &&
  2682. env->lines[old_line]->text[i+1].codepoint == '*' &&
  2683. env->lines[old_line]->text[i+2].codepoint == '/') {
  2684. break;
  2685. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  2686. env->lines[old_line]->text[i].codepoint == '\t') {
  2687. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  2688. env->col_no++;
  2689. changed = 1;
  2690. } else {
  2691. break;
  2692. }
  2693. }
  2694. }
  2695. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  2696. if (env->tabs) {
  2697. char_t c;
  2698. c.codepoint = '\t';
  2699. c.display_width = env->tabstop;
  2700. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  2701. env->col_no++;
  2702. changed = 1;
  2703. } else {
  2704. for (int j = 0; j < env->tabstop; ++j) {
  2705. char_t c;
  2706. c.codepoint = ' ';
  2707. c.display_width = 1;
  2708. c.flags = FLAG_SELECT;
  2709. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  2710. env->col_no++;
  2711. }
  2712. changed = 1;
  2713. }
  2714. }
  2715. int was_whitespace = 1;
  2716. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  2717. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  2718. env->lines[old_line]->text[i].codepoint != '\t') {
  2719. was_whitespace = 0;
  2720. break;
  2721. }
  2722. }
  2723. if (was_whitespace) {
  2724. while (env->lines[old_line]->actual) {
  2725. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  2726. }
  2727. }
  2728. if (changed) {
  2729. recalculate_syntax(env->lines[new_line],new_line);
  2730. }
  2731. }
  2732. }
  2733. /**
  2734. * Initialize a buffer with default values
  2735. */
  2736. void setup_buffer(buffer_t * env) {
  2737. /* If this buffer was already initialized, clear out its line data */
  2738. if (env->lines) {
  2739. for (int i = 0; i < env->line_count; ++i) {
  2740. free(env->lines[i]);
  2741. }
  2742. free(env->lines);
  2743. }
  2744. /* Default state parameters */
  2745. env->line_no = 1; /* Default cursor position */
  2746. env->col_no = 1;
  2747. env->line_count = 1; /* Buffers always have at least one line */
  2748. env->modified = 0;
  2749. env->readonly = 0;
  2750. env->offset = 0;
  2751. env->line_avail = 8; /* Default line buffer capacity */
  2752. env->tabs = 1; /* Tabs by default */
  2753. env->tabstop = 4; /* Tab stop width */
  2754. env->indent = 1; /* Auto-indent by default */
  2755. env->history = malloc(sizeof(struct history));
  2756. memset(env->history, 0, sizeof(struct history));
  2757. env->last_save_history = env->history;
  2758. /* Allocate line buffer */
  2759. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  2760. /* Initialize the first line */
  2761. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  2762. env->lines[0]->available = 32;
  2763. }
  2764. /**
  2765. * Toggle buffered / unbuffered modes
  2766. */
  2767. struct termios old;
  2768. void get_initial_termios(void) {
  2769. tcgetattr(STDOUT_FILENO, &old);
  2770. }
  2771. void set_unbuffered(void) {
  2772. struct termios new = old;
  2773. new.c_iflag &= (~ICRNL);
  2774. new.c_lflag &= (~ICANON) & (~ECHO);
  2775. new.c_cc[VINTR] = 0;
  2776. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  2777. }
  2778. void set_buffered(void) {
  2779. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  2780. }
  2781. /**
  2782. * Convert codepoint to utf-8 string
  2783. */
  2784. int to_eight(uint32_t codepoint, char * out) {
  2785. memset(out, 0x00, 7);
  2786. if (codepoint < 0x0080) {
  2787. out[0] = (char)codepoint;
  2788. } else if (codepoint < 0x0800) {
  2789. out[0] = 0xC0 | (codepoint >> 6);
  2790. out[1] = 0x80 | (codepoint & 0x3F);
  2791. } else if (codepoint < 0x10000) {
  2792. out[0] = 0xE0 | (codepoint >> 12);
  2793. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  2794. out[2] = 0x80 | (codepoint & 0x3F);
  2795. } else if (codepoint < 0x200000) {
  2796. out[0] = 0xF0 | (codepoint >> 18);
  2797. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  2798. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  2799. out[3] = 0x80 | ((codepoint) & 0x3F);
  2800. } else if (codepoint < 0x4000000) {
  2801. out[0] = 0xF8 | (codepoint >> 24);
  2802. out[1] = 0x80 | (codepoint >> 18);
  2803. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  2804. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  2805. out[4] = 0x80 | ((codepoint) & 0x3F);
  2806. } else {
  2807. out[0] = 0xF8 | (codepoint >> 30);
  2808. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  2809. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  2810. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  2811. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  2812. out[5] = 0x80 | ((codepoint) & 0x3F);
  2813. }
  2814. return strlen(out);
  2815. }
  2816. /**
  2817. * Get the presentation width of a codepoint
  2818. */
  2819. int codepoint_width(wchar_t codepoint) {
  2820. if (codepoint == '\t') {
  2821. return 1; /* Recalculate later */
  2822. }
  2823. if (codepoint < 32) {
  2824. /* We render these as ^@ */
  2825. return 2;
  2826. }
  2827. if (codepoint == 0x7F) {
  2828. /* Renders as ^? */
  2829. return 2;
  2830. }
  2831. if (codepoint > 0x7f && codepoint < 0xa0) {
  2832. /* Upper control bytes <xx> */
  2833. return 4;
  2834. }
  2835. if (codepoint == 0xa0) {
  2836. /* Non-breaking space _ */
  2837. return 1;
  2838. }
  2839. /* Skip wcwidth for anything under 256 */
  2840. if (codepoint > 256) {
  2841. if (global_config.can_unicode) {
  2842. /* Higher codepoints may be wider (eg. Japanese) */
  2843. int out = wcwidth(codepoint);
  2844. if (out >= 1) return out;
  2845. }
  2846. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  2847. return (codepoint < 0x10000) ? 8 : 10;
  2848. }
  2849. return 1;
  2850. }
  2851. /**
  2852. * Move the terminal cursor
  2853. */
  2854. void place_cursor(int x, int y) {
  2855. printf("\033[%d;%dH", y, x);
  2856. fflush(stdout);
  2857. }
  2858. /**
  2859. * Set text colors
  2860. *
  2861. * Normally, text colors are just strings, but if they
  2862. * start with @ they will be parsed as integers
  2863. * representing one of the 16 standard colors, suitable
  2864. * for terminals without support for the 256- or 24-bit
  2865. * color modes.
  2866. */
  2867. void set_colors(const char * fg, const char * bg) {
  2868. printf("\033[22;23;24;");
  2869. if (*bg == '@') {
  2870. int _bg = atoi(bg+1);
  2871. if (_bg < 10) {
  2872. printf("4%d;", _bg);
  2873. } else {
  2874. printf("10%d;", _bg-10);
  2875. }
  2876. } else {
  2877. printf("48;%s;", bg);
  2878. }
  2879. if (*fg == '@') {
  2880. int _fg = atoi(fg+1);
  2881. if (_fg < 10) {
  2882. printf("3%dm", _fg);
  2883. } else {
  2884. printf("9%dm", _fg-10);
  2885. }
  2886. } else {
  2887. printf("38;%sm", fg);
  2888. }
  2889. fflush(stdout);
  2890. }
  2891. /**
  2892. * Set just the foreground color
  2893. *
  2894. * (See set_colors above)
  2895. */
  2896. void set_fg_color(const char * fg) {
  2897. printf("\033[22;23;24;");
  2898. if (*fg == '@') {
  2899. int _fg = atoi(fg+1);
  2900. if (_fg < 10) {
  2901. printf("3%dm", _fg);
  2902. } else {
  2903. printf("9%dm", _fg-10);
  2904. }
  2905. } else {
  2906. printf("38;%sm", fg);
  2907. }
  2908. fflush(stdout);
  2909. }
  2910. /**
  2911. * Clear the rest of this line
  2912. */
  2913. void clear_to_end(void) {
  2914. if (global_config.can_bce) {
  2915. printf("\033[K");
  2916. fflush(stdout);
  2917. }
  2918. }
  2919. /**
  2920. * For terminals without bce,
  2921. * prepaint the whole line, so we don't have to track
  2922. * where the cursor is for everything. Inefficient,
  2923. * but effective.
  2924. */
  2925. void paint_line(const char * bg) {
  2926. if (!global_config.can_bce) {
  2927. set_colors(COLOR_FG, bg);
  2928. for (int i = 0; i < global_config.term_width; ++i) {
  2929. printf(" ");
  2930. }
  2931. printf("\r");
  2932. }
  2933. }
  2934. /**
  2935. * Enable bold text display
  2936. */
  2937. void set_bold(void) {
  2938. printf("\033[1m");
  2939. fflush(stdout);
  2940. }
  2941. /**
  2942. * Disable bold
  2943. */
  2944. void unset_bold(void) {
  2945. printf("\033[22m");
  2946. fflush(stdout);
  2947. }
  2948. /**
  2949. * Enable underlined text display
  2950. */
  2951. void set_underline(void) {
  2952. printf("\033[4m");
  2953. fflush(stdout);
  2954. }
  2955. /**
  2956. * Disable underlined text display
  2957. */
  2958. void unset_underline(void) {
  2959. printf("\033[24m");
  2960. fflush(stdout);
  2961. }
  2962. /**
  2963. * Reset text display attributes
  2964. */
  2965. void reset(void) {
  2966. printf("\033[0m");
  2967. fflush(stdout);
  2968. }
  2969. /**
  2970. * Clear the entire screen
  2971. */
  2972. void clear_screen(void) {
  2973. printf("\033[H\033[2J");
  2974. fflush(stdout);
  2975. }
  2976. /**
  2977. * Hide the cursor
  2978. */
  2979. void hide_cursor(void) {
  2980. if (global_config.can_hideshow) {
  2981. printf("\033[?25l");
  2982. }
  2983. fflush(stdout);
  2984. }
  2985. /**
  2986. * Show the cursor
  2987. */
  2988. void show_cursor(void) {
  2989. if (global_config.can_hideshow) {
  2990. printf("\033[?25h");
  2991. }
  2992. fflush(stdout);
  2993. }
  2994. /**
  2995. * Request mouse events
  2996. */
  2997. void mouse_enable(void) {
  2998. if (global_config.can_mouse) {
  2999. printf("\033[?1000h");
  3000. }
  3001. fflush(stdout);
  3002. }
  3003. /**
  3004. * Stop mouse events
  3005. */
  3006. void mouse_disable(void) {
  3007. if (global_config.can_mouse) {
  3008. printf("\033[?1000l");
  3009. }
  3010. fflush(stdout);
  3011. }
  3012. /**
  3013. * Shift the screen up one line
  3014. */
  3015. void shift_up(void) {
  3016. printf("\033[1S");
  3017. }
  3018. /**
  3019. * Shift the screen down one line.
  3020. */
  3021. void shift_down(void) {
  3022. printf("\033[1T");
  3023. }
  3024. /**
  3025. * Switch to the alternate terminal screen.
  3026. */
  3027. void set_alternate_screen(void) {
  3028. if (global_config.can_altscreen) {
  3029. printf("\033[?1049h");
  3030. }
  3031. }
  3032. /**
  3033. * Restore the standard terminal screen.
  3034. */
  3035. void unset_alternate_screen(void) {
  3036. if (global_config.can_altscreen) {
  3037. printf("\033[?1049l");
  3038. }
  3039. }
  3040. char * file_basename(char * file) {
  3041. char * c = strrchr(file, '/');
  3042. if (!c) return file;
  3043. return (c+1);
  3044. }
  3045. int draw_tab_name(buffer_t * _env, char * out) {
  3046. return sprintf(out, "%s %.40s ",
  3047. _env->modified ? " +" : "",
  3048. _env->file_name ? file_basename(_env->file_name) : "[No Name]");
  3049. }
  3050. /**
  3051. * Redaw the tabbar, with a tab for each buffer.
  3052. *
  3053. * The active buffer is highlighted.
  3054. */
  3055. void redraw_tabbar(void) {
  3056. /* Hide cursor while rendering UI */
  3057. hide_cursor();
  3058. /* Move to upper left */
  3059. place_cursor(1,1);
  3060. paint_line(COLOR_TABBAR_BG);
  3061. /* For each buffer... */
  3062. int offset = 0;
  3063. for (int i = 0; i < buffers_len; i++) {
  3064. buffer_t * _env = buffers[i];
  3065. if (_env == env) {
  3066. /* If this is the active buffer, hilight it */
  3067. reset();
  3068. set_colors(COLOR_FG, COLOR_BG);
  3069. set_bold();
  3070. } else {
  3071. /* Otherwise use default tab color */
  3072. reset();
  3073. set_colors(COLOR_FG, COLOR_TAB_BG);
  3074. set_underline();
  3075. }
  3076. char title[64];
  3077. int size = draw_tab_name(_env, title);
  3078. if (offset + size >= global_config.term_width) {
  3079. if (global_config.term_width - offset - 1 > 0) {
  3080. printf("%*s", global_config.term_width - offset - 1, title);
  3081. }
  3082. break;
  3083. } else {
  3084. printf("%s", title);
  3085. }
  3086. offset += size;
  3087. }
  3088. /* Reset bold/underline */
  3089. reset();
  3090. /* Fill the rest of the tab bar */
  3091. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  3092. clear_to_end();
  3093. }
  3094. /**
  3095. * Braindead log10 implementation for the line numbers
  3096. */
  3097. int log_base_10(unsigned int v) {
  3098. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  3099. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  3100. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  3101. return r;
  3102. }
  3103. /**
  3104. * Render a line of text
  3105. *
  3106. * This handles rendering the actual text content. A full line of text
  3107. * also includes a line number and some padding.
  3108. *
  3109. * width: width of the text display region (term width - line number width)
  3110. * offset: how many cells into the line to start rendering at
  3111. */
  3112. void render_line(line_t * line, int width, int offset, int line_no) {
  3113. int i = 0; /* Offset in char_t line data entries */
  3114. int j = 0; /* Offset in terminal cells */
  3115. const char * last_color = NULL;
  3116. int was_selecting = 0, was_searching = 0;
  3117. /* Set default text colors */
  3118. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  3119. /*
  3120. * When we are rendering in the middle of a wide character,
  3121. * we render -'s to fill the remaining amount of the
  3122. * charater's width
  3123. */
  3124. int remainder = 0;
  3125. /* For each character in the line ... */
  3126. while (i < line->actual) {
  3127. /* If there is remaining text... */
  3128. if (remainder) {
  3129. /* If we should be drawing by now... */
  3130. if (j >= offset) {
  3131. /* Fill remainder with -'s */
  3132. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3133. printf("-");
  3134. set_colors(COLOR_FG, COLOR_BG);
  3135. }
  3136. /* One less remaining width cell to fill */
  3137. remainder--;
  3138. /* Terminal offset moves forward */
  3139. j++;
  3140. /*
  3141. * If this was the last remaining character, move to
  3142. * the next codepoint in the line
  3143. */
  3144. if (remainder == 0) {
  3145. i++;
  3146. }
  3147. continue;
  3148. }
  3149. /* Get the next character to draw */
  3150. char_t c = line->text[i];
  3151. /* If we should be drawing by now... */
  3152. if (j >= offset) {
  3153. /* If this character is going to fall off the edge of the screen... */
  3154. if (j - offset + c.display_width >= width) {
  3155. /* We draw this with special colors so it isn't ambiguous */
  3156. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3157. /* If it's wide, draw ---> as needed */
  3158. while (j - offset < width - 1) {
  3159. printf("-");
  3160. j++;
  3161. }
  3162. /* End the line with a > to show it overflows */
  3163. printf(">");
  3164. set_colors(COLOR_FG, COLOR_BG);
  3165. return;
  3166. }
  3167. /* Syntax hilighting */
  3168. const char * color = flag_to_color(c.flags);
  3169. if (c.flags & FLAG_SELECT) {
  3170. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3171. was_selecting = 1;
  3172. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  3173. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  3174. was_searching = 1;
  3175. } else {
  3176. if (was_selecting || was_searching) {
  3177. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  3178. last_color = color;
  3179. } else if (!last_color || strcmp(color, last_color)) {
  3180. set_fg_color(color);
  3181. last_color = color;
  3182. }
  3183. }
  3184. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  3185. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  3186. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  3187. ((j == env->sel_col) ||
  3188. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  3189. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3190. was_selecting = 1;
  3191. }
  3192. #define _set_colors(fg,bg) \
  3193. if (!(c.flags & FLAG_SELECT) && !(was_selecting)) { \
  3194. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  3195. }
  3196. /* Render special characters */
  3197. if (c.codepoint == '\t') {
  3198. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3199. if (global_config.can_unicode) {
  3200. printf("»");
  3201. for (int i = 1; i < c.display_width; ++i) {
  3202. printf("·");
  3203. }
  3204. } else {
  3205. printf(">");
  3206. for (int i = 1; i < c.display_width; ++i) {
  3207. printf("-");
  3208. }
  3209. }
  3210. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3211. } else if (c.codepoint < 32) {
  3212. /* Codepoints under 32 to get converted to ^@ escapes */
  3213. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3214. printf("^%c", '@' + c.codepoint);
  3215. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3216. } else if (c.codepoint == 0x7f) {
  3217. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3218. printf("^?");
  3219. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3220. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  3221. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3222. printf("<%2x>", c.codepoint);
  3223. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3224. } else if (c.codepoint == 0xa0) {
  3225. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3226. printf("_");
  3227. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3228. } else if (c.display_width == 8) {
  3229. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3230. printf("[U+%04x]", c.codepoint);
  3231. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3232. } else if (c.display_width == 10) {
  3233. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3234. printf("[U+%06x]", c.codepoint);
  3235. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  3236. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  3237. /* Special case: space at end of line */
  3238. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3239. printf("·");
  3240. _set_colors(COLOR_FG, COLOR_BG);
  3241. } else {
  3242. /* Normal characters get output */
  3243. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  3244. to_eight(c.codepoint, tmp);
  3245. printf("%s", tmp);
  3246. }
  3247. /* Advance the terminal cell offset by the render width of this character */
  3248. j += c.display_width;
  3249. /* Advance to the next character */
  3250. i++;
  3251. } else if (c.display_width > 1) {
  3252. /*
  3253. * If this is a wide character but we aren't ready to render yet,
  3254. * we may need to draw some filler text for the remainder of its
  3255. * width to ensure we don't jump around when horizontally scrolling
  3256. * past wide characters.
  3257. */
  3258. remainder = c.display_width - 1;
  3259. j++;
  3260. } else {
  3261. /* Regular character, not ready to draw, advance without doing anything */
  3262. j++;
  3263. i++;
  3264. }
  3265. }
  3266. if (env->mode != MODE_LINE_SELECTION) {
  3267. if (line->is_current) {
  3268. set_colors(COLOR_FG, COLOR_ALT_BG);
  3269. } else {
  3270. set_colors(COLOR_FG, COLOR_BG);
  3271. }
  3272. } else {
  3273. if (!line->actual) {
  3274. if (env->line_no == line_no ||
  3275. (env->start_line > env->line_no &&
  3276. (line_no >= env->line_no && line_no <= env->start_line)) ||
  3277. (env->start_line < env->line_no &&
  3278. (line_no >= env->start_line && line_no <= env->line_no))) {
  3279. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3280. }
  3281. }
  3282. }
  3283. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  3284. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  3285. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  3286. j <= env->sel_col &&
  3287. env->sel_col < width) {
  3288. set_colors(COLOR_FG, COLOR_BG);
  3289. while (j < env->sel_col) {
  3290. printf(" ");
  3291. j++;
  3292. }
  3293. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  3294. printf(" ");
  3295. j++;
  3296. set_colors(COLOR_FG, COLOR_BG);
  3297. }
  3298. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  3299. clear_to_end();
  3300. } else {
  3301. /* Paint the rest of the line */
  3302. for (; j - offset < width; ++j) {
  3303. printf(" ");
  3304. }
  3305. }
  3306. }
  3307. /**
  3308. * Get the width of the line number region
  3309. */
  3310. int num_width(void) {
  3311. int w = log_base_10(env->line_count) + 1;
  3312. if (w < 2) return 2;
  3313. return w;
  3314. }
  3315. /**
  3316. * Draw the gutter and line numbers.
  3317. */
  3318. void draw_line_number(int x) {
  3319. /* Draw the line number */
  3320. if (env->lines[x]->is_current) {
  3321. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  3322. } else {
  3323. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  3324. }
  3325. int num_size = num_width();
  3326. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  3327. printf(" ");
  3328. }
  3329. printf("%d%c", x + 1, (x+1 == env->line_no && env->coffset > 0) ? '<' : ' ');
  3330. }
  3331. /**
  3332. * Used to highlight the current line after moving the cursor.
  3333. */
  3334. void recalculate_current_line(void) {
  3335. if (!global_config.hilight_current_line) return;
  3336. for (int i = 0; i < env->line_count; ++i) {
  3337. if (env->lines[i]->is_current && i != env->line_no-1) {
  3338. env->lines[i]->is_current = 0;
  3339. if ((i) - env->offset > -1 &&
  3340. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3341. redraw_line((i) - env->offset, i);
  3342. }
  3343. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  3344. env->lines[i]->is_current = 1;
  3345. if ((i) - env->offset > -1 &&
  3346. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3347. redraw_line((i) - env->offset, i);
  3348. }
  3349. }
  3350. }
  3351. }
  3352. /**
  3353. * Redraw line.
  3354. *
  3355. * This draws the line number as well as the actual text.
  3356. * j = screen-relative line offset.
  3357. */
  3358. void redraw_line(int j, int x) {
  3359. if (env->loading) return;
  3360. /* Hide cursor when drawing */
  3361. hide_cursor();
  3362. /* Move cursor to upper left most cell of this line */
  3363. place_cursor(1 + env->left,2 + j);
  3364. /* Draw a gutter on the left. */
  3365. switch (env->lines[x]->rev_status) {
  3366. case 1:
  3367. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  3368. printf(" ");
  3369. break;
  3370. case 2:
  3371. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  3372. printf(" ");
  3373. break;
  3374. case 3:
  3375. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  3376. printf(" ");
  3377. break;
  3378. case 4:
  3379. set_colors(COLOR_ALT_FG, COLOR_RED);
  3380. printf("▆");
  3381. break;
  3382. case 5:
  3383. set_colors(COLOR_KEYWORD, COLOR_RED);
  3384. printf("▆");
  3385. break;
  3386. default:
  3387. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  3388. printf(" ");
  3389. break;
  3390. }
  3391. draw_line_number(x);
  3392. /*
  3393. * Draw the line text
  3394. * If this is the active line, the current character cell offset should be used.
  3395. * (Non-active lines are not shifted and always render from the start of the line)
  3396. */
  3397. render_line(env->lines[x], env->width - 3 - num_width(), (x + 1 == env->line_no) ? env->coffset : 0, x+1);
  3398. }
  3399. /**
  3400. * Draw a ~ line where there is no buffer text.
  3401. */
  3402. void draw_excess_line(int j) {
  3403. place_cursor(1+env->left,2 + j);
  3404. paint_line(COLOR_ALT_BG);
  3405. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  3406. printf("~");
  3407. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  3408. clear_to_end();
  3409. } else {
  3410. /* Paint the rest of the line */
  3411. for (int x = 1; x < env->width; ++x) {
  3412. printf(" ");
  3413. }
  3414. }
  3415. }
  3416. /**
  3417. * Redraw the entire text area
  3418. */
  3419. void redraw_text(void) {
  3420. /* Hide cursor while rendering */
  3421. hide_cursor();
  3422. /* Figure out the available size of the text region */
  3423. int l = global_config.term_height - global_config.bottom_size - 1;
  3424. int j = 0;
  3425. /* Draw each line */
  3426. for (int x = env->offset; j < l && x < env->line_count; x++) {
  3427. redraw_line(j,x);
  3428. j++;
  3429. }
  3430. /* Draw the rest of the text region as ~ lines */
  3431. for (; j < l; ++j) {
  3432. draw_excess_line(j);
  3433. }
  3434. }
  3435. static int view_left_offset = 0;
  3436. static int view_right_offset = 0;
  3437. void redraw_alt_buffer(buffer_t * buf) {
  3438. if (left_buffer == right_buffer) {
  3439. /* draw the opposite view */
  3440. int left, width, offset;
  3441. left = env->left;
  3442. width = env->width;
  3443. offset = env->offset;
  3444. if (left == 0) {
  3445. /* Draw the right side */
  3446. env->left = width;
  3447. env->width = global_config.term_width - width;
  3448. env->offset = view_right_offset;
  3449. view_left_offset = offset;
  3450. } else {
  3451. env->left = 0;
  3452. env->width = global_config.term_width * global_config.split_percent / 100;
  3453. env->offset = view_left_offset;
  3454. view_right_offset = offset;
  3455. }
  3456. redraw_text();
  3457. env->left = left;
  3458. env->width = width;
  3459. env->offset = offset;
  3460. }
  3461. /* Swap out active buffer */
  3462. buffer_t * tmp = env;
  3463. env = buf;
  3464. /* Redraw text */
  3465. redraw_text();
  3466. /* Return original active buffer */
  3467. env = tmp;
  3468. }
  3469. /**
  3470. * Draw the status bar
  3471. *
  3472. * The status bar shows the name of the file, whether it has modifications,
  3473. * and (in the future) what syntax highlighting mode is enabled.
  3474. *
  3475. * The right side of the tatus bar shows the line number and column.
  3476. */
  3477. void redraw_statusbar(void) {
  3478. /* Hide cursor while rendering */
  3479. hide_cursor();
  3480. /* Move cursor to the status bar line (second from bottom */
  3481. place_cursor(1, global_config.term_height - 1);
  3482. /* Set background colors for status line */
  3483. paint_line(COLOR_STATUS_BG);
  3484. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3485. /* Print the file name */
  3486. char status_bits[1024] = {0}; /* Sane maximum */
  3487. char * s = status_bits;
  3488. if (env->syntax) {
  3489. s += snprintf(s, 100, "[%s]", env->syntax->name);
  3490. }
  3491. /* Print file status indicators */
  3492. if (env->modified) {
  3493. s += snprintf(s, 5, "[+]");
  3494. }
  3495. if (env->readonly) {
  3496. s += snprintf(s, 6, "[ro]");
  3497. }
  3498. s += snprintf(s, 2, " ");
  3499. if (env->tabs) {
  3500. s += snprintf(s, 20, "[tabs]");
  3501. } else {
  3502. s += snprintf(s, 20, "[spaces=%d]", env->tabstop);
  3503. }
  3504. if (global_config.yanks) {
  3505. s += snprintf(s, 20, "[y:%ld]", global_config.yank_count);
  3506. }
  3507. if (env->indent) {
  3508. s += snprintf(s, 20, "[indent]");
  3509. }
  3510. /* Pre-render the right hand side of the status bar */
  3511. char right_hand[1024];
  3512. snprintf(right_hand, 1024, "Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  3513. if (env->file_name) {
  3514. int len = strlen(env->file_name);
  3515. int i = 0;
  3516. while (len > 5 && len > (int)global_config.term_width - (int)strlen(right_hand) - (int)strlen(status_bits) - 5) {
  3517. len--;
  3518. i += 1;
  3519. }
  3520. printf("%s%s", i > 0 ? "<" : "", env->file_name + i);
  3521. } else {
  3522. printf("[No Name]");
  3523. }
  3524. printf(" ");
  3525. printf("%s", status_bits);
  3526. /* Clear the rest of the status bar */
  3527. clear_to_end();
  3528. /* Move the cursor appropriately to draw it */
  3529. place_cursor(global_config.term_width - strlen(right_hand), global_config.term_height - 1);
  3530. /* TODO: What if we're localized and this has wide chars? */
  3531. printf("%s",right_hand);
  3532. fflush(stdout);
  3533. }
  3534. /**
  3535. * Draw the command line
  3536. *
  3537. * The command line either has input from the user (:quit, :!make, etc.)
  3538. * or shows the INSERT (or VISUAL in the future) mode name.
  3539. */
  3540. void redraw_commandline(void) {
  3541. /* Hide cursor while rendering */
  3542. hide_cursor();
  3543. /* Move cursor to the last line */
  3544. place_cursor(1, global_config.term_height);
  3545. /* Set background color */
  3546. paint_line(COLOR_BG);
  3547. set_colors(COLOR_FG, COLOR_BG);
  3548. /* If we are in an edit mode, note that. */
  3549. if (env->mode == MODE_INSERT) {
  3550. set_bold();
  3551. printf("-- INSERT --");
  3552. clear_to_end();
  3553. unset_bold();
  3554. } else if (env->mode == MODE_LINE_SELECTION) {
  3555. set_bold();
  3556. printf("-- LINE SELECTION -- (%d:%d)",
  3557. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3558. (env->start_line < env->line_no) ? env->line_no : env->start_line
  3559. );
  3560. clear_to_end();
  3561. unset_bold();
  3562. } else if (env->mode == MODE_COL_SELECTION) {
  3563. set_bold();
  3564. printf("-- COL SELECTION -- (%d:%d %d)",
  3565. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3566. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  3567. (env->sel_col)
  3568. );
  3569. clear_to_end();
  3570. unset_bold();
  3571. } else if (env->mode == MODE_COL_INSERT) {
  3572. set_bold();
  3573. printf("-- COL INSERT -- (%d:%d %d)",
  3574. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  3575. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  3576. (env->sel_col)
  3577. );
  3578. clear_to_end();
  3579. unset_bold();
  3580. } else if (env->mode == MODE_REPLACE) {
  3581. set_bold();
  3582. printf("-- REPLACE --");
  3583. clear_to_end();
  3584. unset_bold();
  3585. } else if (env->mode == MODE_CHAR_SELECTION) {
  3586. set_bold();
  3587. printf("-- CHAR SELECTION -- ");
  3588. clear_to_end();
  3589. reset();
  3590. } else {
  3591. clear_to_end();
  3592. }
  3593. }
  3594. /**
  3595. * Draw a message on the command line.
  3596. */
  3597. void render_commandline_message(char * message, ...) {
  3598. /* varargs setup */
  3599. va_list args;
  3600. va_start(args, message);
  3601. char buf[1024];
  3602. /* Process format string */
  3603. vsnprintf(buf, 1024, message, args);
  3604. va_end(args);
  3605. /* Hide cursor while rendering */
  3606. hide_cursor();
  3607. /* Move cursor to the last line */
  3608. place_cursor(1, global_config.term_height);
  3609. /* Set background color */
  3610. paint_line(COLOR_BG);
  3611. set_colors(COLOR_FG, COLOR_BG);
  3612. printf("%s", buf);
  3613. /* Clear the rest of the status bar */
  3614. clear_to_end();
  3615. }
  3616. /**
  3617. * Draw all screen elements
  3618. */
  3619. void redraw_all(void) {
  3620. redraw_tabbar();
  3621. redraw_text();
  3622. if (left_buffer) {
  3623. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  3624. }
  3625. redraw_statusbar();
  3626. redraw_commandline();
  3627. }
  3628. void redraw_most(void) {
  3629. redraw_tabbar();
  3630. redraw_text();
  3631. redraw_statusbar();
  3632. redraw_commandline();
  3633. }
  3634. void unsplit(void) {
  3635. if (left_buffer) {
  3636. left_buffer->left = 0;
  3637. left_buffer->width = global_config.term_width;
  3638. }
  3639. if (right_buffer) {
  3640. right_buffer->left = 0;
  3641. right_buffer->width = global_config.term_width;
  3642. }
  3643. left_buffer = NULL;
  3644. right_buffer = NULL;
  3645. redraw_all();
  3646. }
  3647. /**
  3648. * Update the terminal title bar
  3649. */
  3650. void update_title(void) {
  3651. if (!global_config.can_title) return;
  3652. char cwd[1024] = {'/',0};
  3653. getcwd(cwd, 1024);
  3654. for (int i = 1; i < 3; ++i) {
  3655. printf("\033]%d;%s%s (%s) - BIM\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  3656. }
  3657. }
  3658. /**
  3659. * Mark this buffer as modified and
  3660. * redraw the status and tabbar if needed.
  3661. */
  3662. void set_modified(void) {
  3663. /* If it was already marked modified, no need to do anything */
  3664. if (env->modified) return;
  3665. /* Mark as modified */
  3666. env->modified = 1;
  3667. /* Redraw some things */
  3668. update_title();
  3669. redraw_tabbar();
  3670. redraw_statusbar();
  3671. }
  3672. /**
  3673. * Draw a message on the status line
  3674. */
  3675. void render_status_message(char * message, ...) {
  3676. /* varargs setup */
  3677. va_list args;
  3678. va_start(args, message);
  3679. char buf[1024];
  3680. /* Process format string */
  3681. vsnprintf(buf, 1024, message, args);
  3682. va_end(args);
  3683. /* Hide cursor while rendering */
  3684. hide_cursor();
  3685. /* Move cursor to the status bar line (second from bottom */
  3686. place_cursor(1, global_config.term_height - 1);
  3687. /* Set background colors for status line */
  3688. paint_line(COLOR_STATUS_BG);
  3689. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3690. printf("%s", buf);
  3691. /* Clear the rest of the status bar */
  3692. clear_to_end();
  3693. }
  3694. /**
  3695. * Draw an errormessage to the command line.
  3696. */
  3697. void render_error(char * message, ...) {
  3698. /* varargs setup */
  3699. va_list args;
  3700. va_start(args, message);
  3701. char buf[1024];
  3702. /* Process format string */
  3703. vsnprintf(buf, 1024, message, args);
  3704. va_end(args);
  3705. /* Hide cursor while rendering */
  3706. hide_cursor();
  3707. /* Move cursor to the command line */
  3708. place_cursor(1, global_config.term_height);
  3709. /* Set appropriate error message colors */
  3710. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  3711. /* Draw the message */
  3712. printf("%s", buf);
  3713. fflush(stdout);
  3714. }
  3715. char * paren_pairs = "()[]{}<>";
  3716. void find_matching_paren(int * out_line, int * out_col, int in_col);
  3717. int is_paren(int c) {
  3718. char * p = paren_pairs;
  3719. while (*p) {
  3720. if (c == *p) return 1;
  3721. p++;
  3722. }
  3723. return 0;
  3724. }
  3725. /**
  3726. * If the config option is enabled, find the matching
  3727. * paren character and highlight it with the SELECT
  3728. * colors, clearing out other SELECT values. As we
  3729. * co-opt the SELECT flag, don't do this in selection
  3730. * modes - only in normal and insert modes.
  3731. */
  3732. void highlight_matching_paren(void) {
  3733. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  3734. if (!global_config.highlight_parens) return;
  3735. int line = -1, col = -1;
  3736. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  3737. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  3738. find_matching_paren(&line, &col, 1);
  3739. if (line != -1) env->highlighting_paren = 1;
  3740. } else if (env->line_no <= env->line_count && env->col_no > 1 && is_paren(env->lines[env->line_no-1]->text[env->col_no-2].codepoint)) {
  3741. find_matching_paren(&line, &col, 2);
  3742. if (line != -1) env->highlighting_paren = 1;
  3743. }
  3744. if (!env->highlighting_paren) return;
  3745. for (int i = 0; i < env->line_count; ++i) {
  3746. int redraw = 0;
  3747. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3748. if (i == line-1 && j == col-1) {
  3749. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT;
  3750. redraw = 1;
  3751. continue;
  3752. }
  3753. if (env->lines[i]->text[j].flags & FLAG_SELECT) {
  3754. redraw = 1;
  3755. }
  3756. env->lines[i]->text[j].flags &= (~FLAG_SELECT);
  3757. }
  3758. if (redraw) {
  3759. if ((i) - env->offset > -1 &&
  3760. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  3761. redraw_line((i) - env->offset, i);
  3762. }
  3763. }
  3764. }
  3765. if (line == -1) env->highlighting_paren = 0;
  3766. }
  3767. /**
  3768. * Move the cursor to the appropriate location based
  3769. * on where it is in the text region.
  3770. *
  3771. * This does some additional math to set the text
  3772. * region horizontal offset.
  3773. */
  3774. void place_cursor_actual(void) {
  3775. /* Invalid positions */
  3776. if (env->line_no < 1) env->line_no = 1;
  3777. if (env->col_no < 1) env->col_no = 1;
  3778. /* Account for the left hand gutter */
  3779. int num_size = num_width() + 3;
  3780. int x = num_size + 1 - env->coffset;
  3781. /* Determine where the cursor is physically */
  3782. for (int i = 0; i < env->col_no - 1; ++i) {
  3783. char_t * c = &env->lines[env->line_no-1]->text[i];
  3784. x += c->display_width;
  3785. }
  3786. /* y is a bit easier to calculate */
  3787. int y = env->line_no - env->offset + 1;
  3788. int needs_redraw = 0;
  3789. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  3790. y++;
  3791. env->offset--;
  3792. needs_redraw = 1;
  3793. }
  3794. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  3795. y--;
  3796. env->offset++;
  3797. needs_redraw = 1;
  3798. }
  3799. if (needs_redraw) {
  3800. redraw_text();
  3801. redraw_tabbar();
  3802. redraw_statusbar();
  3803. redraw_commandline();
  3804. }
  3805. /* If the cursor has gone off screen to the right... */
  3806. if (x > env->width - 1) {
  3807. /* Adjust the offset appropriately to scroll horizontally */
  3808. int diff = x - (env->width - 1);
  3809. env->coffset += diff;
  3810. x -= diff;
  3811. redraw_text();
  3812. }
  3813. /* Same for scrolling horizontally to the left */
  3814. if (x < num_size + 1) {
  3815. int diff = (num_size + 1) - x;
  3816. env->coffset -= diff;
  3817. x += diff;
  3818. redraw_text();
  3819. }
  3820. highlight_matching_paren();
  3821. recalculate_current_line();
  3822. /* Move the actual terminal cursor */
  3823. place_cursor(x+env->left,y);
  3824. /* Show the cursor */
  3825. show_cursor();
  3826. }
  3827. void update_split_size(void) {
  3828. if (!left_buffer) return;
  3829. if (left_buffer == right_buffer) {
  3830. if (left_buffer->left == 0) {
  3831. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3832. } else {
  3833. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  3834. right_buffer->width = global_config.term_width - right_buffer->left;
  3835. }
  3836. return;
  3837. }
  3838. left_buffer->left = 0;
  3839. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3840. right_buffer->left = left_buffer->width;
  3841. right_buffer->width = global_config.term_width - left_buffer->width;
  3842. }
  3843. /**
  3844. * Update screen size
  3845. */
  3846. void update_screen_size(void) {
  3847. struct winsize w;
  3848. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  3849. global_config.term_width = w.ws_col;
  3850. global_config.term_height = w.ws_row;
  3851. if (env) {
  3852. if (left_buffer) {
  3853. update_split_size();
  3854. } else if (env != left_buffer && env != right_buffer) {
  3855. env->width = w.ws_col;
  3856. }
  3857. }
  3858. }
  3859. /**
  3860. * Handle terminal size changes
  3861. */
  3862. void SIGWINCH_handler(int sig) {
  3863. (void)sig;
  3864. update_screen_size();
  3865. redraw_all();
  3866. signal(SIGWINCH, SIGWINCH_handler);
  3867. }
  3868. /**
  3869. * Handle suspend
  3870. */
  3871. void SIGTSTP_handler(int sig) {
  3872. (void)sig;
  3873. mouse_disable();
  3874. set_buffered();
  3875. reset();
  3876. clear_screen();
  3877. show_cursor();
  3878. unset_alternate_screen();
  3879. fflush(stdout);
  3880. signal(SIGTSTP, SIG_DFL);
  3881. raise(SIGTSTP);
  3882. }
  3883. void SIGCONT_handler(int sig) {
  3884. (void)sig;
  3885. set_alternate_screen();
  3886. set_unbuffered();
  3887. mouse_enable();
  3888. redraw_all();
  3889. signal(SIGCONT, SIGCONT_handler);
  3890. signal(SIGTSTP, SIGTSTP_handler);
  3891. }
  3892. /**
  3893. * Move the cursor to a specific line.
  3894. */
  3895. void goto_line(int line) {
  3896. /* Respect file bounds */
  3897. if (line < 1) line = 1;
  3898. if (line > env->line_count) line = env->line_count;
  3899. /* Move the cursor / text region offsets */
  3900. env->coffset = 0;
  3901. env->offset = line - 1;
  3902. env->line_no = line;
  3903. env->col_no = 1;
  3904. redraw_most();
  3905. }
  3906. /**
  3907. * UTF-8 parser state
  3908. */
  3909. static uint32_t codepoint_r;
  3910. static uint32_t state = 0;
  3911. #define UTF8_ACCEPT 0
  3912. #define UTF8_REJECT 1
  3913. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  3914. static int state_table[32] = {
  3915. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  3916. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  3917. 2,2,2,2, /* 110xxxxx */
  3918. 3,3, /* 1110xxxx */
  3919. 4, /* 11110xxx */
  3920. 1 /* 11111xxx */
  3921. };
  3922. static int mask_bytes[32] = {
  3923. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  3924. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  3925. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  3926. 0x1F,0x1F,0x1F,0x1F,
  3927. 0x0F,0x0F,
  3928. 0x07,
  3929. 0x00
  3930. };
  3931. static int next[5] = {
  3932. 0,
  3933. 1,
  3934. 0,
  3935. 2,
  3936. 3
  3937. };
  3938. if (*state == UTF8_ACCEPT) {
  3939. *codep = byte & mask_bytes[byte >> 3];
  3940. *state = state_table[byte >> 3];
  3941. } else if (*state > 0) {
  3942. *codep = (byte & 0x3F) | (*codep << 6);
  3943. *state = next[*state];
  3944. }
  3945. return *state;
  3946. }
  3947. /**
  3948. * Processs (part of) a file and add it to a buffer.
  3949. */
  3950. void add_buffer(uint8_t * buf, int size) {
  3951. for (int i = 0; i < size; ++i) {
  3952. if (!decode(&state, &codepoint_r, buf[i])) {
  3953. uint32_t c = codepoint_r;
  3954. if (c == '\n') {
  3955. env->lines = add_line(env->lines, env->line_no);
  3956. env->col_no = 1;
  3957. env->line_no += 1;
  3958. } else {
  3959. char_t _c;
  3960. _c.codepoint = (uint32_t)c;
  3961. _c.flags = 0;
  3962. _c.display_width = codepoint_width((wchar_t)c);
  3963. line_t * line = env->lines[env->line_no - 1];
  3964. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3965. if (line != nline) {
  3966. env->lines[env->line_no - 1] = nline;
  3967. }
  3968. env->col_no += 1;
  3969. }
  3970. } else if (state == UTF8_REJECT) {
  3971. state = 0;
  3972. }
  3973. }
  3974. }
  3975. struct syntax_definition * match_syntax(char * file) {
  3976. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3977. for (char ** ext = s->ext; *ext; ++ext) {
  3978. int i = strlen(file);
  3979. int j = strlen(*ext);
  3980. do {
  3981. if (file[i] != (*ext)[j]) break;
  3982. if (j == 0) return s;
  3983. if (i == 0) break;
  3984. i--;
  3985. j--;
  3986. } while (1);
  3987. }
  3988. }
  3989. return NULL;
  3990. }
  3991. /**
  3992. * Check if a string is all numbers.
  3993. */
  3994. int is_all_numbers(const char * c) {
  3995. while (*c) {
  3996. if (!isdigit(*c)) return 0;
  3997. c++;
  3998. }
  3999. return 1;
  4000. }
  4001. /**
  4002. * Create a new buffer from a file.
  4003. */
  4004. void open_file(char * file) {
  4005. env = buffer_new();
  4006. env->width = global_config.term_width;
  4007. env->left = 0;
  4008. env->loading = 1;
  4009. setup_buffer(env);
  4010. FILE * f;
  4011. int init_line = -1;
  4012. if (!strcmp(file,"-")) {
  4013. /**
  4014. * Read file from stdin. stderr provides terminal input.
  4015. */
  4016. f = stdin;
  4017. global_config.tty_in = STDERR_FILENO;
  4018. env->modified = 1;
  4019. } else {
  4020. char * l = strrchr(file, ':');
  4021. if (l && is_all_numbers(l+1)) {
  4022. *l = '\0';
  4023. l++;
  4024. init_line = atoi(l);
  4025. }
  4026. struct stat statbuf;
  4027. if (!stat(file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  4028. DIR * dirp = opendir(file);
  4029. if (!dirp) {
  4030. env->loading = 0;
  4031. return;
  4032. }
  4033. struct dirent * ent = readdir(dirp);
  4034. while (ent) {
  4035. add_buffer((unsigned char*)ent->d_name, strlen(ent->d_name));
  4036. add_buffer((unsigned char*)"\n",1);
  4037. ent = readdir(dirp);
  4038. }
  4039. closedir(dirp);
  4040. env->file_name = strdup(file);
  4041. env->readonly = 1;
  4042. env->loading = 0;
  4043. return;
  4044. }
  4045. f = fopen(file, "r");
  4046. env->file_name = strdup(file);
  4047. }
  4048. if (!f) {
  4049. if (global_config.hilight_on_open) {
  4050. env->syntax = match_syntax(file);
  4051. }
  4052. env->loading = 0;
  4053. if (global_config.go_to_line) {
  4054. goto_line(1);
  4055. }
  4056. if (env->syntax && env->syntax->prefers_spaces) {
  4057. env->tabs = 0;
  4058. }
  4059. return;
  4060. }
  4061. uint8_t buf[BLOCK_SIZE];
  4062. state = 0;
  4063. while (!feof(f) && !ferror(f)) {
  4064. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  4065. add_buffer(buf, r);
  4066. }
  4067. if (ferror(f)) {
  4068. env->loading = 0;
  4069. return;
  4070. }
  4071. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4072. /* Remove blank line from end */
  4073. remove_line(env->lines, env->line_no-1);
  4074. }
  4075. if (global_config.hilight_on_open) {
  4076. env->syntax = match_syntax(file);
  4077. for (int i = 0; i < env->line_count; ++i) {
  4078. recalculate_syntax(env->lines[i],i);
  4079. }
  4080. }
  4081. /* Try to automatically figure out tabs vs. spaces */
  4082. int tabs = 0, spaces = 0;
  4083. for (int i = 0; i < env->line_count; ++i) {
  4084. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  4085. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  4086. if (env->lines[i]->text[0].codepoint == ' ' &&
  4087. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  4088. spaces++;
  4089. }
  4090. }
  4091. if (spaces > tabs) {
  4092. env->tabs = 0;
  4093. }
  4094. /* TODO figure out tabstop for spaces? */
  4095. env->loading = 0;
  4096. if (global_config.check_git) {
  4097. env->checkgitstatusonwrite = 1;
  4098. git_examine(file);
  4099. }
  4100. for (int i = 0; i < env->line_count; ++i) {
  4101. recalculate_tabs(env->lines[i]);
  4102. }
  4103. if (global_config.go_to_line) {
  4104. if (init_line != -1) {
  4105. goto_line(init_line);
  4106. } else {
  4107. env->line_no = 1;
  4108. env->col_no = 1;
  4109. fetch_from_biminfo(env);
  4110. place_cursor_actual();
  4111. redraw_all();
  4112. set_preferred_column();
  4113. }
  4114. }
  4115. fclose(f);
  4116. }
  4117. /**
  4118. * Clean up the terminal and exit the editor.
  4119. */
  4120. void quit(void) {
  4121. mouse_disable();
  4122. set_buffered();
  4123. reset();
  4124. clear_screen();
  4125. show_cursor();
  4126. unset_alternate_screen();
  4127. exit(0);
  4128. }
  4129. /**
  4130. * Try to quit, but don't continue if there are
  4131. * modified buffers open.
  4132. */
  4133. void try_quit(void) {
  4134. for (int i = 0; i < buffers_len; i++ ) {
  4135. buffer_t * _env = buffers[i];
  4136. if (_env->modified) {
  4137. if (_env->file_name) {
  4138. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  4139. } else {
  4140. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  4141. }
  4142. return;
  4143. }
  4144. }
  4145. /* Close all buffers */
  4146. while (buffers_len) {
  4147. buffer_close(buffers[0]);
  4148. }
  4149. quit();
  4150. }
  4151. /**
  4152. * Switch to the previous buffer
  4153. */
  4154. void previous_tab(void) {
  4155. buffer_t * last = NULL;
  4156. for (int i = 0; i < buffers_len; i++) {
  4157. buffer_t * _env = buffers[i];
  4158. if (_env == env) {
  4159. if (last) {
  4160. /* Wrap around */
  4161. env = last;
  4162. redraw_all();
  4163. return;
  4164. } else {
  4165. env = buffers[buffers_len-1];
  4166. redraw_all();
  4167. return;
  4168. }
  4169. }
  4170. last = _env;
  4171. }
  4172. }
  4173. /**
  4174. * Switch to the next buffer
  4175. */
  4176. void next_tab(void) {
  4177. for (int i = 0; i < buffers_len; i++) {
  4178. buffer_t * _env = buffers[i];
  4179. if (_env == env) {
  4180. if (i != buffers_len - 1) {
  4181. env = buffers[i+1];
  4182. redraw_all();
  4183. return;
  4184. } else {
  4185. /* Wrap around */
  4186. env = buffers[0];
  4187. redraw_all();
  4188. return;
  4189. }
  4190. }
  4191. }
  4192. }
  4193. /**
  4194. * Check for modified lines in a file by examining `git diff` output.
  4195. * This can be enabled globally in bimrc or per environment with the 'git' option.
  4196. */
  4197. int git_examine(char * filename) {
  4198. if (env->modified) return 1;
  4199. #ifndef __toaru__
  4200. int fds[2];
  4201. pipe(fds);
  4202. int child = fork();
  4203. if (child == 0) {
  4204. FILE * dev_null = fopen("/dev/null","w");
  4205. close(fds[0]);
  4206. dup2(fds[1], STDOUT_FILENO);
  4207. dup2(fileno(dev_null), STDERR_FILENO);
  4208. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  4209. exit(execvp("git",args));
  4210. } else if (child < 0) {
  4211. return 1;
  4212. }
  4213. close(fds[1]);
  4214. FILE * f = fdopen(fds[0],"r");
  4215. int line_offset = 0;
  4216. while (!feof(f)) {
  4217. int c = fgetc(f);
  4218. if (c < 0) break;
  4219. if (c == '@' && line_offset == 0) {
  4220. /* Read line offset, count */
  4221. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  4222. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  4223. int from_line = 0;
  4224. int from_count = 0;
  4225. int to_line = 0;
  4226. int to_count = 0;
  4227. fscanf(f,"%d",&from_line);
  4228. if (fgetc(f) == ',') {
  4229. fscanf(f,"%d",&from_count);
  4230. } else {
  4231. from_count = 1;
  4232. }
  4233. fscanf(f,"%d",&to_line);
  4234. if (fgetc(f) == ',') {
  4235. fscanf(f,"%d",&to_count);
  4236. } else {
  4237. to_count = 1;
  4238. }
  4239. if (to_line > env->line_count) continue;
  4240. if (from_count == 0 && to_count > 0) {
  4241. /* No -, all + means all of to_count is green */
  4242. for (int i = 0; i < to_count; ++i) {
  4243. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  4244. }
  4245. } else if (from_count > 0 && to_count == 0) {
  4246. /*
  4247. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  4248. * Note that to_line is one lower than the affacted line, so we don't need to mes with indexes.
  4249. */
  4250. if (to_line >= env->line_count) continue;
  4251. env->lines[to_line]->rev_status = 4; /* Red */
  4252. } else if (from_count > 0 && from_count == to_count) {
  4253. /* from = to, all modified */
  4254. for (int i = 0; i < to_count; ++i) {
  4255. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  4256. }
  4257. } else if (from_count > 0 && from_count < to_count) {
  4258. /* from < to, some modified, some added */
  4259. for (int i = 0; i < from_count; ++i) {
  4260. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  4261. }
  4262. for (int i = from_count; i < to_count; ++i) {
  4263. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  4264. }
  4265. } else if (to_count > 0 && from_count > to_count) {
  4266. /* from > to, we deleted but also modified some lines */
  4267. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  4268. for (int i = 1; i < to_count-1; ++i) {
  4269. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  4270. }
  4271. }
  4272. }
  4273. }
  4274. if (c == '\n') {
  4275. line_offset = 0;
  4276. continue;
  4277. }
  4278. line_offset++;
  4279. }
  4280. fclose(f);
  4281. #endif
  4282. return 0;
  4283. }
  4284. /**
  4285. * Write active buffer to file
  4286. */
  4287. void write_file(char * file) {
  4288. if (!file) {
  4289. render_error("Need a file to write to.");
  4290. return;
  4291. }
  4292. FILE * f = fopen(file, "w+");
  4293. if (!f) {
  4294. render_error("Failed to open file for writing.");
  4295. return;
  4296. }
  4297. /* Go through each line and convert it back to UTF-8 */
  4298. int i, j;
  4299. for (i = 0; i < env->line_count; ++i) {
  4300. line_t * line = env->lines[i];
  4301. line->rev_status = 0;
  4302. for (j = 0; j < line->actual; j++) {
  4303. char_t c = line->text[j];
  4304. if (c.codepoint == 0) {
  4305. char buf[1] = {0};
  4306. fwrite(buf, 1, 1, f);
  4307. } else {
  4308. char tmp[8] = {0};
  4309. int i = to_eight(c.codepoint, tmp);
  4310. fwrite(tmp, i, 1, f);
  4311. }
  4312. }
  4313. fputc('\n', f);
  4314. }
  4315. fclose(f);
  4316. /* Mark it no longer modified */
  4317. env->modified = 0;
  4318. env->last_save_history = env->history;
  4319. /* If there was no file name set, set one */
  4320. if (!env->file_name) {
  4321. env->file_name = malloc(strlen(file) + 1);
  4322. memcpy(env->file_name, file, strlen(file) + 1);
  4323. }
  4324. if (env->checkgitstatusonwrite) {
  4325. git_examine(file);
  4326. }
  4327. update_title();
  4328. redraw_all();
  4329. }
  4330. /**
  4331. * Close the active buffer
  4332. */
  4333. void close_buffer(void) {
  4334. buffer_t * previous_env = env;
  4335. buffer_t * new_env = buffer_close(env);
  4336. if (new_env == previous_env) {
  4337. /* ?? Failed to close buffer */
  4338. render_error("lolwat");
  4339. }
  4340. if (left_buffer && env == left_buffer) {
  4341. left_buffer = NULL;
  4342. right_buffer->left = 0;
  4343. right_buffer->width = global_config.term_width;
  4344. right_buffer = NULL;
  4345. } else if (left_buffer && env == right_buffer) {
  4346. right_buffer = NULL;
  4347. left_buffer->left = 0;
  4348. left_buffer->width = global_config.term_width;
  4349. left_buffer = NULL;
  4350. }
  4351. /* No more buffers, exit */
  4352. if (!new_env) {
  4353. quit();
  4354. }
  4355. /* Set the new active buffer */
  4356. env = new_env;
  4357. /* Redraw the screen */
  4358. redraw_all();
  4359. }
  4360. void set_preferred_column(void) {
  4361. int c = 0;
  4362. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  4363. c += env->lines[env->line_no-1]->text[i].display_width;
  4364. }
  4365. env->preferred_column = c;
  4366. }
  4367. /**
  4368. * Move the cursor down one line in the text region
  4369. */
  4370. void cursor_down(void) {
  4371. /* If this isn't already the last line... */
  4372. if (env->line_no < env->line_count) {
  4373. /* Move the cursor down */
  4374. env->line_no += 1;
  4375. /* Try to place the cursor horizontally at the preferred column */
  4376. int _x = 0;
  4377. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4378. char_t * c = &env->lines[env->line_no-1]->text[i];
  4379. _x += c->display_width;
  4380. env->col_no = i+1;
  4381. if (_x > env->preferred_column) {
  4382. break;
  4383. }
  4384. }
  4385. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4386. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4387. }
  4388. /*
  4389. * If the horizontal cursor position exceeds the width the new line,
  4390. * then move the cursor left to the extent of the new line.
  4391. *
  4392. * If we're in insert mode, we can go one cell beyond the end of the line
  4393. */
  4394. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4395. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4396. if (env->col_no == 0) env->col_no = 1;
  4397. }
  4398. /*
  4399. * If the screen was scrolled horizontally, unscroll it;
  4400. * if it will be scrolled on this line as well, that will
  4401. * be handled by place_cursor_actual
  4402. */
  4403. int redraw = 0;
  4404. if (env->coffset != 0) {
  4405. env->coffset = 0;
  4406. redraw = 1;
  4407. }
  4408. /* If we've scrolled past the bottom of the screen, scroll the screen */
  4409. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  4410. env->offset += 1;
  4411. /* Tell terminal to scroll */
  4412. if (global_config.can_scroll && !left_buffer) {
  4413. shift_up();
  4414. /* A new line appears on screen at the bottom, draw it */
  4415. int l = global_config.term_height - global_config.bottom_size - 1;
  4416. if (env->offset + l < env->line_count + 1) {
  4417. redraw_line(l-1, env->offset + l-1);
  4418. } else {
  4419. draw_excess_line(l - 1);
  4420. }
  4421. } else {
  4422. redraw_text();
  4423. }
  4424. redraw_tabbar();
  4425. redraw_statusbar();
  4426. redraw_commandline();
  4427. place_cursor_actual();
  4428. return;
  4429. } else if (redraw) {
  4430. /* Otherwise, if we need to redraw because of coffset change, do that */
  4431. redraw_text();
  4432. }
  4433. /* Update the status bar */
  4434. redraw_statusbar();
  4435. /* Place the terminal cursor again */
  4436. place_cursor_actual();
  4437. }
  4438. }
  4439. /**
  4440. * Move the cursor up one line in the text region
  4441. */
  4442. void cursor_up(void) {
  4443. /* If this isn't the first line already */
  4444. if (env->line_no > 1) {
  4445. /* Move the cursor down */
  4446. env->line_no -= 1;
  4447. /* Try to place the cursor horizontally at the preferred column */
  4448. int _x = 0;
  4449. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4450. char_t * c = &env->lines[env->line_no-1]->text[i];
  4451. _x += c->display_width;
  4452. env->col_no = i+1;
  4453. if (_x > env->preferred_column) {
  4454. break;
  4455. }
  4456. }
  4457. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4458. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4459. }
  4460. /*
  4461. * If the horizontal cursor position exceeds the width the new line,
  4462. * then move the cursor left to the extent of the new line.
  4463. *
  4464. * If we're in insert mode, we can go one cell beyond the end of the line
  4465. */
  4466. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4467. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4468. if (env->col_no == 0) env->col_no = 1;
  4469. }
  4470. /*
  4471. * If the screen was scrolled horizontally, unscroll it;
  4472. * if it will be scrolled on this line as well, that will
  4473. * be handled by place_cursor_actual
  4474. */
  4475. int redraw = 0;
  4476. if (env->coffset != 0) {
  4477. env->coffset = 0;
  4478. redraw = 1;
  4479. }
  4480. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  4481. if (env->line_no <= e) {
  4482. env->offset -= 1;
  4483. /* Tell terminal to scroll */
  4484. if (global_config.can_scroll && !left_buffer) {
  4485. shift_down();
  4486. /*
  4487. * The line at the top of the screen should always be real
  4488. * so we can just call redraw_line here
  4489. */
  4490. redraw_line(0,env->offset);
  4491. } else {
  4492. redraw_text();
  4493. }
  4494. redraw_tabbar();
  4495. redraw_statusbar();
  4496. redraw_commandline();
  4497. place_cursor_actual();
  4498. return;
  4499. } else if (redraw) {
  4500. /* Otherwise, if we need to redraw because of coffset change, do that */
  4501. redraw_text();
  4502. }
  4503. /* Update the status bar */
  4504. redraw_statusbar();
  4505. /* Place the terminal cursor again */
  4506. place_cursor_actual();
  4507. }
  4508. }
  4509. /**
  4510. * Move the cursor one column left.
  4511. */
  4512. void cursor_left(void) {
  4513. if (env->col_no > 1) {
  4514. env->col_no -= 1;
  4515. /* Update the status bar */
  4516. redraw_statusbar();
  4517. /* Place the terminal cursor again */
  4518. place_cursor_actual();
  4519. }
  4520. set_preferred_column();
  4521. }
  4522. /**
  4523. * Move the cursor one column right.
  4524. */
  4525. void cursor_right(void) {
  4526. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  4527. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  4528. env->col_no += 1;
  4529. /* Update the status bar */
  4530. redraw_statusbar();
  4531. /* Place the terminal cursor again */
  4532. place_cursor_actual();
  4533. }
  4534. set_preferred_column();
  4535. }
  4536. /**
  4537. * Move the cursor to the fron the of the line
  4538. */
  4539. void cursor_home(void) {
  4540. env->col_no = 1;
  4541. set_preferred_column();
  4542. /* Update the status bar */
  4543. redraw_statusbar();
  4544. /* Place the terminal cursor again */
  4545. place_cursor_actual();
  4546. }
  4547. /**
  4548. * Move the cursor to the end of the line.
  4549. *
  4550. * In INSERT mode, moves one cell right of the end of the line.
  4551. * In NORMAL mode, moves the cursor to the last occupied cell.
  4552. */
  4553. void cursor_end(void) {
  4554. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4555. set_preferred_column();
  4556. /* Update the status bar */
  4557. redraw_statusbar();
  4558. /* Place the terminal cursor again */
  4559. place_cursor_actual();
  4560. }
  4561. /**
  4562. * Leave INSERT mode
  4563. *
  4564. * If the cursor is too far right, adjust it.
  4565. * Redraw the command line.
  4566. */
  4567. void leave_insert(void) {
  4568. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4569. env->col_no = env->lines[env->line_no-1]->actual;
  4570. if (env->col_no == 0) env->col_no = 1;
  4571. set_preferred_column();
  4572. }
  4573. set_history_break();
  4574. env->mode = MODE_NORMAL;
  4575. redraw_commandline();
  4576. }
  4577. int search_matches(uint32_t a, uint32_t b, int mode) {
  4578. if (mode == 0) {
  4579. return a == b;
  4580. } else if (mode == 1) {
  4581. return tolower(a) == tolower(b);
  4582. }
  4583. return 0;
  4584. }
  4585. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4586. line_t * line = env->lines[line_no-1];
  4587. int j = col;
  4588. while (j < line->actual + 1) {
  4589. int k = j;
  4590. uint32_t * match = needle;
  4591. while (k < line->actual + 1) {
  4592. if (*match == '\0') {
  4593. /* Perform replacement */
  4594. for (uint32_t * n = needle; *n; ++n) {
  4595. line_delete(line, j+1, line_no-1);
  4596. }
  4597. int t = 0;
  4598. for (uint32_t * r = replacement; *r; ++r) {
  4599. char_t _c;
  4600. _c.codepoint = *r;
  4601. _c.flags = 0;
  4602. _c.display_width = codepoint_width(*r);
  4603. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4604. if (line != nline) {
  4605. env->lines[line_no-1] = nline;
  4606. line = nline;
  4607. }
  4608. t++;
  4609. }
  4610. *out_col = j + t;
  4611. set_modified();
  4612. return;
  4613. }
  4614. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  4615. match++;
  4616. k++;
  4617. }
  4618. j++;
  4619. }
  4620. *out_col = -1;
  4621. }
  4622. #define COMMAND_HISTORY_MAX 255
  4623. char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4624. void insert_command_history(char * cmd) {
  4625. /* See if this is already in the history. */
  4626. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4627. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4628. if (!strcmp(command_history[i], cmd)) {
  4629. free(command_history[i]);
  4630. amount_to_shift = i;
  4631. break;
  4632. }
  4633. }
  4634. /* Remove last entry that will roll off the stack */
  4635. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4636. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4637. }
  4638. /* Roll the history */
  4639. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4640. command_history[0] = strdup(cmd);
  4641. }
  4642. /**
  4643. * Process a user command.
  4644. */
  4645. void process_command(char * cmd) {
  4646. /* Special case ! to run shell commands without parsing tokens */
  4647. int c;
  4648. /* Add command to history */
  4649. insert_command_history(cmd);
  4650. if (*cmd == '!') {
  4651. /* Reset and draw some line feeds */
  4652. reset();
  4653. printf("\n\n");
  4654. /* Set buffered for shell application */
  4655. set_buffered();
  4656. /* Call the shell and wait for completion */
  4657. system(&cmd[1]);
  4658. /* Return to the editor, wait for user to press enter. */
  4659. set_unbuffered();
  4660. printf("\n\nPress ENTER to continue.");
  4661. fflush(stdout);
  4662. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4663. /* Redraw the screen */
  4664. redraw_all();
  4665. /* Done processing command */
  4666. return;
  4667. }
  4668. /* Arguments aren't really tokenized, but the first command before a space is extracted */
  4669. char *argv[512]; /* If a specific command wants to tokenize further, it can do that later. */
  4670. int argc = 0;
  4671. argv[0] = cmd;
  4672. if (*cmd) argc++;
  4673. /* Collect up until first space for argv[0] */
  4674. for (char * c = cmd; *c; ++c) {
  4675. if (*c == ' ') {
  4676. *c = '\0';
  4677. argv[1] = c+1;
  4678. if (*argv[1]) argc++;
  4679. break;
  4680. }
  4681. }
  4682. argv[argc] = NULL;
  4683. if (argc < 1) {
  4684. /* no op */
  4685. return;
  4686. }
  4687. int all_lines = 0;
  4688. if (argv[0][0] == '%') {
  4689. all_lines = 1;
  4690. argv[0]++;
  4691. }
  4692. if (!strcmp(argv[0], "e")) {
  4693. /* e: edit file */
  4694. if (argc > 1) {
  4695. /* This actually opens a new tab */
  4696. open_file(argv[1]);
  4697. update_title();
  4698. } else {
  4699. if (env->modified) {
  4700. render_error("File is modified, can not reload.");
  4701. return;
  4702. }
  4703. buffer_t * old_env = env;
  4704. open_file(env->file_name);
  4705. buffer_t * new_env = env;
  4706. env = old_env;
  4707. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4708. SWAP(line_t **, env->lines, new_env->lines);
  4709. SWAP(int, env->line_count, new_env->line_count);
  4710. SWAP(int, env->line_avail, new_env->line_avail);
  4711. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4712. redraw_all();
  4713. }
  4714. } else if (!strcmp(argv[0], "s")) {
  4715. if (argc < 2) {
  4716. render_error("expected substitution argument");
  4717. return;
  4718. }
  4719. /* Substitution */
  4720. int range_top, range_bot;
  4721. if (env->mode == MODE_LINE_SELECTION) {
  4722. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4723. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4724. } else if (all_lines) {
  4725. range_top = 1;
  4726. range_bot = env->line_count;
  4727. } else {
  4728. range_top = env->line_no;
  4729. range_bot = env->line_no;
  4730. }
  4731. /* Determine replacement parameters */
  4732. char divider = argv[1][0];
  4733. char * needle = &argv[1][1];
  4734. char * c = needle;
  4735. char * replacement = NULL;
  4736. char * options = "";
  4737. while (*c) {
  4738. if (*c == divider) {
  4739. *c = '\0';
  4740. replacement = c + 1;
  4741. break;
  4742. }
  4743. c++;
  4744. }
  4745. if (!replacement) {
  4746. render_error("nothing to replace with");
  4747. return;
  4748. }
  4749. c = replacement;
  4750. while (*c) {
  4751. if (*c == divider) {
  4752. *c = '\0';
  4753. options = c + 1;
  4754. break;
  4755. }
  4756. c++;
  4757. }
  4758. int global = 0;
  4759. int case_insensitive = 0;
  4760. /* Parse options */
  4761. while (*options) {
  4762. switch (*options) {
  4763. case 'g':
  4764. global = 1;
  4765. break;
  4766. case 'i':
  4767. case_insensitive = 1;
  4768. break;
  4769. }
  4770. options++;
  4771. }
  4772. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4773. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4774. {
  4775. int i = 0;
  4776. uint32_t c, state = 0;
  4777. for (char * cin = needle; *cin; cin++) {
  4778. if (!decode(&state, &c, *cin)) {
  4779. needle_c[i] = c;
  4780. i++;
  4781. } else if (state == UTF8_REJECT) {
  4782. state = 0;
  4783. }
  4784. }
  4785. needle_c[i] = 0;
  4786. i = 0;
  4787. c = 0;
  4788. state = 0;
  4789. for (char * cin = replacement; *cin; cin++) {
  4790. if (!decode(&state, &c, *cin)) {
  4791. replacement_c[i] = c;
  4792. i++;
  4793. } else if (state == UTF8_REJECT) {
  4794. state = 0;
  4795. }
  4796. }
  4797. replacement_c[i] = 0;
  4798. }
  4799. int replacements = 0;
  4800. for (int line = range_top; line <= range_bot; ++line) {
  4801. int col = 0;
  4802. while (col != -1) {
  4803. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4804. if (col != -1) replacements++;
  4805. if (!global) break;
  4806. }
  4807. }
  4808. free(needle_c);
  4809. free(replacement_c);
  4810. if (replacements) {
  4811. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4812. set_history_break();
  4813. redraw_text();
  4814. } else {
  4815. render_error("Pattern not found: %s", needle);
  4816. }
  4817. } else if (!strcmp(argv[0], "tabnew")) {
  4818. if (argc > 1) {
  4819. open_file(argv[1]);
  4820. update_title();
  4821. } else {
  4822. env = buffer_new();
  4823. setup_buffer(env);
  4824. redraw_all();
  4825. update_title();
  4826. }
  4827. } else if (!strcmp(argv[0], "w")) {
  4828. /* w: write file */
  4829. if (argc > 1) {
  4830. write_file(argv[1]);
  4831. } else {
  4832. write_file(env->file_name);
  4833. }
  4834. } else if (!strcmp(argv[0], "history")) {
  4835. render_commandline_message(""); /* To clear command line */
  4836. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4837. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4838. }
  4839. render_commandline_message("\n");
  4840. redraw_tabbar();
  4841. redraw_commandline();
  4842. fflush(stdout);
  4843. int c;
  4844. while ((c = bim_getch())== -1);
  4845. bim_unget(c);
  4846. redraw_all();
  4847. } else if (!strcmp(argv[0], "wq")) {
  4848. /* wq: write file and close buffer; if there's no file to write to, may do weird things */
  4849. write_file(env->file_name);
  4850. close_buffer();
  4851. } else if (!strcmp(argv[0], "q")) {
  4852. /* close buffer if unmodified */
  4853. if (left_buffer && left_buffer == right_buffer) {
  4854. unsplit();
  4855. return;
  4856. }
  4857. if (env->modified) {
  4858. render_error("No write since last change. Use :q! to force exit.");
  4859. } else {
  4860. close_buffer();
  4861. }
  4862. } else if (!strcmp(argv[0], "q!")) {
  4863. /* close buffer without warning if unmodified */
  4864. close_buffer();
  4865. } else if (!strcmp(argv[0], "qa") || !strcmp(argv[0], "qall")) {
  4866. /* Close all */
  4867. try_quit();
  4868. } else if (!strcmp(argv[0], "qa!")) {
  4869. /* Forcefully exit editor */
  4870. while (buffers_len) {
  4871. buffer_close(buffers[0]);
  4872. }
  4873. quit();
  4874. } else if (!strcmp(argv[0], "tabp")) {
  4875. /* Next tab */
  4876. previous_tab();
  4877. update_title();
  4878. } else if (!strcmp(argv[0], "tabn")) {
  4879. /* Previous tab */
  4880. next_tab();
  4881. update_title();
  4882. } else if (!strcmp(argv[0], "git")) {
  4883. if (argc < 2) {
  4884. render_status_message("git=%d", env->checkgitstatusonwrite);
  4885. } else {
  4886. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4887. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4888. git_examine(env->file_name);
  4889. redraw_text();
  4890. }
  4891. }
  4892. } else if (!strcmp(argv[0], "colorgutter")) {
  4893. if (argc < 2) {
  4894. render_status_message("colorgutter=%d", global_config.color_gutter);
  4895. } else {
  4896. global_config.color_gutter = !!atoi(argv[1]);
  4897. redraw_text();
  4898. }
  4899. } else if (!strcmp(argv[0], "indent")) {
  4900. env->indent = 1;
  4901. redraw_statusbar();
  4902. } else if (!strcmp(argv[0], "noindent")) {
  4903. env->indent = 0;
  4904. redraw_statusbar();
  4905. } else if (!strcmp(argv[0], "cursorcolumn")) {
  4906. render_status_message("cursorcolumn=%d", env->preferred_column);
  4907. } else if (!strcmp(argv[0], "noh")) {
  4908. if (env->search) {
  4909. free(env->search);
  4910. env->search = NULL;
  4911. for (int i = 0; i < env->line_count; ++i) {
  4912. recalculate_syntax(env->lines[i],i);
  4913. }
  4914. redraw_text();
  4915. }
  4916. } else if (!strcmp(argv[0], "help")) {
  4917. /*
  4918. * The repeated calls to redraw_commandline here make use
  4919. * of scrolling to draw this multiline help message on
  4920. * the same background as the command line.
  4921. */
  4922. render_commandline_message(""); /* To clear command line */
  4923. render_commandline_message("\n");
  4924. render_commandline_message(" \033[1mbim - The standard ToaruOS Text Editor\033[22m\n");
  4925. render_commandline_message("\n");
  4926. render_commandline_message(" Available commands:\n");
  4927. render_commandline_message(" Quit with \033[3m:q\033[23m, \033[3m:qa\033[23m, \033[3m:q!\033[23m, \033[3m:qa!\033[23m\n");
  4928. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4929. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4930. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4931. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4932. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4933. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4934. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4935. render_commandline_message("\n");
  4936. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4937. render_commandline_message("\n");
  4938. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4939. redraw_tabbar();
  4940. redraw_commandline();
  4941. fflush(stdout);
  4942. /* Wait for a character so we can redraw the screen before continuing */
  4943. int c;
  4944. while ((c = bim_getch())== -1);
  4945. /* Make sure that key press actually gets used */
  4946. bim_unget(c);
  4947. /*
  4948. * Redraw everything to hide the help message and get the
  4949. * upper few lines of text on screen again
  4950. */
  4951. redraw_all();
  4952. } else if (!strcmp(argv[0], "theme")) {
  4953. if (argc < 2) {
  4954. render_status_message("theme=%s", current_theme);
  4955. return;
  4956. }
  4957. for (struct theme_def * d = themes; d->name; ++d) {
  4958. if (!strcmp(argv[1], d->name)) {
  4959. d->load();
  4960. redraw_all();
  4961. return;
  4962. }
  4963. }
  4964. } else if (!strcmp(argv[0], "splitpercent")) {
  4965. if (argc < 2) {
  4966. render_status_message("splitpercent=%d", global_config.split_percent);
  4967. return;
  4968. } else {
  4969. global_config.split_percent = atoi(argv[1]);
  4970. if (left_buffer) {
  4971. update_split_size();
  4972. redraw_all();
  4973. }
  4974. }
  4975. } else if (!strcmp(argv[0], "split")) {
  4976. if (argc < 2 && buffers_len == 1) {
  4977. left_buffer = buffers[0];
  4978. right_buffer = buffers[0];
  4979. update_split_size();
  4980. redraw_all();
  4981. } else if ((argc < 2 && buffers_len != 2) || (argc == 2 && buffers_len != 1)) {
  4982. render_error("(splits are experimental and only work with two buffers; sorry!)");
  4983. return;
  4984. } else {
  4985. if (argc == 2) {
  4986. open_file(argv[1]);
  4987. }
  4988. left_buffer = buffers[0];
  4989. right_buffer = buffers[1];
  4990. update_split_size();
  4991. redraw_alt_buffer(left_buffer);
  4992. redraw_alt_buffer(right_buffer);
  4993. }
  4994. } else if (!strcmp(argv[0], "unsplit")) {
  4995. unsplit();
  4996. } else if (!strcmp(argv[0], "syntax")) {
  4997. if (argc < 2) {
  4998. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  4999. return;
  5000. }
  5001. if (!strcmp(argv[1],"none")) {
  5002. for (int i = 0; i < env->line_count; ++i) {
  5003. env->lines[i]->istate = 0;
  5004. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5005. env->lines[i]->text[j].flags = 0;
  5006. }
  5007. }
  5008. redraw_all();
  5009. return;
  5010. }
  5011. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  5012. if (!strcmp(argv[1],s->name)) {
  5013. env->syntax = s;
  5014. for (int i = 0; i < env->line_count; ++i) {
  5015. env->lines[i]->istate = 0;
  5016. }
  5017. for (int i = 0; i < env->line_count; ++i) {
  5018. recalculate_syntax(env->lines[i],i);
  5019. }
  5020. redraw_all();
  5021. return;
  5022. }
  5023. }
  5024. render_error("unrecognized syntax type");
  5025. } else if (!strcmp(argv[0], "recalc")) {
  5026. for (int i = 0; i < env->line_count; ++i) {
  5027. env->lines[i]->istate = 0;
  5028. }
  5029. env->loading = 1;
  5030. for (int i = 0; i < env->line_count; ++i) {
  5031. recalculate_syntax(env->lines[i],i);
  5032. }
  5033. env->loading = 0;
  5034. redraw_all();
  5035. } else if (!strcmp(argv[0], "tabs")) {
  5036. env->tabs = 1;
  5037. redraw_statusbar();
  5038. } else if (!strcmp(argv[0], "spaces")) {
  5039. env->tabs = 0;
  5040. redraw_statusbar();
  5041. } else if (!strcmp(argv[0], "tabstop")) {
  5042. if (argc < 2) {
  5043. render_status_message("tabstop=%d", env->tabstop);
  5044. } else {
  5045. int t = atoi(argv[1]);
  5046. if (t > 0 && t < 32) {
  5047. env->tabstop = t;
  5048. for (int i = 0; i < env->line_count; ++i) {
  5049. recalculate_tabs(env->lines[i]);
  5050. }
  5051. redraw_all();
  5052. } else {
  5053. render_error("Invalid tabstop: %s", argv[1]);
  5054. }
  5055. }
  5056. } else if (!strcmp(argv[0], "clearyank")) {
  5057. if (global_config.yanks) {
  5058. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5059. free(global_config.yanks[i]);
  5060. }
  5061. free(global_config.yanks);
  5062. global_config.yanks = NULL;
  5063. global_config.yank_count = 0;
  5064. redraw_statusbar();
  5065. }
  5066. } else if (!strcmp(argv[0], "padding")) {
  5067. if (argc < 2) {
  5068. render_status_message("padding=%d", global_config.cursor_padding);
  5069. } else {
  5070. global_config.cursor_padding = atoi(argv[1]);
  5071. place_cursor_actual();
  5072. }
  5073. } else if (!strcmp(argv[0], "smartcase")) {
  5074. if (argc < 2) {
  5075. render_status_message("smartcase=%d", global_config.smart_case);
  5076. } else {
  5077. global_config.smart_case = atoi(argv[1]);
  5078. place_cursor_actual();
  5079. }
  5080. } else if (!strcmp(argv[0], "hlparen")) {
  5081. if (argc < 2) {
  5082. render_status_message("hlparen=%d", global_config.highlight_parens);
  5083. } else {
  5084. global_config.highlight_parens = atoi(argv[1]);
  5085. for (int i = 0; i < env->line_count; ++i) {
  5086. recalculate_syntax(env->lines[i],i);
  5087. }
  5088. redraw_text();
  5089. place_cursor_actual();
  5090. }
  5091. } else if (!strcmp(argv[0], "hlcurrent")) {
  5092. if (argc < 2) {
  5093. render_status_message("hlcurrent=%d", global_config.hilight_current_line);
  5094. } else {
  5095. global_config.hilight_current_line = atoi(argv[1]);
  5096. if (!global_config.hilight_current_line) {
  5097. for (int i = 0; i < env->line_count; ++i) {
  5098. env->lines[i]->is_current = 0;
  5099. }
  5100. }
  5101. redraw_text();
  5102. place_cursor_actual();
  5103. }
  5104. } else if (isdigit(*argv[0])) {
  5105. /* Go to line number */
  5106. goto_line(atoi(argv[0]));
  5107. } else {
  5108. /* Unrecognized command */
  5109. render_error("Not an editor command: %s", argv[0]);
  5110. }
  5111. }
  5112. /**
  5113. * Tab completion for command mode.
  5114. */
  5115. void command_tab_complete(char * buffer) {
  5116. /* Figure out which argument this is and where it starts */
  5117. int arg = 0;
  5118. char * buf = strdup(buffer);
  5119. char * b = buf;
  5120. char * args[32];
  5121. int candidate_count= 0;
  5122. int candidate_space = 4;
  5123. char ** candidates = malloc(sizeof(char*)*candidate_space);
  5124. /* Accept whitespace before first argument */
  5125. while (*b == ' ') b++;
  5126. char * start = b;
  5127. args[0] = start;
  5128. while (*b && *b != ' ') b++;
  5129. while (*b) {
  5130. while (*b == ' ') {
  5131. *b = '\0';
  5132. b++;
  5133. }
  5134. start = b;
  5135. arg++;
  5136. if (arg < 32) {
  5137. args[arg] = start;
  5138. }
  5139. while (*b && *b != ' ') b++;
  5140. }
  5141. /**
  5142. * Check a possible candidate and add it to the
  5143. * candidates list, expanding as necessary,
  5144. * if it matches for the current argument.
  5145. */
  5146. #define add_candidate(candidate) \
  5147. do { \
  5148. char * _arg = args[arg]; \
  5149. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5150. if (!r) { \
  5151. if (candidate_count == candidate_space) { \
  5152. candidate_space *= 2; \
  5153. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  5154. } \
  5155. candidates[candidate_count] = strdup(candidate); \
  5156. candidate_count++; \
  5157. } \
  5158. } while (0)
  5159. if (arg == 0) {
  5160. /* Complete command names */
  5161. add_candidate("help");
  5162. add_candidate("recalc");
  5163. add_candidate("syntax");
  5164. add_candidate("tabn");
  5165. add_candidate("tabp");
  5166. add_candidate("tabnew");
  5167. add_candidate("theme");
  5168. add_candidate("tabs");
  5169. add_candidate("tabstop");
  5170. add_candidate("spaces");
  5171. add_candidate("noh");
  5172. add_candidate("clearyank");
  5173. add_candidate("indent");
  5174. add_candidate("noindent");
  5175. add_candidate("padding");
  5176. add_candidate("hlparen");
  5177. add_candidate("hlcurrent");
  5178. add_candidate("cursorcolumn");
  5179. add_candidate("smartcase");
  5180. add_candidate("split");
  5181. add_candidate("splitpercent");
  5182. add_candidate("unsplit");
  5183. add_candidate("git");
  5184. add_candidate("colorgutter");
  5185. goto _accept_candidate;
  5186. }
  5187. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5188. /* Complete syntax options */
  5189. add_candidate("none");
  5190. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  5191. add_candidate(s->name);
  5192. }
  5193. goto _accept_candidate;
  5194. }
  5195. if (arg == 1 && !strcmp(args[0], "theme")) {
  5196. /* Complete color theme names */
  5197. for (struct theme_def * s = themes; s->name; ++s) {
  5198. add_candidate(s->name);
  5199. }
  5200. goto _accept_candidate;
  5201. }
  5202. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") || !strcmp(args[0],"split"))) {
  5203. /* Complete file paths */
  5204. /* First, find the deepest directory match */
  5205. char * tmp = strdup(args[arg]);
  5206. char * last_slash = strrchr(tmp, '/');
  5207. DIR * dirp;
  5208. if (last_slash) {
  5209. *last_slash = '\0';
  5210. if (last_slash == tmp) {
  5211. /* Started with slash, and it was the only slash */
  5212. dirp = opendir("/");
  5213. } else {
  5214. dirp = opendir(tmp);
  5215. }
  5216. } else {
  5217. /* No directory match, completing from current directory */
  5218. dirp = opendir(".");
  5219. tmp[0] = '\0';
  5220. }
  5221. if (!dirp) {
  5222. /* Directory match doesn't exist, no candidates to populate */
  5223. free(tmp);
  5224. goto done;
  5225. }
  5226. struct dirent * ent = readdir(dirp);
  5227. while (ent != NULL) {
  5228. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5229. struct stat statbuf;
  5230. /* Figure out if this file is a directory */
  5231. if (last_slash) {
  5232. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5233. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5234. stat(x, &statbuf);
  5235. free(x);
  5236. } else {
  5237. stat(ent->d_name, &statbuf);
  5238. }
  5239. /* Build the complete argument name to tab complete */
  5240. char s[1024] = {0};
  5241. if (last_slash == tmp) {
  5242. strcat(s,"/");
  5243. } else if (*tmp) {
  5244. strcat(s,tmp);
  5245. strcat(s,"/");
  5246. }
  5247. strcat(s,ent->d_name);
  5248. /*
  5249. * If it is a directory, add a / to the end so the next completion
  5250. * attempt will complete the directory's contents.
  5251. */
  5252. if (S_ISDIR(statbuf.st_mode)) {
  5253. strcat(s,"/");
  5254. }
  5255. add_candidate(s);
  5256. }
  5257. ent = readdir(dirp);
  5258. }
  5259. closedir(dirp);
  5260. free(tmp);
  5261. goto _accept_candidate;
  5262. }
  5263. _accept_candidate:
  5264. if (candidate_count == 0) {
  5265. redraw_statusbar();
  5266. goto done;
  5267. }
  5268. if (candidate_count == 1) {
  5269. /* Only one completion possibility */
  5270. redraw_statusbar();
  5271. /* Fill out the rest of the command */
  5272. char * cstart = (buffer) + (start - buf);
  5273. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5274. *cstart = candidates[0][i];
  5275. cstart++;
  5276. }
  5277. *cstart = '\0';
  5278. } else {
  5279. /* Print candidates in status bar */
  5280. char * tmp = malloc(global_config.term_width+1);
  5281. memset(tmp, 0, global_config.term_width+1);
  5282. int offset = 0;
  5283. for (int i = 0; i < candidate_count; ++i) {
  5284. if (offset + 1 + (signed)strlen(candidates[i]) > global_config.term_width - 5) {
  5285. strcat(tmp, "...");
  5286. break;
  5287. }
  5288. if (offset > 0) {
  5289. strcat(tmp, " ");
  5290. offset++;
  5291. }
  5292. strcat(tmp, candidates[i]);
  5293. offset += strlen(candidates[i]);
  5294. }
  5295. render_status_message("%s", tmp);
  5296. free(tmp);
  5297. /* Complete to longest common substring */
  5298. char * cstart = (buffer) + (start - buf);
  5299. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5300. for (int j = 1; j < candidate_count; ++j) {
  5301. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5302. }
  5303. *cstart = candidates[0][i];
  5304. cstart++;
  5305. }
  5306. /* End of longest common substring */
  5307. _reject:
  5308. *cstart = '\0';
  5309. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5310. if (start > buf) { /* Start point needs to be something other than first byte */
  5311. char * tmp = cstart - 1;
  5312. if ((*tmp & 0xC0) == 0x80) {
  5313. /* Count back until we find the start byte and make sure we have the right number */
  5314. int count = 1;
  5315. int x = 0;
  5316. while (tmp >= start) {
  5317. x++;
  5318. tmp--;
  5319. if ((*tmp & 0xC0) == 0x80) {
  5320. count++;
  5321. } else if ((*tmp & 0xC0) == 0xC0) {
  5322. /* How many should we have? */
  5323. int i = 1;
  5324. int j = *tmp;
  5325. while (j & 0x20) {
  5326. i += 1;
  5327. j <<= 1;
  5328. }
  5329. if (count != i) {
  5330. *tmp = '\0';
  5331. break;
  5332. }
  5333. break;
  5334. } else {
  5335. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5336. tmp++;
  5337. *tmp = '\0';
  5338. break;
  5339. }
  5340. }
  5341. } else if ((*tmp & 0xC0) == 0xC0) {
  5342. *tmp = '\0';
  5343. }
  5344. }
  5345. }
  5346. /* Free candidates */
  5347. for (int i = 0; i < candidate_count; ++i) {
  5348. free(candidates[i]);
  5349. }
  5350. /* Redraw command line */
  5351. done:
  5352. redraw_commandline();
  5353. printf(":%s", buffer);
  5354. free(candidates);
  5355. free(buf);
  5356. }
  5357. int handle_command_escape(int * this_buf, int * timeout, int c) {
  5358. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  5359. this_buf[*timeout] = c;
  5360. (*timeout)++;
  5361. return 1;
  5362. }
  5363. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  5364. *timeout = 0;
  5365. bim_unget(c);
  5366. return 1;
  5367. }
  5368. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  5369. *timeout = 1;
  5370. this_buf[*timeout] = c;
  5371. (*timeout)++;
  5372. return 0;
  5373. }
  5374. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  5375. (isdigit(c) || c == ';')) {
  5376. this_buf[*timeout] = c;
  5377. (*timeout)++;
  5378. return 0;
  5379. }
  5380. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  5381. int out = 0;
  5382. switch (c) {
  5383. case 'M':
  5384. out = 2;
  5385. break;
  5386. case 'A': // up
  5387. case 'B': // down
  5388. case 'C': // right
  5389. case 'D': // left
  5390. case 'H': // home
  5391. case 'F': // end
  5392. out = c;
  5393. break;
  5394. }
  5395. *timeout = 0;
  5396. return out;
  5397. }
  5398. *timeout = 0;
  5399. return 0;
  5400. }
  5401. /**
  5402. * Command mode
  5403. *
  5404. * Accept a user command and then process it and
  5405. * return to normal mode.
  5406. *
  5407. * TODO: We only have basic line editing here; it might be
  5408. * nice to add more advanced line editing, like cursor
  5409. * movement, tab completion, etc. This is easier than
  5410. * with the shell since we have a lot more control over
  5411. * where the command input bar is rendered.
  5412. */
  5413. void command_mode(void) {
  5414. int c;
  5415. char buffer[1024] = {0};
  5416. int buffer_len = 0;
  5417. int _redraw_on_byte = 0;
  5418. int timeout = 0;
  5419. int this_buf[20];
  5420. redraw_commandline();
  5421. printf(":");
  5422. show_cursor();
  5423. int history_point = -1;
  5424. while ((c = bim_getch())) {
  5425. if (c == -1) {
  5426. if (timeout && this_buf[timeout-1] == '\033') {
  5427. return;
  5428. }
  5429. timeout = 0;
  5430. continue;
  5431. } else {
  5432. if (timeout == 0) {
  5433. switch (c) {
  5434. case '\033':
  5435. /* Escape, cancel command */
  5436. if (timeout == 0) {
  5437. this_buf[timeout] = c;
  5438. timeout++;
  5439. }
  5440. break;
  5441. case ENTER_KEY:
  5442. case LINE_FEED:
  5443. /* Enter, run command */
  5444. process_command(buffer);
  5445. return;
  5446. case '\t':
  5447. /* Handle tab completion */
  5448. command_tab_complete(buffer);
  5449. buffer_len = strlen(buffer);
  5450. break;
  5451. case BACKSPACE_KEY:
  5452. case DELETE_KEY:
  5453. /* Backspace, delete last character in command buffer */
  5454. if (buffer_len > 0) {
  5455. do {
  5456. buffer_len--;
  5457. if ((buffer[buffer_len] & 0xC0) != 0x80) {
  5458. buffer[buffer_len] = '\0';
  5459. break;
  5460. }
  5461. } while (1);
  5462. goto _redraw_buffer;
  5463. } else {
  5464. /* If backspaced through entire command, cancel command mode */
  5465. redraw_commandline();
  5466. return;
  5467. }
  5468. break;
  5469. case 23:
  5470. while (buffer_len >0 &&
  5471. (buffer[buffer_len-1] == ' ' ||
  5472. buffer[buffer_len-1] == '/')) {
  5473. buffer_len--;
  5474. buffer[buffer_len] = '\0';
  5475. }
  5476. while (buffer_len > 0 &&
  5477. buffer[buffer_len-1] != ' ' &&
  5478. buffer[buffer_len-1] != '/') {
  5479. buffer_len--;
  5480. buffer[buffer_len] = '\0';
  5481. }
  5482. goto _redraw_buffer;
  5483. default:
  5484. /* Regular character */
  5485. buffer[buffer_len] = c;
  5486. buffer_len++;
  5487. if ((c & 0xC0) == 0xC0) {
  5488. /* This is the start of a UTF-8 character; how many bytes do we need? */
  5489. int i = 1;
  5490. int j = c;
  5491. while (j & 0x20) {
  5492. i += 1;
  5493. j <<= 1;
  5494. }
  5495. _redraw_on_byte = i;
  5496. } else if ((c & 0xC0) == 0x80 && _redraw_on_byte) {
  5497. _redraw_on_byte--;
  5498. if (_redraw_on_byte == 0) {
  5499. goto _redraw_buffer;
  5500. }
  5501. } else {
  5502. printf("%c", c);
  5503. }
  5504. break;
  5505. }
  5506. } else {
  5507. switch (handle_command_escape(this_buf,&timeout,c)) {
  5508. case 1:
  5509. bim_unget(c);
  5510. return;
  5511. case 'A':
  5512. /* Load from history */
  5513. if (command_history[history_point+1]) {
  5514. memcpy(buffer, command_history[history_point+1], strlen(command_history[history_point+1])+1);
  5515. history_point++;
  5516. buffer_len = strlen(buffer);
  5517. }
  5518. goto _redraw_buffer;
  5519. case 'B':
  5520. if (history_point > 0) {
  5521. history_point--;
  5522. memcpy(buffer, command_history[history_point], strlen(command_history[history_point])+1);
  5523. } else {
  5524. history_point = -1;
  5525. memset(buffer, 0, 1000);
  5526. }
  5527. buffer_len = strlen(buffer);
  5528. goto _redraw_buffer;
  5529. case 'C':
  5530. case 'D':
  5531. case 'H':
  5532. case 'F':
  5533. render_status_message("line editing not supported in command mode (sorry)");
  5534. goto _redraw_buffer;
  5535. }
  5536. }
  5537. show_cursor();
  5538. continue;
  5539. _redraw_buffer:
  5540. redraw_commandline();
  5541. printf(":%s", buffer);
  5542. show_cursor();
  5543. }
  5544. }
  5545. }
  5546. int smart_case(uint32_t * str) {
  5547. if (!global_config.smart_case) return 0;
  5548. for (uint32_t * s = str; *s; ++s) {
  5549. if (tolower(*s) != (int)*s) {
  5550. return 0;
  5551. }
  5552. }
  5553. return 1;
  5554. }
  5555. /**
  5556. * Search forward from the given cursor position
  5557. * to find a basic search match.
  5558. *
  5559. * This could be more complicated...
  5560. */
  5561. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5562. int col = from_col;
  5563. int ignorecase = smart_case(str);
  5564. for (int i = from_line; i <= env->line_count; ++i) {
  5565. line_t * line = env->lines[i - 1];
  5566. int j = col - 1;
  5567. while (j < line->actual + 1) {
  5568. int k = j;
  5569. uint32_t * match = str;
  5570. while (k < line->actual + 1) {
  5571. if (*match == '\0') {
  5572. *out_line = i;
  5573. *out_col = j + 1;
  5574. return;
  5575. }
  5576. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  5577. match++;
  5578. k++;
  5579. }
  5580. j++;
  5581. }
  5582. col = 0;
  5583. }
  5584. }
  5585. /**
  5586. * Search backwards for matching string.
  5587. */
  5588. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5589. int col = from_col;
  5590. int ignorecase = smart_case(str);
  5591. for (int i = from_line; i >= 1; --i) {
  5592. line_t * line = env->lines[i-1];
  5593. int j = col - 1;
  5594. while (j > -1) {
  5595. int k = j;
  5596. uint32_t * match = str;
  5597. while (k < line->actual + 1) {
  5598. if (*match == '\0') {
  5599. *out_line = i;
  5600. *out_col = j + 1;
  5601. return;
  5602. }
  5603. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  5604. match++;
  5605. k++;
  5606. }
  5607. j--;
  5608. }
  5609. col = (i > 1) ? (env->lines[i-2]->actual) : -1;
  5610. }
  5611. }
  5612. /**
  5613. * Draw the matched search result.
  5614. */
  5615. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  5616. for (int i = 0; i < env->line_count; ++i) {
  5617. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5618. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5619. }
  5620. }
  5621. int line = -1, col = -1, _line = 1, _col = 1;
  5622. do {
  5623. find_match(_line, _col, &line, &col, buffer);
  5624. if (line != -1) {
  5625. line_t * l = env->lines[line-1];
  5626. uint32_t * t = buffer;
  5627. for (int i = col; *t; ++i, ++t) {
  5628. l->text[i-1].flags |= FLAG_SEARCH;
  5629. }
  5630. }
  5631. _line = line;
  5632. _col = col+1;
  5633. line = -1;
  5634. col = -1;
  5635. } while (_line != -1);
  5636. redraw_text();
  5637. place_cursor_actual();
  5638. redraw_statusbar();
  5639. redraw_commandline();
  5640. if (redraw_buffer != -1) {
  5641. printf(redraw_buffer == 1 ? "/" : "?");
  5642. uint32_t * c = buffer;
  5643. while (*c) {
  5644. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5645. to_eight(*c, tmp);
  5646. printf("%s", tmp);
  5647. c++;
  5648. }
  5649. }
  5650. }
  5651. /**
  5652. * Search mode
  5653. *
  5654. * Search text for substring match.
  5655. */
  5656. void search_mode(int direction) {
  5657. uint32_t c;
  5658. uint32_t buffer[1024] = {0};
  5659. int buffer_len = 0;
  5660. /* utf-8 decoding */
  5661. /* Remember where the cursor is so we can cancel */
  5662. int prev_line = env->line_no;
  5663. int prev_col = env->col_no;
  5664. int prev_coffset = env->coffset;
  5665. int prev_offset = env->offset;
  5666. redraw_commandline();
  5667. printf(direction == 1 ? "/" : "?");
  5668. if (env->search) {
  5669. printf("\0337");
  5670. set_colors(COLOR_ALT_FG, COLOR_BG);
  5671. uint32_t * c = env->search;
  5672. while (*c) {
  5673. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5674. to_eight(*c, tmp);
  5675. printf("%s", tmp);
  5676. c++;
  5677. }
  5678. printf("\0338");
  5679. set_colors(COLOR_FG, COLOR_BG);
  5680. }
  5681. show_cursor();
  5682. uint32_t state = 0;
  5683. int cin;
  5684. while ((cin = bim_getch())) {
  5685. if (cin == -1) {
  5686. /* Time out */
  5687. continue;
  5688. }
  5689. if (!decode(&state, &c, cin)) {
  5690. if (c == '\033') {
  5691. /* Cancel search */
  5692. env->line_no = prev_line;
  5693. env->col_no = prev_col;
  5694. /* Unhighlight search matches */
  5695. for (int i = 0; i < env->line_count; ++i) {
  5696. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5697. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5698. }
  5699. }
  5700. redraw_all();
  5701. break;
  5702. } else if (c == ENTER_KEY || c == LINE_FEED) {
  5703. /* Exit search */
  5704. if (!buffer_len) {
  5705. if (env->search) {
  5706. search_next();
  5707. }
  5708. break;
  5709. }
  5710. if (env->search) {
  5711. free(env->search);
  5712. }
  5713. env->search = malloc((buffer_len + 1) * sizeof(uint32_t));
  5714. memcpy(env->search, buffer, (buffer_len + 1) * sizeof(uint32_t));
  5715. break;
  5716. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  5717. /* Backspace, delete last character in search buffer */
  5718. if (buffer_len > 0) {
  5719. buffer_len -= 1;
  5720. buffer[buffer_len] = '\0';
  5721. /* Search from beginning to find first match */
  5722. int line = -1, col = -1;
  5723. if (direction == 1) {
  5724. find_match(prev_line, prev_col, &line, &col, buffer);
  5725. } else {
  5726. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  5727. }
  5728. if (line != -1) {
  5729. env->col_no = col;
  5730. env->line_no = line;
  5731. set_preferred_column();
  5732. }
  5733. draw_search_match(buffer, direction);
  5734. } else {
  5735. /* If backspaced through entire search term, cancel search */
  5736. redraw_commandline();
  5737. env->coffset = prev_coffset;
  5738. env->offset = prev_offset;
  5739. env->col_no = prev_col;
  5740. set_preferred_column();
  5741. env->line_no = prev_line;
  5742. redraw_all();
  5743. break;
  5744. }
  5745. } else {
  5746. /* Regular character */
  5747. buffer[buffer_len] = c;
  5748. buffer_len++;
  5749. buffer[buffer_len] = '\0';
  5750. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  5751. to_eight(c, tmp);
  5752. printf("%s", tmp);
  5753. /* Find the next search match */
  5754. int line = -1, col = -1;
  5755. if (direction == 1) {
  5756. find_match(prev_line, prev_col, &line, &col, buffer);
  5757. } else {
  5758. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  5759. }
  5760. if (line != -1) {
  5761. env->col_no = col;
  5762. env->line_no = line;
  5763. set_preferred_column();
  5764. } else {
  5765. env->coffset = prev_coffset;
  5766. env->offset = prev_offset;
  5767. env->col_no = prev_col;
  5768. set_preferred_column();
  5769. env->line_no = prev_line;
  5770. }
  5771. draw_search_match(buffer, direction);
  5772. }
  5773. show_cursor();
  5774. } else if (state == UTF8_REJECT) {
  5775. state = 0;
  5776. }
  5777. }
  5778. }
  5779. /**
  5780. * Find the next search result, or loop back around if at the end.
  5781. */
  5782. void search_next(void) {
  5783. if (!env->search) return;
  5784. if (env->coffset) env->coffset = 0;
  5785. int line = -1, col = -1;
  5786. find_match(env->line_no, env->col_no+1, &line, &col, env->search);
  5787. if (line == -1) {
  5788. find_match(1,1, &line, &col, env->search);
  5789. if (line == -1) return;
  5790. }
  5791. env->col_no = col;
  5792. env->line_no = line;
  5793. set_preferred_column();
  5794. draw_search_match(env->search, -1);
  5795. }
  5796. /**
  5797. * Find the previous search result, or loop to the end of the file.
  5798. */
  5799. void search_prev(void) {
  5800. if (!env->search) return;
  5801. if (env->coffset) env->coffset = 0;
  5802. int line = -1, col = -1;
  5803. find_match_backwards(env->line_no, env->col_no-1, &line, &col, env->search);
  5804. if (line == -1) {
  5805. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, env->search);
  5806. if (line == -1) return;
  5807. }
  5808. env->col_no = col;
  5809. env->line_no = line;
  5810. set_preferred_column();
  5811. draw_search_match(env->search, -1);
  5812. }
  5813. /**
  5814. * Find the matching paren for this one.
  5815. *
  5816. * This approach skips having to do its own syntax parsing
  5817. * to deal with, eg., erroneous parens in comments. It does
  5818. * this by finding the matching paren with the same flag
  5819. * value, thus parens in strings will match, parens outside
  5820. * of strings will match, but parens in strings won't
  5821. * match parens outside of strings and so on.
  5822. */
  5823. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  5824. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  5825. return; /* Invalid cursor position */
  5826. }
  5827. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  5828. int paren_match = 0;
  5829. int direction = 0;
  5830. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  5831. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0xF;
  5832. int count = 0;
  5833. /* TODO what about unicode parens? */
  5834. for (int i = 0; paren_pairs[i]; ++i) {
  5835. if (start == paren_pairs[i]) {
  5836. direction = (i % 2 == 0) ? 1 : -1;
  5837. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  5838. break;
  5839. }
  5840. }
  5841. if (!paren_match) return;
  5842. /* Scan for match */
  5843. int line = env->line_no;
  5844. int col = env->col_no - in_col + 1;
  5845. do {
  5846. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  5847. /* Only match on same syntax */
  5848. if ((env->lines[line-1]->text[col-1].flags & 0xF) == flags) {
  5849. /* Count up on same direction */
  5850. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  5851. /* Count down on opposite direction */
  5852. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  5853. count--;
  5854. /* When count == 0 we have a match */
  5855. if (count == 0) goto _match_found;
  5856. }
  5857. }
  5858. col += direction;
  5859. }
  5860. line += direction;
  5861. /* Reached first/last line with no match */
  5862. if (line == 0 || line == env->line_count + 1) {
  5863. return;
  5864. }
  5865. /* Reset column to start/end of line, depending on direction */
  5866. if (direction > 0) {
  5867. col = 1;
  5868. } else {
  5869. col = env->lines[line-1]->actual;
  5870. }
  5871. } while (1);
  5872. _match_found:
  5873. *out_line = line;
  5874. *out_col = col;
  5875. }
  5876. void use_left_buffer(void) {
  5877. if (left_buffer == right_buffer && env->left != 0) {
  5878. view_right_offset = env->offset;
  5879. env->width = env->left;
  5880. env->left = 0;
  5881. env->offset = view_left_offset;
  5882. }
  5883. env = left_buffer;
  5884. }
  5885. void use_right_buffer(void) {
  5886. if (left_buffer == right_buffer && env->left == 0) {
  5887. view_left_offset = env->offset;
  5888. env->left = env->width;
  5889. env->width = global_config.term_width - env->width;
  5890. env->offset = view_right_offset;
  5891. }
  5892. env = right_buffer;
  5893. }
  5894. /**
  5895. * Handle mouse event
  5896. */
  5897. void handle_mouse(void) {
  5898. int buttons = bim_getch() - 32;
  5899. int x = bim_getch() - 32;
  5900. int y = bim_getch() - 32;
  5901. if (buttons == 64) {
  5902. /* Scroll up */
  5903. if (global_config.shift_scrolling) {
  5904. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5905. if (env->offset > 0) env->offset--;
  5906. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  5907. cursor_up();
  5908. }
  5909. }
  5910. redraw_most();
  5911. } else {
  5912. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5913. cursor_up();
  5914. }
  5915. }
  5916. return;
  5917. } else if (buttons == 65) {
  5918. /* Scroll down */
  5919. if (global_config.shift_scrolling) {
  5920. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5921. if (env->offset < env->line_count-1) env->offset++;
  5922. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  5923. if (env->line_no <= e) {
  5924. cursor_down();
  5925. }
  5926. }
  5927. redraw_most();
  5928. } else {
  5929. for (int i = 0; i < global_config.scroll_amount; ++i) {
  5930. cursor_down();
  5931. }
  5932. }
  5933. return;
  5934. } else if (buttons == 3) {
  5935. /* Move cursor to position */
  5936. if (x < 0) return;
  5937. if (y < 0) return;
  5938. if (y == 1) {
  5939. /* Pick from tabs */
  5940. int _x = 0;
  5941. for (int i = 0; i < buffers_len; i++) {
  5942. buffer_t * _env = buffers[i];
  5943. char tmp[64];
  5944. _x += draw_tab_name(_env, tmp);
  5945. if (_x >= x) {
  5946. env = buffers[i];
  5947. redraw_all();
  5948. return;
  5949. }
  5950. }
  5951. return;
  5952. }
  5953. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  5954. int current_mode = env->mode;
  5955. if (x < env->left && env == right_buffer) {
  5956. use_left_buffer();
  5957. } else if (x > env->width && env == left_buffer) {
  5958. use_right_buffer();
  5959. }
  5960. env->mode = current_mode;
  5961. redraw_all();
  5962. }
  5963. if (env->left) {
  5964. x -= env->left;
  5965. }
  5966. /* Figure out y coordinate */
  5967. int line_no = y + env->offset - 1;
  5968. int col_no = -1;
  5969. if (line_no > env->line_count) {
  5970. line_no = env->line_count;
  5971. }
  5972. /* Account for the left hand gutter */
  5973. int num_size = num_width() + 3;
  5974. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  5975. /* Determine where the cursor is physically */
  5976. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  5977. char_t * c = &env->lines[line_no-1]->text[i];
  5978. _x += c->display_width;
  5979. if (_x > x-1) {
  5980. col_no = i+1;
  5981. break;
  5982. }
  5983. }
  5984. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  5985. col_no = env->lines[line_no-1]->actual;
  5986. }
  5987. env->line_no = line_no;
  5988. env->col_no = col_no;
  5989. set_preferred_column();
  5990. place_cursor_actual();
  5991. }
  5992. return;
  5993. }
  5994. /**
  5995. * Append a character at the current cursor point.
  5996. */
  5997. void insert_char(unsigned int c) {
  5998. if (!c) {
  5999. render_error("Inserted nil byte?");
  6000. return;
  6001. }
  6002. char_t _c;
  6003. _c.codepoint = c;
  6004. _c.flags = 0;
  6005. _c.display_width = codepoint_width(c);
  6006. line_t * line = env->lines[env->line_no - 1];
  6007. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6008. if (line != nline) {
  6009. env->lines[env->line_no - 1] = nline;
  6010. }
  6011. env->col_no += 1;
  6012. set_modified();
  6013. }
  6014. /**
  6015. * Replace a single character at the current cursor point
  6016. */
  6017. void replace_char(unsigned int c) {
  6018. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6019. char_t _c;
  6020. _c.codepoint = c;
  6021. _c.flags = 0;
  6022. _c.display_width = codepoint_width(c);
  6023. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6024. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6025. set_modified();
  6026. }
  6027. /**
  6028. * Undo a history entry.
  6029. */
  6030. void undo_history(void) {
  6031. if (!global_config.history_enabled) return;
  6032. env->loading = 1;
  6033. history_t * e = env->history;
  6034. if (e->type == HISTORY_SENTINEL) {
  6035. env->loading = 0;
  6036. render_commandline_message("Already at oldest change");
  6037. return;
  6038. }
  6039. int count_chars = 0;
  6040. int count_lines = 0;
  6041. do {
  6042. if (e->type == HISTORY_SENTINEL) break;
  6043. switch (e->type) {
  6044. case HISTORY_INSERT:
  6045. /* Delete */
  6046. line_delete(
  6047. env->lines[e->contents.insert_delete_replace.lineno],
  6048. e->contents.insert_delete_replace.offset+1,
  6049. e->contents.insert_delete_replace.lineno
  6050. );
  6051. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6052. env->col_no = e->contents.insert_delete_replace.offset + 1;
  6053. count_chars++;
  6054. break;
  6055. case HISTORY_DELETE:
  6056. {
  6057. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6058. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6059. env->lines[e->contents.insert_delete_replace.lineno],
  6060. _c,
  6061. e->contents.insert_delete_replace.offset-1,
  6062. e->contents.insert_delete_replace.lineno
  6063. );
  6064. }
  6065. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6066. env->col_no = e->contents.insert_delete_replace.offset + 2;
  6067. count_chars++;
  6068. break;
  6069. case HISTORY_REPLACE:
  6070. {
  6071. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6072. line_replace(
  6073. env->lines[e->contents.insert_delete_replace.lineno],
  6074. _o,
  6075. e->contents.insert_delete_replace.offset,
  6076. e->contents.insert_delete_replace.lineno
  6077. );
  6078. }
  6079. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6080. env->col_no = e->contents.insert_delete_replace.offset + 1;
  6081. count_chars++;
  6082. break;
  6083. case HISTORY_REMOVE_LINE:
  6084. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6085. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6086. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6087. env->col_no = 1;
  6088. count_lines++;
  6089. break;
  6090. case HISTORY_ADD_LINE:
  6091. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6092. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  6093. env->col_no = 1;
  6094. count_lines++;
  6095. break;
  6096. case HISTORY_REPLACE_LINE:
  6097. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6098. env->line_no = e->contents.remove_replace_line.lineno + 1;
  6099. env->col_no = 1;
  6100. count_lines++;
  6101. break;
  6102. case HISTORY_SPLIT_LINE:
  6103. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6104. env->line_no = e->contents.add_merge_split_lines.lineno + 2;
  6105. env->col_no = 1;
  6106. count_lines++;
  6107. break;
  6108. case HISTORY_MERGE_LINES:
  6109. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6110. env->line_no = e->contents.add_merge_split_lines.lineno;
  6111. env->col_no = 1;
  6112. count_lines++;
  6113. break;
  6114. case HISTORY_BREAK:
  6115. /* Ignore break */
  6116. break;
  6117. default:
  6118. render_error("Unknown type %d!\n", e->type);
  6119. break;
  6120. }
  6121. env->history = e->previous;
  6122. e = env->history;
  6123. } while (e->type != HISTORY_BREAK);
  6124. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6125. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6126. env->modified = (env->history != env->last_save_history);
  6127. env->loading = 0;
  6128. for (int i = 0; i < env->line_count; ++i) {
  6129. env->lines[i]->istate = 0;
  6130. recalculate_tabs(env->lines[i]);
  6131. }
  6132. for (int i = 0; i < env->line_count; ++i) {
  6133. recalculate_syntax(env->lines[i],i);
  6134. }
  6135. place_cursor_actual();
  6136. update_title();
  6137. redraw_all();
  6138. render_commandline_message("%d character%s, %d line%s changed",
  6139. count_chars, (count_chars == 1) ? "" : "s",
  6140. count_lines, (count_lines == 1) ? "" : "s");
  6141. }
  6142. /**
  6143. * Replay a history entry.
  6144. */
  6145. void redo_history(void) {
  6146. if (!global_config.history_enabled) return;
  6147. env->loading = 1;
  6148. history_t * e = env->history->next;
  6149. if (!e) {
  6150. env->loading = 0;
  6151. render_commandline_message("Already at newest change");
  6152. return;
  6153. }
  6154. int count_chars = 0;
  6155. int count_lines = 0;
  6156. while (e) {
  6157. if (e->type == HISTORY_BREAK) {
  6158. env->history = e;
  6159. break;
  6160. }
  6161. switch (e->type) {
  6162. case HISTORY_INSERT:
  6163. {
  6164. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6165. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6166. env->lines[e->contents.insert_delete_replace.lineno],
  6167. _c,
  6168. e->contents.insert_delete_replace.offset,
  6169. e->contents.insert_delete_replace.lineno
  6170. );
  6171. }
  6172. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6173. env->col_no = e->contents.insert_delete_replace.offset + 2;
  6174. count_chars++;
  6175. break;
  6176. case HISTORY_DELETE:
  6177. /* Delete */
  6178. line_delete(
  6179. env->lines[e->contents.insert_delete_replace.lineno],
  6180. e->contents.insert_delete_replace.offset,
  6181. e->contents.insert_delete_replace.lineno
  6182. );
  6183. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6184. env->col_no = e->contents.insert_delete_replace.offset + 1;
  6185. count_chars++;
  6186. break;
  6187. case HISTORY_REPLACE:
  6188. {
  6189. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6190. line_replace(
  6191. env->lines[e->contents.insert_delete_replace.lineno],
  6192. _o,
  6193. e->contents.insert_delete_replace.offset,
  6194. e->contents.insert_delete_replace.lineno
  6195. );
  6196. }
  6197. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  6198. env->col_no = e->contents.insert_delete_replace.offset + 2;
  6199. count_chars++;
  6200. break;
  6201. case HISTORY_ADD_LINE:
  6202. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6203. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6204. env->col_no = 1;
  6205. count_lines++;
  6206. break;
  6207. case HISTORY_REMOVE_LINE:
  6208. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6209. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  6210. env->col_no = 1;
  6211. count_lines++;
  6212. break;
  6213. case HISTORY_REPLACE_LINE:
  6214. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6215. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6216. env->col_no = 1;
  6217. count_lines++;
  6218. break;
  6219. case HISTORY_MERGE_LINES:
  6220. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6221. env->line_no = e->contents.remove_replace_line.lineno + 1;
  6222. env->col_no = 1;
  6223. count_lines++;
  6224. break;
  6225. case HISTORY_SPLIT_LINE:
  6226. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6227. env->line_no = e->contents.remove_replace_line.lineno + 2;
  6228. env->col_no = 1;
  6229. count_lines++;
  6230. break;
  6231. case HISTORY_BREAK:
  6232. /* Ignore break */
  6233. break;
  6234. default:
  6235. render_error("Unknown type %d!\n", e->type);
  6236. break;
  6237. }
  6238. env->history = e;
  6239. e = e->next;
  6240. }
  6241. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6242. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6243. env->modified = (env->history != env->last_save_history);
  6244. env->loading = 0;
  6245. for (int i = 0; i < env->line_count; ++i) {
  6246. env->lines[i]->istate = 0;
  6247. recalculate_tabs(env->lines[i]);
  6248. }
  6249. for (int i = 0; i < env->line_count; ++i) {
  6250. recalculate_syntax(env->lines[i],i);
  6251. }
  6252. place_cursor_actual();
  6253. update_title();
  6254. redraw_all();
  6255. render_commandline_message("%d character%s, %d line%s changed",
  6256. count_chars, (count_chars == 1) ? "" : "s",
  6257. count_lines, (count_lines == 1) ? "" : "s");
  6258. }
  6259. /**
  6260. * Move the cursor the start of the previous word.
  6261. */
  6262. void word_left(void) {
  6263. int line_no = env->line_no;
  6264. int col_no = env->col_no;
  6265. do {
  6266. col_no--;
  6267. while (col_no == 0) {
  6268. line_no--;
  6269. if (line_no == 0) {
  6270. goto_line(1);
  6271. set_preferred_column();
  6272. return;
  6273. }
  6274. col_no = env->lines[line_no-1]->actual;
  6275. }
  6276. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6277. do {
  6278. col_no--;
  6279. if (col_no == 0) {
  6280. col_no = 1;
  6281. break;
  6282. }
  6283. if (col_no == 1) {
  6284. env->col_no = 1;
  6285. env->line_no = line_no;
  6286. set_preferred_column();
  6287. redraw_statusbar();
  6288. place_cursor_actual();
  6289. return;
  6290. }
  6291. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6292. env->col_no = col_no;
  6293. env->line_no = line_no;
  6294. set_preferred_column();
  6295. cursor_right();
  6296. }
  6297. /**
  6298. * Word right
  6299. */
  6300. void word_right(void) {
  6301. int line_no = env->line_no;
  6302. int col_no = env->col_no;
  6303. do {
  6304. col_no++;
  6305. if (col_no > env->lines[line_no-1]->actual) {
  6306. line_no++;
  6307. if (line_no > env->line_count) {
  6308. env->line_no = env->line_count;
  6309. env->col_no = env->lines[env->line_no-1]->actual;
  6310. set_preferred_column();
  6311. redraw_statusbar();
  6312. place_cursor_actual();
  6313. return;
  6314. }
  6315. col_no = 0;
  6316. break;
  6317. }
  6318. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6319. do {
  6320. col_no++;
  6321. while (col_no > env->lines[line_no-1]->actual) {
  6322. line_no++;
  6323. if (line_no >= env->line_count) {
  6324. env->col_no = env->lines[env->line_count-1]->actual;
  6325. env->line_no = env->line_count;
  6326. set_preferred_column();
  6327. redraw_statusbar();
  6328. place_cursor_actual();
  6329. return;
  6330. }
  6331. col_no = 1;
  6332. }
  6333. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6334. env->col_no = col_no;
  6335. env->line_no = line_no;
  6336. set_preferred_column();
  6337. redraw_statusbar();
  6338. place_cursor_actual();
  6339. return;
  6340. }
  6341. /**
  6342. * Backspace from the current cursor position.
  6343. */
  6344. void delete_at_cursor(void) {
  6345. if (env->col_no > 1) {
  6346. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6347. env->col_no -= 1;
  6348. if (env->coffset > 0) env->coffset--;
  6349. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6350. set_modified();
  6351. redraw_statusbar();
  6352. place_cursor_actual();
  6353. } else if (env->line_no > 1) {
  6354. int tmp = env->lines[env->line_no - 2]->actual;
  6355. merge_lines(env->lines, env->line_no - 1);
  6356. env->line_no -= 1;
  6357. env->col_no = tmp+1;
  6358. set_preferred_column();
  6359. redraw_text();
  6360. set_modified();
  6361. redraw_statusbar();
  6362. place_cursor_actual();
  6363. }
  6364. }
  6365. int is_whitespace(int codepoint) {
  6366. return codepoint == ' ' || codepoint == '\t';
  6367. }
  6368. int is_normal(int codepoint) {
  6369. return isalnum(codepoint) || codepoint == '_';
  6370. }
  6371. int is_special(int codepoint) {
  6372. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6373. }
  6374. void delete_word(void) {
  6375. if (!env->lines[env->line_no-1]) return;
  6376. if (env->col_no > 1) {
  6377. /* Start by deleting whitespace */
  6378. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6379. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6380. env->col_no -= 1;
  6381. if (env->coffset > 0) env->coffset--;
  6382. }
  6383. int (*inverse_comparator)(int) = is_special;
  6384. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6385. inverse_comparator = is_normal;
  6386. }
  6387. do {
  6388. if (env->col_no > 1) {
  6389. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6390. env->col_no -= 1;
  6391. if (env->coffset > 0) env->coffset--;
  6392. }
  6393. } while (env->col_no > 1 && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint));
  6394. set_preferred_column();
  6395. redraw_text();
  6396. set_modified();
  6397. redraw_statusbar();
  6398. place_cursor_actual();
  6399. }
  6400. }
  6401. /**
  6402. * Break the current line in two at the current cursor position.
  6403. */
  6404. void insert_line_feed(void) {
  6405. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6406. env->lines = add_line(env->lines, env->line_no);
  6407. } else {
  6408. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6409. }
  6410. env->col_no = 1;
  6411. env->line_no += 1;
  6412. set_preferred_column();
  6413. add_indent(env->line_no-1,env->line_no-2,0);
  6414. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  6415. env->offset += 1;
  6416. }
  6417. set_modified();
  6418. }
  6419. /**
  6420. * Yank lines between line start and line end (which may be in either order)
  6421. */
  6422. void yank_lines(int start, int end) {
  6423. if (global_config.yanks) {
  6424. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6425. free(global_config.yanks[i]);
  6426. }
  6427. free(global_config.yanks);
  6428. }
  6429. int lines_to_yank;
  6430. int start_point;
  6431. if (start <= end) {
  6432. lines_to_yank = end - start + 1;
  6433. start_point = start - 1;
  6434. } else {
  6435. lines_to_yank = start - end + 1;
  6436. start_point = end - 1;
  6437. }
  6438. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6439. global_config.yank_count = lines_to_yank;
  6440. global_config.yank_is_full_lines = 1;
  6441. for (int i = 0; i < lines_to_yank; ++i) {
  6442. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6443. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6444. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6445. global_config.yanks[i]->istate = 0;
  6446. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6447. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6448. global_config.yanks[i]->text[j].flags = 0;
  6449. }
  6450. }
  6451. }
  6452. /**
  6453. * Helper to yank part of a line into a new yank line.
  6454. */
  6455. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  6456. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  6457. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  6458. global_config.yanks[yank_no]->actual = count;
  6459. global_config.yanks[yank_no]->istate = 0;
  6460. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  6461. for (int i = 0; i < count; ++i) {
  6462. global_config.yanks[yank_no]->text[i].flags = 0;
  6463. }
  6464. }
  6465. /**
  6466. * Yank text...
  6467. */
  6468. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  6469. if (global_config.yanks) {
  6470. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6471. free(global_config.yanks[i]);
  6472. }
  6473. free(global_config.yanks);
  6474. }
  6475. int lines_to_yank = end_line - start_line + 1;
  6476. int start_point = start_line - 1;
  6477. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6478. global_config.yank_count = lines_to_yank;
  6479. global_config.yank_is_full_lines = 0;
  6480. if (lines_to_yank == 1) {
  6481. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  6482. } else {
  6483. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  6484. /* Yank middle lines */
  6485. for (int i = 1; i < lines_to_yank - 1; ++i) {
  6486. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6487. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6488. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6489. global_config.yanks[i]->istate = 0;
  6490. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6491. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6492. global_config.yanks[i]->text[j].flags = 0;
  6493. }
  6494. }
  6495. /* Yank end line */
  6496. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  6497. }
  6498. }
  6499. /**
  6500. * Handle shared escape keys (mostly navigation)
  6501. */
  6502. int handle_escape(int * this_buf, int * timeout, int c) {
  6503. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  6504. this_buf[*timeout] = c;
  6505. (*timeout)++;
  6506. return 1;
  6507. }
  6508. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  6509. *timeout = 0;
  6510. bim_unget(c);
  6511. return 1;
  6512. }
  6513. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  6514. *timeout = 1;
  6515. this_buf[*timeout] = c;
  6516. (*timeout)++;
  6517. return 0;
  6518. }
  6519. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  6520. (isdigit(c) || c == ';')) {
  6521. this_buf[*timeout] = c;
  6522. (*timeout)++;
  6523. return 0;
  6524. }
  6525. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  6526. switch (c) {
  6527. case 'M':
  6528. handle_mouse();
  6529. break;
  6530. case 'A': // up
  6531. cursor_up();
  6532. break;
  6533. case 'B': // down
  6534. cursor_down();
  6535. break;
  6536. case 'C': // right
  6537. if (this_buf[*timeout-1] == '5') {
  6538. word_right();
  6539. } else if (this_buf[*timeout-1] == '3') {
  6540. global_config.split_percent += 1;
  6541. update_split_size();
  6542. redraw_all();
  6543. } else if (this_buf[*timeout-1] == '4') {
  6544. use_right_buffer();
  6545. redraw_all();
  6546. } else {
  6547. cursor_right();
  6548. }
  6549. break;
  6550. case 'D': // left
  6551. if (this_buf[*timeout-1] == '5') {
  6552. word_left();
  6553. } else if (this_buf[*timeout-1] == '3') {
  6554. global_config.split_percent -= 1;
  6555. update_split_size();
  6556. redraw_all();
  6557. } else if (this_buf[*timeout-1] == '4') {
  6558. use_left_buffer();
  6559. redraw_all();
  6560. } else {
  6561. cursor_left();
  6562. }
  6563. break;
  6564. case 'H': // home
  6565. cursor_home();
  6566. break;
  6567. case 'F': // end
  6568. cursor_end();
  6569. break;
  6570. case 'I':
  6571. goto_line(env->line_no - (global_config.term_height - 6));
  6572. break;
  6573. case 'G':
  6574. goto_line(env->line_no + global_config.term_height - 6);
  6575. break;
  6576. case 'Z':
  6577. /* Shift tab */
  6578. if (env->mode == MODE_LINE_SELECTION) {
  6579. *timeout = 0;
  6580. return 'Z';
  6581. }
  6582. break;
  6583. case '~':
  6584. switch (this_buf[*timeout-1]) {
  6585. case '1':
  6586. cursor_home();
  6587. break;
  6588. case '3':
  6589. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) {
  6590. if (env->col_no < env->lines[env->line_no - 1]->actual + 1) {
  6591. line_delete(env->lines[env->line_no - 1], env->col_no, env->line_no - 1);
  6592. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6593. set_modified();
  6594. redraw_statusbar();
  6595. place_cursor_actual();
  6596. } else if (env->line_no < env->line_count) {
  6597. merge_lines(env->lines, env->line_no);
  6598. redraw_text();
  6599. set_modified();
  6600. redraw_statusbar();
  6601. place_cursor_actual();
  6602. }
  6603. }
  6604. break;
  6605. case '4':
  6606. cursor_end();
  6607. break;
  6608. case '5':
  6609. goto_line(env->line_no - (global_config.term_height - 6));
  6610. break;
  6611. case '6':
  6612. goto_line(env->line_no + global_config.term_height - 6);
  6613. break;
  6614. }
  6615. break;
  6616. default:
  6617. render_error("Unrecognized escape sequence identifier: %c", c);
  6618. break;
  6619. }
  6620. *timeout = 0;
  6621. return 0;
  6622. }
  6623. *timeout = 0;
  6624. return 0;
  6625. }
  6626. /**
  6627. * Search for the word under the cursor
  6628. */
  6629. void search_under_cursor(void) {
  6630. /* Figure out size */
  6631. int c_before = 0;
  6632. int c_after = 0;
  6633. int i = env->col_no;
  6634. while (i > 0) {
  6635. if (!c_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6636. c_before++;
  6637. i--;
  6638. }
  6639. i = env->col_no+1;
  6640. while (i < env->lines[env->line_no-1]->actual+1) {
  6641. if (!c_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  6642. c_after++;
  6643. i++;
  6644. }
  6645. if (!c_before && !c_after) return;
  6646. /* Populate with characters */
  6647. if (env->search) free(env->search);
  6648. env->search = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  6649. int j = 0;
  6650. while (c_before) {
  6651. env->search[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  6652. c_before--;
  6653. j++;
  6654. }
  6655. int x = 0;
  6656. while (c_after) {
  6657. env->search[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  6658. j++;
  6659. x++;
  6660. c_after--;
  6661. }
  6662. env->search[j] = 0;
  6663. /* Find it */
  6664. search_next();
  6665. }
  6666. /**
  6667. * Standard navigation shared by normal, line, and char selection.
  6668. */
  6669. void handle_navigation(int c) {
  6670. switch (c) {
  6671. case 2: /* ctrl-b = page up */
  6672. goto_line(env->line_no - (global_config.term_height - 6));
  6673. break;
  6674. case 6: /* ctrl-f = page down */
  6675. goto_line(env->line_no + global_config.term_height - 6);
  6676. break;
  6677. case ':': /* Switch to command mode */
  6678. command_mode();
  6679. break;
  6680. case '/': /* Switch to search mode */
  6681. search_mode(1);
  6682. break;
  6683. case '?': /* Switch to search mode */
  6684. search_mode(0);
  6685. break;
  6686. case 'n': /* Jump to next search result */
  6687. search_next();
  6688. break;
  6689. case 'N': /* Jump backwards to previous search result */
  6690. search_prev();
  6691. break;
  6692. case 'j': /* Move cursor down */
  6693. cursor_down();
  6694. break;
  6695. case 'k': /* Move cursor up */
  6696. cursor_up();
  6697. break;
  6698. case 'h': /* Move cursor left */
  6699. cursor_left();
  6700. break;
  6701. case 'l': /* Move cursor right*/
  6702. cursor_right();
  6703. break;
  6704. case 'w': /* Move cursor one word right */
  6705. word_right();
  6706. break;
  6707. case 'G': /* Go to end of file */
  6708. goto_line(env->line_count);
  6709. break;
  6710. case '*': /* Search for word under cursor */
  6711. search_under_cursor();
  6712. break;
  6713. case ' ': /* Jump forward several lines */
  6714. goto_line(env->line_no + global_config.term_height - 6);
  6715. break;
  6716. case '%': /* Jump to matching brace/bracket */
  6717. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) {
  6718. /* These modes need to recalculate syntax as find_matching_brace uses it to find appropriate match */
  6719. for (int i = 0; i < env->line_count; ++i) {
  6720. recalculate_syntax(env->lines[i],i);
  6721. }
  6722. }
  6723. {
  6724. int paren_line = -1, paren_col = -1;
  6725. find_matching_paren(&paren_line, &paren_col, 1);
  6726. if (paren_line != -1) {
  6727. env->line_no = paren_line;
  6728. env->col_no = paren_col;
  6729. set_preferred_column();
  6730. place_cursor_actual();
  6731. redraw_statusbar();
  6732. }
  6733. }
  6734. break;
  6735. case '{': /* Jump to previous blank line */
  6736. env->col_no = 1;
  6737. if (env->line_no == 1) break;
  6738. do {
  6739. env->line_no--;
  6740. if (env->lines[env->line_no-1]->actual == 0) break;
  6741. } while (env->line_no > 1);
  6742. set_preferred_column();
  6743. redraw_statusbar();
  6744. break;
  6745. case '}': /* Jump to next blank line */
  6746. env->col_no = 1;
  6747. if (env->line_no == env->line_count) break;
  6748. do {
  6749. env->line_no++;
  6750. if (env->lines[env->line_no-1]->actual == 0) break;
  6751. } while (env->line_no < env->line_count);
  6752. set_preferred_column();
  6753. redraw_statusbar();
  6754. break;
  6755. case '$': /* Move cursor to end of line */
  6756. cursor_end();
  6757. break;
  6758. case '^':
  6759. case '0': /* Move cursor to beginning of line */
  6760. cursor_home();
  6761. break;
  6762. }
  6763. }
  6764. /**
  6765. * Macro for redrawing selected lines with appropriate highlighting.
  6766. */
  6767. #define _redraw_line(line, force_start_line) \
  6768. do { \
  6769. if (!(force_start_line) && (line) == env->start_line) break; \
  6770. if ((line) > env->line_count + 1) { \
  6771. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6772. draw_excess_line((line) - env->offset - 1); \
  6773. } \
  6774. break; \
  6775. } \
  6776. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  6777. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  6778. (env->line_no == env->start_line && (line) != env->start_line)) { \
  6779. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  6780. } else { \
  6781. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  6782. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  6783. } \
  6784. } \
  6785. if ((line) - env->offset + 1 > 1 && \
  6786. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  6787. redraw_line((line) - env->offset - 1, (line)-1); \
  6788. } \
  6789. } while (0)
  6790. /**
  6791. * Adjust indentation on selected lines.
  6792. */
  6793. void adjust_indent(int start_line, int direction) {
  6794. int lines_to_cover = 0;
  6795. int start_point = 0;
  6796. if (start_line <= env->line_no) {
  6797. start_point = start_line - 1;
  6798. lines_to_cover = env->line_no - start_line + 1;
  6799. } else {
  6800. start_point = env->line_no - 1;
  6801. lines_to_cover = start_line - env->line_no + 1;
  6802. }
  6803. for (int i = 0; i < lines_to_cover; ++i) {
  6804. if ((direction == -1) && env->lines[start_point + i]->actual < 1) continue;
  6805. if (direction == -1) {
  6806. if (env->tabs) {
  6807. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  6808. line_delete(env->lines[start_point + i],1,start_point+i);
  6809. _redraw_line(start_point+i+1,1);
  6810. }
  6811. } else {
  6812. for (int j = 0; j < env->tabstop; ++j) {
  6813. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  6814. line_delete(env->lines[start_point + i],1,start_point+i);
  6815. }
  6816. }
  6817. _redraw_line(start_point+i+1,1);
  6818. }
  6819. } else if (direction == 1) {
  6820. if (env->tabs) {
  6821. char_t c;
  6822. c.codepoint = '\t';
  6823. c.display_width = env->tabstop;
  6824. c.flags = FLAG_SELECT;
  6825. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6826. } else {
  6827. for (int j = 0; j < env->tabstop; ++j) {
  6828. char_t c;
  6829. c.codepoint = ' ';
  6830. c.display_width = 1;
  6831. c.flags = FLAG_SELECT;
  6832. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  6833. }
  6834. }
  6835. _redraw_line(start_point+i+1,1);
  6836. }
  6837. }
  6838. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6839. env->col_no = env->lines[env->line_no-1]->actual;
  6840. }
  6841. set_preferred_column();
  6842. set_modified();
  6843. }
  6844. /**
  6845. * LINE SELECTION mode
  6846. *
  6847. * Equivalent to visual line in vim; selects lines of texts.
  6848. */
  6849. void line_selection_mode(void) {
  6850. env->start_line = env->line_no;
  6851. int prev_line = env->start_line;
  6852. env->mode = MODE_LINE_SELECTION;
  6853. redraw_commandline();
  6854. int c;
  6855. int timeout = 0;
  6856. int this_buf[20];
  6857. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  6858. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  6859. }
  6860. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  6861. while ((c = bim_getch())) {
  6862. if (c == -1) {
  6863. if (timeout && this_buf[timeout-1] == '\033') {
  6864. goto _leave_select_line;
  6865. }
  6866. timeout = 0;
  6867. continue;
  6868. } else {
  6869. if (timeout == 0) {
  6870. switch (c) {
  6871. case '\033':
  6872. if (timeout == 0) {
  6873. this_buf[timeout] = c;
  6874. timeout++;
  6875. }
  6876. break;
  6877. case DELETE_KEY:
  6878. case BACKSPACE_KEY:
  6879. cursor_left();
  6880. break;
  6881. case '\t':
  6882. if (env->readonly) goto _readonly;
  6883. adjust_indent(env->start_line, 1);
  6884. break;
  6885. case 'V':
  6886. goto _leave_select_line;
  6887. case 'y':
  6888. yank_lines(env->start_line, env->line_no);
  6889. goto _leave_select_line;
  6890. case 'D':
  6891. case 'd':
  6892. if (env->readonly) goto _readonly;
  6893. yank_lines(env->start_line, env->line_no);
  6894. if (env->start_line <= env->line_no) {
  6895. int lines_to_delete = env->line_no - env->start_line + 1;
  6896. for (int i = 0; i < lines_to_delete; ++i) {
  6897. remove_line(env->lines, env->start_line-1);
  6898. }
  6899. env->line_no = env->start_line;
  6900. } else {
  6901. int lines_to_delete = env->start_line - env->line_no + 1;
  6902. for (int i = 0; i < lines_to_delete; ++i) {
  6903. remove_line(env->lines, env->line_no-1);
  6904. }
  6905. }
  6906. if (env->line_no > env->line_count) {
  6907. env->line_no = env->line_count;
  6908. }
  6909. if (env->col_no > env->lines[env->line_no-1]->actual) {
  6910. env->col_no = env->lines[env->line_no-1]->actual;
  6911. }
  6912. set_preferred_column();
  6913. set_modified();
  6914. goto _leave_select_line;
  6915. case ':': /* Handle command mode specially for redraw */
  6916. command_mode();
  6917. goto _leave_select_line;
  6918. default:
  6919. handle_navigation(c);
  6920. break;
  6921. }
  6922. } else {
  6923. switch (handle_escape(this_buf,&timeout,c)) {
  6924. case 1:
  6925. bim_unget(c);
  6926. goto _leave_select_line;
  6927. case 'Z':
  6928. /* Unindent */
  6929. if (env->readonly) goto _readonly;
  6930. adjust_indent(env->start_line, -1);
  6931. break;
  6932. }
  6933. }
  6934. /* Mark current line */
  6935. _redraw_line(env->line_no,0);
  6936. /* Properly mark everything in the span we just moved through */
  6937. if (prev_line < env->line_no) {
  6938. for (int i = prev_line; i < env->line_no; ++i) {
  6939. _redraw_line(i,0);
  6940. }
  6941. prev_line = env->line_no;
  6942. } else if (prev_line > env->line_no) {
  6943. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  6944. _redraw_line(i,0);
  6945. }
  6946. prev_line = env->line_no;
  6947. }
  6948. redraw_commandline();
  6949. place_cursor_actual();
  6950. continue;
  6951. _readonly:
  6952. render_error("Buffer is read-only");
  6953. }
  6954. }
  6955. _leave_select_line:
  6956. set_history_break();
  6957. env->mode = MODE_NORMAL;
  6958. for (int i = 0; i < env->line_count; ++i) {
  6959. recalculate_syntax(env->lines[i],i);
  6960. }
  6961. redraw_all();
  6962. }
  6963. #define _redraw_line_col(line, force_start_line) \
  6964. do {\
  6965. if (!(force_start_line) && (line) == env->start_line) break; \
  6966. if ((line) > env->line_count + 1) { \
  6967. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  6968. draw_excess_line((line) - env->offset - 1); \
  6969. } \
  6970. break; \
  6971. } \
  6972. if ((line) - env->offset + 1 > 1 && \
  6973. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  6974. redraw_line((line) - env->offset - 1, (line)-1); \
  6975. } \
  6976. } while (0)
  6977. void col_insert_mode(void) {
  6978. if (env->start_line < env->line_no) {
  6979. /* swap */
  6980. int tmp = env->line_no;
  6981. env->line_no = env->start_line;
  6982. env->start_line = tmp;
  6983. }
  6984. /* Set column to preferred_column */
  6985. env->mode = MODE_COL_INSERT;
  6986. redraw_commandline();
  6987. place_cursor_actual();
  6988. int cin;
  6989. uint32_t c;
  6990. int timeout = 0;
  6991. int this_buf[20];
  6992. uint32_t istate = 0;
  6993. int redraw = 0;
  6994. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  6995. if (cin == -1) {
  6996. if (redraw) {
  6997. if (redraw & 2) {
  6998. redraw_text();
  6999. } else {
  7000. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7001. }
  7002. redraw_statusbar();
  7003. place_cursor_actual();
  7004. redraw = 0;
  7005. }
  7006. if (timeout && this_buf[timeout-1] == '\033') {
  7007. return;
  7008. }
  7009. timeout = 0;
  7010. continue;
  7011. }
  7012. if (!decode(&istate, &c, cin)) {
  7013. if (timeout == 0) {
  7014. switch (c) {
  7015. case '\033':
  7016. if (timeout == 0) {
  7017. this_buf[timeout] = c;
  7018. timeout++;
  7019. }
  7020. break;
  7021. case DELETE_KEY:
  7022. case BACKSPACE_KEY:
  7023. if (env->sel_col > 0) {
  7024. int prev_width = 0;
  7025. for (int i = env->line_no; i <= env->start_line; i++) {
  7026. line_t * line = env->lines[i - 1];
  7027. int _x = 0;
  7028. int col = 1;
  7029. int j = 0;
  7030. for (; j < line->actual; ++j) {
  7031. char_t * c = &line->text[j];
  7032. _x += c->display_width;
  7033. col = j+1;
  7034. prev_width = c->display_width;
  7035. if (_x > env->sel_col) break;
  7036. }
  7037. if ((_x == env->sel_col && j == line->actual)) {
  7038. line_delete(line, line->actual, i - 1);
  7039. set_modified();
  7040. } else if (_x > env->sel_col) {
  7041. line_delete(line, col - 1, i - 1);
  7042. set_modified();
  7043. }
  7044. }
  7045. env->sel_col -= prev_width;
  7046. redraw_text();
  7047. }
  7048. break;
  7049. case ENTER_KEY:
  7050. case LINE_FEED:
  7051. /* do nothing in these cases */
  7052. break;
  7053. case 23: /* ^W */
  7054. break;
  7055. case 22: /* ^V */
  7056. render_commandline_message("^V");
  7057. while ((cin = bim_getch()) == -1);
  7058. c = cin;
  7059. redraw_commandline();
  7060. /* fallthrough */
  7061. default:
  7062. /* Okay, this is going to duplicate a lot of insert_char */
  7063. if (c) {
  7064. char_t _c;
  7065. _c.codepoint = c;
  7066. _c.flags = 0;
  7067. _c.display_width = codepoint_width(c);
  7068. /* For each line */
  7069. for (int i = env->line_no; i <= env->start_line; i++) {
  7070. line_t * line = env->lines[i - 1];
  7071. int _x = 0;
  7072. int col = 1;
  7073. int j = 0;
  7074. for (; j < line->actual; ++j) {
  7075. char_t * c = &line->text[j];
  7076. _x += c->display_width;
  7077. col = j+1;
  7078. if (_x > env->sel_col) break;
  7079. }
  7080. if ((_x == env->sel_col && j == line->actual)) {
  7081. _x = env->sel_col + 1;
  7082. col = line->actual + 1;
  7083. }
  7084. if (_x > env->sel_col) {
  7085. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7086. if (line != nline) {
  7087. env->lines[i - 1] = nline;
  7088. }
  7089. set_modified();
  7090. }
  7091. }
  7092. env->sel_col += _c.display_width;
  7093. redraw_text();
  7094. }
  7095. }
  7096. } else {
  7097. /* Don't handle escapes */
  7098. }
  7099. } else if (istate == UTF8_REJECT) {
  7100. istate = 0;
  7101. }
  7102. }
  7103. }
  7104. /**
  7105. * COL SELECTION mode
  7106. *
  7107. * Limited selection mode for doing inserts on multiple lines.
  7108. * Experimental. Based on how I usually use vim's VISUAL BLOCK mode.
  7109. */
  7110. void col_selection_mode(void) {
  7111. env->start_line = env->line_no;
  7112. env->sel_col = env->preferred_column;
  7113. int prev_line = env->start_line;
  7114. env->mode = MODE_COL_SELECTION;
  7115. redraw_commandline();
  7116. int c;
  7117. int timeout = 0;
  7118. int this_buf[20];
  7119. while ((c = bim_getch())) {
  7120. if (c == -1) {
  7121. if (timeout && this_buf[timeout-1] == '\033') {
  7122. goto _leave_select_col;
  7123. }
  7124. timeout = 0;
  7125. continue;
  7126. } else {
  7127. if (timeout == 0) {
  7128. switch (c) {
  7129. case '\033':
  7130. if (timeout == 0) {
  7131. this_buf[timeout] = c;
  7132. timeout++;
  7133. }
  7134. break;
  7135. case 'I':
  7136. if (env->readonly) goto _readonly;
  7137. col_insert_mode();
  7138. goto _leave_select_col;
  7139. case 'a':
  7140. if (env->readonly) goto _readonly;
  7141. env->sel_col += 1;
  7142. redraw_text();
  7143. col_insert_mode();
  7144. goto _leave_select_col;
  7145. case ':':
  7146. command_mode();
  7147. goto _leave_select_col;
  7148. default:
  7149. handle_navigation(c);
  7150. break;
  7151. }
  7152. } else {
  7153. switch (handle_escape(this_buf,&timeout,c)) {
  7154. case 1:
  7155. bim_unget(c);
  7156. goto _leave_select_col;
  7157. /* Doesn't support anything else. */
  7158. }
  7159. }
  7160. }
  7161. _redraw_line_col(env->line_no, 0);
  7162. /* Properly mark everything in the span we just moved through */
  7163. if (prev_line < env->line_no) {
  7164. for (int i = prev_line; i < env->line_no; ++i) {
  7165. _redraw_line_col(i,0);
  7166. }
  7167. prev_line = env->line_no;
  7168. } else if (prev_line > env->line_no) {
  7169. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  7170. _redraw_line_col(i,0);
  7171. }
  7172. prev_line = env->line_no;
  7173. }
  7174. /* prev_line... */
  7175. redraw_commandline();
  7176. place_cursor_actual();
  7177. continue;
  7178. _readonly:
  7179. render_error("Buffer is read-only.");
  7180. }
  7181. _leave_select_col:
  7182. set_history_break();
  7183. env->mode = MODE_NORMAL;
  7184. redraw_all();
  7185. }
  7186. /**
  7187. * Determine if a column + line number are within range of the
  7188. * current character selection specified by start_line, etc.
  7189. *
  7190. * Used to determine how syntax flags should be set when redrawing
  7191. * selected text in CHAR SELECTION mode.
  7192. */
  7193. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7194. if (start_line == end_line) {
  7195. if ( end_col < start_col) {
  7196. int tmp = end_col;
  7197. end_col = start_col;
  7198. start_col = tmp;
  7199. }
  7200. return (col >= start_col && col <= end_col);
  7201. }
  7202. if (start_line > end_line) {
  7203. int tmp = end_line;
  7204. end_line = start_line;
  7205. start_line = tmp;
  7206. tmp = end_col;
  7207. end_col = start_col;
  7208. start_col = tmp;
  7209. }
  7210. if (line < start_line || line > end_line) return 0;
  7211. if (line == start_line) {
  7212. return col >= start_col;
  7213. }
  7214. if (line == end_line) {
  7215. return col <= end_col;
  7216. }
  7217. return 1;
  7218. }
  7219. #define _redraw_line_char(line, force_start_line) \
  7220. do { \
  7221. if (!(force_start_line) && (line) == start_line) break; \
  7222. if ((line) > env->line_count + 1) { \
  7223. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7224. draw_excess_line((line) - env->offset - 1); \
  7225. } \
  7226. break; \
  7227. } \
  7228. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  7229. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  7230. (env->line_no == start_line && (line) != start_line)) { \
  7231. /* Line is completely outside selection */ \
  7232. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7233. } else { \
  7234. if ((line) == start_line || (line) == env->line_no) { \
  7235. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7236. } \
  7237. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7238. if (point_in_range(start_line, env->line_no,start_col, env->col_no, (line), j+1)) { \
  7239. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7240. } \
  7241. } \
  7242. } \
  7243. if ((line) - env->offset + 1 > 1 && \
  7244. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  7245. redraw_line((line) - env->offset - 1, (line)-1); \
  7246. } \
  7247. } while (0)
  7248. /**
  7249. * CHAR SELECTION mode.
  7250. */
  7251. void char_selection_mode(void) {
  7252. int start_line = env->line_no;
  7253. int start_col = env->col_no;
  7254. int prev_line = start_line;
  7255. env->mode = MODE_CHAR_SELECTION;
  7256. redraw_commandline();
  7257. int c;
  7258. int timeout = 0;
  7259. int this_buf[20];
  7260. /* Select single character */
  7261. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7262. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7263. while ((c = bim_getch())) {
  7264. if (c == -1) {
  7265. if (timeout && this_buf[timeout-1] == '\033') {
  7266. goto _leave_select_char;
  7267. }
  7268. timeout = 0;
  7269. continue;
  7270. } else {
  7271. if (timeout == 0) {
  7272. switch (c) {
  7273. case '\033':
  7274. if (timeout == 0) {
  7275. this_buf[timeout] = c;
  7276. timeout++;
  7277. }
  7278. break;
  7279. case DELETE_KEY:
  7280. case BACKSPACE_KEY:
  7281. cursor_left();
  7282. break;
  7283. case 'v':
  7284. goto _leave_select_char;
  7285. case 'y':
  7286. {
  7287. int end_line = env->line_no;
  7288. int end_col = env->col_no;
  7289. if (start_line == end_line) {
  7290. if (start_col > end_col) {
  7291. int tmp = start_col;
  7292. start_col = end_col;
  7293. end_col = tmp;
  7294. }
  7295. } else if (start_line > end_line) {
  7296. int tmp = start_line;
  7297. start_line = end_line;
  7298. end_line = tmp;
  7299. tmp = start_col;
  7300. start_col = end_col;
  7301. end_col = tmp;
  7302. }
  7303. yank_text(start_line, start_col, end_line, end_col);
  7304. }
  7305. goto _leave_select_char;
  7306. case 'D':
  7307. case 'd':
  7308. if (env->readonly) goto _readonly;
  7309. {
  7310. int end_line = env->line_no;
  7311. int end_col = env->col_no;
  7312. if (start_line == end_line) {
  7313. if (start_col > end_col) {
  7314. int tmp = start_col;
  7315. start_col = end_col;
  7316. end_col = tmp;
  7317. }
  7318. yank_text(start_line, start_col, end_line, end_col);
  7319. for (int i = start_col; i <= end_col; ++i) {
  7320. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  7321. }
  7322. env->col_no = start_col;
  7323. } else {
  7324. if (start_line > end_line) {
  7325. int tmp = start_line;
  7326. start_line = end_line;
  7327. end_line = tmp;
  7328. tmp = start_col;
  7329. start_col = end_col;
  7330. end_col = tmp;
  7331. }
  7332. /* Copy lines */
  7333. yank_text(start_line, start_col, end_line, end_col);
  7334. /* Delete lines */
  7335. for (int i = start_line+1; i < end_line; ++i) {
  7336. remove_line(env->lines, start_line);
  7337. } /* end_line is no longer valid; should be start_line+1*/
  7338. /* Delete from start_col forward */
  7339. int tmp = env->lines[start_line-1]->actual;
  7340. for (int i = start_col; i <= tmp; ++i) {
  7341. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  7342. }
  7343. for (int i = 1; i <= end_col; ++i) {
  7344. line_delete(env->lines[start_line], 1, start_line);
  7345. }
  7346. /* Merge start and end lines */
  7347. merge_lines(env->lines, start_line);
  7348. env->line_no = start_line;
  7349. env->col_no = start_col;
  7350. }
  7351. }
  7352. if (env->line_no > env->line_count) {
  7353. env->line_no = env->line_count;
  7354. }
  7355. set_preferred_column();
  7356. set_modified();
  7357. goto _leave_select_char;
  7358. case ':':
  7359. command_mode();
  7360. goto _leave_select_char;
  7361. default:
  7362. handle_navigation(c);
  7363. break;
  7364. }
  7365. } else {
  7366. switch (handle_escape(this_buf,&timeout,c)) {
  7367. case 1:
  7368. bim_unget(c);
  7369. goto _leave_select_char;
  7370. }
  7371. }
  7372. /* Mark current line */
  7373. _redraw_line_char(env->line_no,1);
  7374. /* Properly mark everything in the span we just moved through */
  7375. if (prev_line < env->line_no) {
  7376. for (int i = prev_line; i < env->line_no; ++i) {
  7377. _redraw_line_char(i,1);
  7378. }
  7379. prev_line = env->line_no;
  7380. } else if (prev_line > env->line_no) {
  7381. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  7382. _redraw_line_char(i,1);
  7383. }
  7384. prev_line = env->line_no;
  7385. }
  7386. place_cursor_actual();
  7387. continue;
  7388. _readonly:
  7389. render_error("Buffer is read-only");
  7390. }
  7391. }
  7392. _leave_select_char:
  7393. set_history_break();
  7394. env->mode = MODE_NORMAL;
  7395. for (int i = 0; i < env->line_count; ++i) {
  7396. recalculate_syntax(env->lines[i],i);
  7397. }
  7398. redraw_all();
  7399. }
  7400. /**
  7401. * INSERT mode
  7402. *
  7403. * Accept input into the text buffer.
  7404. */
  7405. void insert_mode(void) {
  7406. int cin;
  7407. uint32_t c;
  7408. /* Set mode line */
  7409. env->mode = MODE_INSERT;
  7410. redraw_commandline();
  7411. /* Place the cursor in the text area */
  7412. place_cursor_actual();
  7413. int timeout = 0;
  7414. int this_buf[20];
  7415. uint32_t istate = 0;
  7416. int redraw = 0;
  7417. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  7418. if (cin == -1) {
  7419. if (redraw) {
  7420. if (redraw & 2) {
  7421. redraw_text();
  7422. } else {
  7423. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7424. }
  7425. redraw_statusbar();
  7426. place_cursor_actual();
  7427. redraw = 0;
  7428. }
  7429. if (timeout && this_buf[timeout-1] == '\033') {
  7430. leave_insert();
  7431. return;
  7432. }
  7433. timeout = 0;
  7434. continue;
  7435. }
  7436. if (!decode(&istate, &c, cin)) {
  7437. if (timeout == 0) {
  7438. switch (c) {
  7439. case '\033':
  7440. if (timeout == 0) {
  7441. this_buf[timeout] = c;
  7442. timeout++;
  7443. }
  7444. break;
  7445. case DELETE_KEY:
  7446. case BACKSPACE_KEY:
  7447. delete_at_cursor();
  7448. break;
  7449. case ENTER_KEY:
  7450. case LINE_FEED:
  7451. if (env->indent) {
  7452. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0xF) == FLAG_COMMENT &&
  7453. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7454. (env->col_no > 3) &&
  7455. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7456. delete_at_cursor();
  7457. }
  7458. }
  7459. insert_line_feed();
  7460. redraw |= 2;
  7461. break;
  7462. case 22: /* ^V */
  7463. /* Insert next byte raw */
  7464. {
  7465. /* Indicate we're in literal mode */
  7466. render_commandline_message("^V");
  7467. /* Put the cursor back into the text field */
  7468. place_cursor_actual();
  7469. /* Get next character */
  7470. while ((cin = bim_getch()) == -1);
  7471. /* Insert literal */
  7472. insert_char(cin);
  7473. /* Redraw INSERT */
  7474. redraw_commandline();
  7475. /* Draw text */
  7476. redraw |= 1;
  7477. }
  7478. break;
  7479. case 23: /* ^W */
  7480. delete_word();
  7481. set_preferred_column();
  7482. break;
  7483. case '\t':
  7484. if (env->tabs) {
  7485. insert_char('\t');
  7486. } else {
  7487. for (int i = 0; i < env->tabstop; ++i) {
  7488. insert_char(' ');
  7489. }
  7490. }
  7491. redraw |= 1;
  7492. set_preferred_column();
  7493. break;
  7494. case '/':
  7495. if (env->indent) {
  7496. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0xF) == FLAG_COMMENT &&
  7497. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  7498. (env->col_no > 3) &&
  7499. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  7500. env->col_no--;
  7501. replace_char('/');
  7502. env->col_no++;
  7503. place_cursor_actual();
  7504. break;
  7505. }
  7506. }
  7507. goto _just_insert;
  7508. case '}':
  7509. if (env->indent) {
  7510. int was_whitespace = 1;
  7511. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  7512. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  7513. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  7514. was_whitespace = 0;
  7515. break;
  7516. }
  7517. }
  7518. insert_char('}');
  7519. if (was_whitespace) {
  7520. int line = -1, col = -1;
  7521. env->col_no--;
  7522. find_matching_paren(&line,&col, 1);
  7523. if (line != -1) {
  7524. while (env->lines[env->line_no-1]->actual) {
  7525. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  7526. }
  7527. add_indent(env->line_no-1,line-1,1);
  7528. env->col_no = env->lines[env->line_no-1]->actual + 1;
  7529. insert_char('}');
  7530. }
  7531. }
  7532. set_preferred_column();
  7533. redraw |= 1;
  7534. break;
  7535. }
  7536. /* fallthrough */
  7537. default:
  7538. _just_insert:
  7539. insert_char(c);
  7540. set_preferred_column();
  7541. redraw |= 1;
  7542. break;
  7543. }
  7544. } else {
  7545. if (handle_escape(this_buf,&timeout,c)) {
  7546. bim_unget(c);
  7547. leave_insert();
  7548. return;
  7549. }
  7550. }
  7551. } else if (istate == UTF8_REJECT) {
  7552. istate = 0;
  7553. }
  7554. }
  7555. }
  7556. /**
  7557. * REPLACE mode
  7558. *
  7559. * Like insert, but replaces characters.
  7560. */
  7561. void replace_mode(void) {
  7562. int cin;
  7563. uint32_t c;
  7564. /* Set mode line */
  7565. env->mode = MODE_REPLACE;
  7566. redraw_commandline();
  7567. /* Place the cursor in the text area */
  7568. place_cursor_actual();
  7569. int timeout = 0;
  7570. int this_buf[20];
  7571. uint32_t istate = 0;
  7572. while ((cin = bim_getch())) {
  7573. if (cin == -1) {
  7574. if (timeout && this_buf[timeout-1] == '\033') {
  7575. leave_insert();
  7576. return;
  7577. }
  7578. timeout = 0;
  7579. continue;
  7580. }
  7581. if (!decode(&istate, &c, cin)) {
  7582. if (timeout == 0) {
  7583. switch (c) {
  7584. case '\033':
  7585. if (timeout == 0) {
  7586. this_buf[timeout] = c;
  7587. timeout++;
  7588. }
  7589. break;
  7590. case DELETE_KEY:
  7591. case BACKSPACE_KEY:
  7592. if (env->line_no > 1 && env->col_no == 1) {
  7593. env->line_no--;
  7594. env->col_no = env->lines[env->line_no-1]->actual;
  7595. set_preferred_column();
  7596. place_cursor_actual();
  7597. } else {
  7598. cursor_left();
  7599. }
  7600. break;
  7601. case ENTER_KEY:
  7602. case LINE_FEED:
  7603. insert_line_feed();
  7604. redraw_text();
  7605. set_modified();
  7606. redraw_statusbar();
  7607. place_cursor_actual();
  7608. break;
  7609. default:
  7610. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  7611. replace_char(c);
  7612. env->col_no += 1;
  7613. } else {
  7614. insert_char(c);
  7615. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  7616. }
  7617. redraw_statusbar();
  7618. place_cursor_actual();
  7619. break;
  7620. }
  7621. } else {
  7622. if (handle_escape(this_buf,&timeout,c)) {
  7623. bim_unget(c);
  7624. leave_insert();
  7625. return;
  7626. }
  7627. }
  7628. } else if (istate == UTF8_REJECT) {
  7629. istate = 0;
  7630. }
  7631. }
  7632. }
  7633. void replace_one(void) {
  7634. /* Read one character and replace */
  7635. render_commandline_message("r");
  7636. uint32_t state = 0;
  7637. int cin;
  7638. uint32_t c;
  7639. while ((cin = bim_getch())) {
  7640. if (cin == -1) continue;
  7641. if (!decode(&state, &c, cin)) {
  7642. if (c == '\033') {
  7643. return;
  7644. } else if (c == 22) { /* ctrl-v */
  7645. render_commandline_message("r ^V");
  7646. while ((cin = bim_getch()) == -1);
  7647. replace_char(cin);
  7648. return;
  7649. } else {
  7650. replace_char(c);
  7651. return;
  7652. }
  7653. }
  7654. }
  7655. return;
  7656. }
  7657. /**
  7658. * NORMAL mode
  7659. *
  7660. * Default editor mode - just cursor navigation and keybinds
  7661. * to enter the other modes.
  7662. */
  7663. void normal_mode(void) {
  7664. while (1) {
  7665. place_cursor_actual();
  7666. int c;
  7667. int timeout = 0;
  7668. int this_buf[20];
  7669. while ((c = bim_getch())) {
  7670. if (c == -1) {
  7671. /* getch timed out, nothing to do in normal mode */
  7672. continue;
  7673. }
  7674. if (timeout == 0) {
  7675. switch (c) {
  7676. case '\033':
  7677. if (timeout == 0) {
  7678. this_buf[timeout] = c;
  7679. timeout++;
  7680. }
  7681. break;
  7682. case DELETE_KEY:
  7683. case BACKSPACE_KEY:
  7684. if (env->line_no > 1 && env->col_no == 1) {
  7685. env->line_no--;
  7686. env->col_no = env->lines[env->line_no-1]->actual;
  7687. set_preferred_column();
  7688. place_cursor_actual();
  7689. } else {
  7690. cursor_left();
  7691. }
  7692. break;
  7693. case 'V': /* Enter LINE SELECTION mode */
  7694. line_selection_mode();
  7695. break;
  7696. case 'v': /* Enter CHAR SELECTION mode */
  7697. char_selection_mode();
  7698. break;
  7699. case 22: /* ctrl-v, enter COL SELECTION mode */
  7700. col_selection_mode();
  7701. break;
  7702. case 'O': /* Append line before and enter INSERT mode */
  7703. {
  7704. if (env->readonly) goto _readonly;
  7705. env->lines = add_line(env->lines, env->line_no-1);
  7706. env->col_no = 1;
  7707. add_indent(env->line_no-1,env->line_no,0);
  7708. redraw_text();
  7709. set_preferred_column();
  7710. set_modified();
  7711. place_cursor_actual();
  7712. goto _insert;
  7713. }
  7714. case 'o': /* Append line after and enter INSERT mode */
  7715. {
  7716. if (env->readonly) goto _readonly;
  7717. env->lines = add_line(env->lines, env->line_no);
  7718. env->col_no = 1;
  7719. env->line_no += 1;
  7720. add_indent(env->line_no-1,env->line_no-2,0);
  7721. set_preferred_column();
  7722. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7723. env->offset += 1;
  7724. }
  7725. redraw_text();
  7726. set_modified();
  7727. place_cursor_actual();
  7728. goto _insert;
  7729. }
  7730. case 'a': /* Enter INSERT mode with cursor after current position */
  7731. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  7732. env->col_no += 1;
  7733. }
  7734. goto _insert;
  7735. case 'P': /* Paste before */
  7736. case 'p': /* Paste after */
  7737. if (env->readonly) goto _readonly;
  7738. if (global_config.yanks) {
  7739. if (!global_config.yank_is_full_lines) {
  7740. /* Handle P for paste before, p for past after */
  7741. int target_column = (c == 'P' ? (env->col_no) : (env->col_no+1));
  7742. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  7743. target_column = env->lines[env->line_no-1]->actual + 1;
  7744. }
  7745. if (global_config.yank_count > 1) {
  7746. /* Spit the current line at the current position */
  7747. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  7748. }
  7749. /* Insert first line at current position */
  7750. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  7751. env->lines[env->line_no - 1] = line_insert(env->lines[env->line_no - 1], global_config.yanks[0]->text[i], target_column + i - 1, env->line_no - 1);
  7752. }
  7753. if (global_config.yank_count > 1) {
  7754. /* Insert full lines */
  7755. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7756. env->lines = add_line(env->lines, env->line_no);
  7757. }
  7758. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  7759. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  7760. }
  7761. /* Insert characters from last line into (what was) the next line */
  7762. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  7763. env->lines[env->line_no + global_config.yank_count - 2] = line_insert(env->lines[env->line_no + global_config.yank_count - 2], global_config.yanks[global_config.yank_count-1]->text[i], i, env->line_no + global_config.yank_count - 2);
  7764. }
  7765. }
  7766. } else {
  7767. /* Insert full lines */
  7768. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7769. env->lines = add_line(env->lines, env->line_no - (c == 'P' ? 1 : 0));
  7770. }
  7771. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  7772. replace_line(env->lines, env->line_no - (c == 'P' ? 1 : 0) + i, global_config.yanks[i]);
  7773. }
  7774. }
  7775. /* Recalculate whole document syntax */
  7776. for (int i = 0; i < env->line_count; ++i) {
  7777. env->lines[i]->istate = 0;
  7778. }
  7779. for (int i = 0; i < env->line_count; ++i) {
  7780. recalculate_syntax(env->lines[i],i);
  7781. }
  7782. if (c == 'p') {
  7783. if (global_config.yank_is_full_lines) {
  7784. env->line_no += 1;
  7785. } else {
  7786. if (global_config.yank_count == 1) {
  7787. env->col_no = env->col_no + global_config.yanks[0]->actual;
  7788. } else {
  7789. env->line_no = env->line_no + global_config.yank_count - 1;
  7790. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  7791. }
  7792. }
  7793. }
  7794. set_history_break();
  7795. set_modified();
  7796. redraw_all();
  7797. }
  7798. break;
  7799. case 'r': /* Replace with next */
  7800. replace_one();
  7801. redraw_commandline();
  7802. break;
  7803. case 'u': /* Undo one block of history */
  7804. undo_history();
  7805. break;
  7806. case 18: /* ^R - Redo one block of history */
  7807. redo_history();
  7808. break;
  7809. case 12: /* ^L - Repaint the whole screen */
  7810. redraw_all();
  7811. break;
  7812. case 'i': /* Enter INSERT mode */
  7813. _insert:
  7814. if (env->readonly) goto _readonly;
  7815. insert_mode();
  7816. redraw_statusbar();
  7817. redraw_commandline();
  7818. timeout = 0;
  7819. break;
  7820. case 'R': /* Enter REPLACE mode */
  7821. if (env->readonly) goto _readonly;
  7822. replace_mode();
  7823. redraw_statusbar();
  7824. redraw_commandline();
  7825. timeout = 0;
  7826. break;
  7827. _readonly:
  7828. render_error("Buffer is read-only");
  7829. break;
  7830. default:
  7831. handle_navigation(c);
  7832. break;
  7833. }
  7834. } else {
  7835. handle_escape(this_buf,&timeout,c);
  7836. }
  7837. place_cursor_actual();
  7838. }
  7839. }
  7840. }
  7841. /**
  7842. * Show help text for -?
  7843. */
  7844. static void show_usage(char * argv[]) {
  7845. #define _s "\033[3m"
  7846. #define _e "\033[0m\n"
  7847. printf(
  7848. "bim - Text editor\n"
  7849. "\n"
  7850. "usage: %s [options] [file]\n"
  7851. " %s [options] -- -\n"
  7852. "\n"
  7853. " -R " _s "open initial buffer read-only" _e
  7854. " -O " _s "set various options:" _e
  7855. " noscroll " _s "disable terminal scrolling" _e
  7856. " noaltscreen " _s "disable alternate screen buffer" _e
  7857. " nomouse " _s "disable mouse support" _e
  7858. " nounicode " _s "disable unicode display" _e
  7859. " nobright " _s "disable bright next" _e
  7860. " nohideshow " _s "disable togglging cursor visibility" _e
  7861. " nosyntax " _s "disable syntax highlighting on load" _e
  7862. " notitle " _s "disable title-setting escapes" _e
  7863. " history " _s "enable experimental undo/redo" _e
  7864. " -c,-C " _s "print file to stdout with syntax hilighting" _e
  7865. " " _s "-C includes line numbers, -c does not" _e
  7866. " -u " _s "override bimrc file" _e
  7867. " -? " _s "show this help text" _e
  7868. " --version " _s "show version information and available plugins" _e
  7869. "\n", argv[0], argv[0]);
  7870. #undef _e
  7871. #undef _s
  7872. }
  7873. /**
  7874. * Load bimrc configuration file.
  7875. *
  7876. * At the moment, this a simple key=value list.
  7877. */
  7878. void load_bimrc(void) {
  7879. if (!global_config.bimrc_path) return;
  7880. /* Default is ~/.bimrc */
  7881. char * tmp = strdup(global_config.bimrc_path);
  7882. if (!*tmp) {
  7883. free(tmp);
  7884. return;
  7885. }
  7886. /* Parse ~ at the front of the path. */
  7887. if (*tmp == '~') {
  7888. char path[1024] = {0};
  7889. char * home = getenv("HOME");
  7890. if (!home) {
  7891. /* $HOME is unset? */
  7892. free(tmp);
  7893. return;
  7894. }
  7895. /* New path is $HOME/.bimrc */
  7896. snprintf(path, 1024, "%s%s", home, tmp+1);
  7897. free(tmp);
  7898. tmp = strdup(path);
  7899. }
  7900. /* Try to open the file */
  7901. FILE * bimrc = fopen(tmp, "r");
  7902. free(tmp);
  7903. if (!bimrc) {
  7904. /* No bimrc, or bad permissions */
  7905. return;
  7906. }
  7907. /* Parse through lines */
  7908. char line[1024];
  7909. while (!feof(bimrc)) {
  7910. char * l = fgets(line, 1023, bimrc);
  7911. /* Ignore bad lines */
  7912. if (!l) break;
  7913. if (!*l) continue;
  7914. if (*l == '\n') continue;
  7915. /* Ignore comment lines */
  7916. if (*l == '#') continue;
  7917. /* Remove linefeed at the end */
  7918. char *nl = strstr(l,"\n");
  7919. if (nl) *nl = '\0';
  7920. /* Extract value from keypair, if available
  7921. * (I foresee options without values in the future) */
  7922. char *value= strstr(l,"=");
  7923. if (value) {
  7924. *value = '\0';
  7925. value++;
  7926. }
  7927. /* theme=... */
  7928. if (!strcmp(l,"theme") && value) {
  7929. /* Examine available themes for a match. */
  7930. for (struct theme_def * d = themes; d->name; ++d) {
  7931. if (!strcmp(value, d->name)) {
  7932. d->load();
  7933. break;
  7934. }
  7935. }
  7936. }
  7937. /* enable history (experimental) */
  7938. if (!strcmp(l,"history")) {
  7939. global_config.history_enabled = (value ? atoi(value) : 1);
  7940. }
  7941. /* padding= */
  7942. if (!strcmp(l,"padding") && value) {
  7943. global_config.cursor_padding = atoi(value);
  7944. }
  7945. if (!strcmp(l,"hlparen") && value) {
  7946. global_config.highlight_parens = atoi(value);
  7947. }
  7948. /* Disable hilighting of current line */
  7949. if (!strcmp(l,"hlcurrent") && value) {
  7950. global_config.hilight_current_line = atoi(value);
  7951. }
  7952. if (!strcmp(l,"splitpercent") && value) {
  7953. global_config.split_percent = atoi(value);
  7954. }
  7955. if (!strcmp(l,"shiftscrolling")) {
  7956. global_config.shift_scrolling = (value ? atoi(value) : 1);
  7957. }
  7958. if (!strcmp(l,"scrollamount") && value) {
  7959. global_config.scroll_amount = atoi(value);
  7960. }
  7961. if (!strcmp(l,"git") && value) {
  7962. global_config.check_git = !!atoi(value);
  7963. }
  7964. if (!strcmp(l,"colorgutter") && value) {
  7965. global_config.color_gutter = !!atoi(value);
  7966. }
  7967. }
  7968. fclose(bimrc);
  7969. }
  7970. /**
  7971. * Set some default values when certain terminals are detected.
  7972. */
  7973. void detect_weird_terminals(void) {
  7974. char * term = getenv("TERM");
  7975. if (term && !strcmp(term,"linux")) {
  7976. /* Linux VTs can't scroll. */
  7977. global_config.can_scroll = 0;
  7978. }
  7979. if (term && !strcmp(term,"cons25")) {
  7980. /* Dragonfly BSD console */
  7981. global_config.can_hideshow = 0;
  7982. global_config.can_altscreen = 0;
  7983. global_config.can_mouse = 0;
  7984. global_config.can_unicode = 0;
  7985. global_config.can_bright = 0;
  7986. }
  7987. if (term && !strcmp(term,"sortix")) {
  7988. /* sortix will spew title escapes to the screen, no good */
  7989. global_config.can_title = 0;
  7990. }
  7991. if (term && strstr(term,"tmux") == term) {
  7992. global_config.can_scroll = 0;
  7993. global_config.can_bce = 0;
  7994. }
  7995. if (term && strstr(term,"screen") == term) {
  7996. /* unfortunately */
  7997. global_config.can_24bit = 0;
  7998. global_config.can_italic = 0;
  7999. }
  8000. if (term && strstr(term,"toaru-vga") == term) {
  8001. global_config.can_24bit = 0; /* Also not strictly true */
  8002. global_config.can_256color = 0; /* Not strictly true */
  8003. }
  8004. }
  8005. /**
  8006. * Run global initialization tasks
  8007. */
  8008. void initialize(void) {
  8009. setlocale(LC_ALL, "");
  8010. detect_weird_terminals();
  8011. load_colorscheme_ansi();
  8012. load_bimrc();
  8013. buffers_avail = 4;
  8014. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  8015. }
  8016. /**
  8017. * Initialize terminal for editor display.
  8018. */
  8019. void init_terminal(void) {
  8020. set_alternate_screen();
  8021. update_screen_size();
  8022. get_initial_termios();
  8023. set_unbuffered();
  8024. mouse_enable();
  8025. signal(SIGWINCH, SIGWINCH_handler);
  8026. signal(SIGCONT, SIGCONT_handler);
  8027. signal(SIGTSTP, SIGTSTP_handler);
  8028. }
  8029. int main(int argc, char * argv[]) {
  8030. int opt;
  8031. while ((opt = getopt(argc, argv, "?c:C:u:RO:-:")) != -1) {
  8032. switch (opt) {
  8033. case 'R':
  8034. global_config.initial_file_is_read_only = 1;
  8035. break;
  8036. case 'c':
  8037. case 'C':
  8038. /* Print file to stdout using our syntax highlighting and color theme */
  8039. initialize();
  8040. global_config.go_to_line = 0;
  8041. open_file(optarg);
  8042. for (int i = 0; i < env->line_count; ++i) {
  8043. if (opt == 'C') {
  8044. draw_line_number(i);
  8045. }
  8046. render_line(env->lines[i], 6 * (env->lines[i]->actual + 1), 0, i + 1);
  8047. reset();
  8048. fprintf(stdout, "\n");
  8049. }
  8050. return 0;
  8051. case 'u':
  8052. global_config.bimrc_path = optarg;
  8053. break;
  8054. case 'O':
  8055. /* Set various display options */
  8056. if (!strcmp(optarg,"noaltscreen")) global_config.can_altscreen = 0;
  8057. else if (!strcmp(optarg,"noscroll")) global_config.can_scroll = 0;
  8058. else if (!strcmp(optarg,"nomouse")) global_config.can_mouse = 0;
  8059. else if (!strcmp(optarg,"nounicode")) global_config.can_unicode = 0;
  8060. else if (!strcmp(optarg,"nobright")) global_config.can_bright = 0;
  8061. else if (!strcmp(optarg,"nohideshow")) global_config.can_hideshow = 0;
  8062. else if (!strcmp(optarg,"nosyntax")) global_config.hilight_on_open = 0;
  8063. else if (!strcmp(optarg,"nohistory")) global_config.history_enabled = 0;
  8064. else if (!strcmp(optarg,"notitle")) global_config.can_title = 0;
  8065. else if (!strcmp(optarg,"nobce")) global_config.can_bce = 0;
  8066. else {
  8067. fprintf(stderr, "%s: unrecognized -O option: %s\n", argv[0], optarg);
  8068. return 1;
  8069. }
  8070. break;
  8071. case '-':
  8072. if (!strcmp(optarg,"version")) {
  8073. fprintf(stderr, "bim %s %s\n", BIM_VERSION, BIM_COPYRIGHT);
  8074. fprintf(stderr, " Available syntax highlighters:");
  8075. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  8076. fprintf(stderr, " %s", s->name);
  8077. }
  8078. fprintf(stderr, "\n");
  8079. fprintf(stderr, " Available color themes:");
  8080. for (struct theme_def * d = themes; d->name; ++d) {
  8081. fprintf(stderr, " %s", d->name);
  8082. }
  8083. fprintf(stderr, "\n");
  8084. return 0;
  8085. } else if (!strcmp(optarg,"help")) {
  8086. show_usage(argv);
  8087. return 0;
  8088. }
  8089. break;
  8090. case '?':
  8091. show_usage(argv);
  8092. return 0;
  8093. }
  8094. }
  8095. /* Set up terminal */
  8096. initialize();
  8097. init_terminal();
  8098. /* Open file */
  8099. if (argc > optind) {
  8100. open_file(argv[optind]);
  8101. update_title();
  8102. if (global_config.initial_file_is_read_only) {
  8103. env->readonly = 1;
  8104. }
  8105. } else {
  8106. env = buffer_new();
  8107. update_title();
  8108. setup_buffer(env);
  8109. }
  8110. /* Draw the screen once */
  8111. redraw_all();
  8112. /* Start accepting key commands */
  8113. normal_mode();
  8114. return 0;
  8115. }