bim.c 359 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168
  1. /**
  2. * This is a baked, single-file version of bim.
  3. * It was built Tue Dec 17 13:18:29 2019
  4. * It is based on git commit 2f4da2036745c3f1b7d532988f346abcca0e59eb
  5. */
  6. #define GIT_TAG "2f4da20-baked"
  7. /* Bim - A Text Editor
  8. *
  9. * Copyright (C) 2012-2019 K. Lange
  10. *
  11. * Permission to use, copy, modify, and/or distribute this software for any
  12. * purpose with or without fee is hereby granted, provided that the above
  13. * copyright notice and this permission notice appear in all copies.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  16. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  17. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  18. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  19. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  20. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  21. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  22. */
  23. /* Included from bim-core.h */
  24. #define _XOPEN_SOURCE 700
  25. #define _DARWIN_C_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. #ifdef __TIMESTAMP__
  45. # define BIM_BUILD_DATE " built " __TIMESTAMP__
  46. #else
  47. # define BIM_BUILD_DATE DATE ""
  48. #endif
  49. #ifdef GIT_TAG
  50. # define TAG "-" GIT_TAG
  51. #else
  52. # define TAG ""
  53. #endif
  54. #define BIM_VERSION "2.5.1" TAG
  55. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  56. #define BLOCK_SIZE 4096
  57. #define ENTER_KEY '\r'
  58. #define LINE_FEED '\n'
  59. #define BACKSPACE_KEY 0x08
  60. #define DELETE_KEY 0x7F
  61. enum Key {
  62. KEY_TIMEOUT = -1,
  63. KEY_CTRL_AT = 0, /* Base */
  64. KEY_CTRL_A, KEY_CTRL_B, KEY_CTRL_C, KEY_CTRL_D, KEY_CTRL_E, KEY_CTRL_F, KEY_CTRL_G, KEY_CTRL_H,
  65. KEY_CTRL_I, KEY_CTRL_J, KEY_CTRL_K, KEY_CTRL_L, KEY_CTRL_M, KEY_CTRL_N, KEY_CTRL_O, KEY_CTRL_P,
  66. KEY_CTRL_Q, KEY_CTRL_R, KEY_CTRL_S, KEY_CTRL_T, KEY_CTRL_U, KEY_CTRL_V, KEY_CTRL_W, KEY_CTRL_X,
  67. KEY_CTRL_Y, KEY_CTRL_Z, /* Note we keep ctrl-z mapped in termios as suspend */
  68. KEY_CTRL_OPEN, KEY_CTRL_BACKSLASH, KEY_CTRL_CLOSE, KEY_CTRL_CARAT, KEY_CTRL_UNDERSCORE,
  69. /* Space... */
  70. /* Some of these are equivalent to things above */
  71. KEY_BACKSPACE = 0x08,
  72. KEY_LINEFEED = '\n',
  73. KEY_ENTER = '\r',
  74. KEY_TAB = '\t',
  75. /* Basic printable characters go here. */
  76. /* Delete is special */
  77. KEY_DELETE = 0x7F,
  78. /* Unicode codepoints go here */
  79. KEY_ESCAPE = 0x400000, /* Escape would normally be 27, but is special because reasons */
  80. KEY_F1, KEY_F2, KEY_F3, KEY_F4,
  81. KEY_F5, KEY_F6, KEY_F7, KEY_F8,
  82. KEY_F9, KEY_F10, KEY_F11, KEY_F12,
  83. /* TODO ALT, SHIFT, etc., for F keys */
  84. KEY_MOUSE, /* Must be followed with a 3-byte mouse read */
  85. KEY_MOUSE_SGR, /* Followed by an SGR-style sequence of mouse data */
  86. KEY_HOME, KEY_END, KEY_PAGE_UP, KEY_PAGE_DOWN,
  87. KEY_UP, KEY_DOWN, KEY_RIGHT, KEY_LEFT,
  88. KEY_SHIFT_UP, KEY_SHIFT_DOWN, KEY_SHIFT_RIGHT, KEY_SHIFT_LEFT,
  89. KEY_CTRL_UP, KEY_CTRL_DOWN, KEY_CTRL_RIGHT, KEY_CTRL_LEFT,
  90. KEY_ALT_UP, KEY_ALT_DOWN, KEY_ALT_RIGHT, KEY_ALT_LEFT,
  91. KEY_ALT_SHIFT_UP, KEY_ALT_SHIFT_DOWN, KEY_ALT_SHIFT_RIGHT, KEY_ALT_SHIFT_LEFT,
  92. KEY_SHIFT_TAB,
  93. };
  94. struct key_name_map {
  95. enum Key keycode;
  96. char * name;
  97. };
  98. extern struct key_name_map KeyNames[];
  99. /**
  100. * Syntax highlighting flags.
  101. */
  102. #define FLAG_NONE 0
  103. #define FLAG_KEYWORD 1
  104. #define FLAG_STRING 2
  105. #define FLAG_COMMENT 3
  106. #define FLAG_TYPE 4
  107. #define FLAG_PRAGMA 5
  108. #define FLAG_NUMERAL 6
  109. #define FLAG_ERROR 7
  110. #define FLAG_DIFFPLUS 8
  111. #define FLAG_DIFFMINUS 9
  112. #define FLAG_NOTICE 10
  113. #define FLAG_BOLD 11
  114. #define FLAG_LINK 12
  115. #define FLAG_ESCAPE 13
  116. #define FLAG_SELECT (1 << 5)
  117. #define FLAG_SEARCH (1 << 6)
  118. /**
  119. * Line buffer definitions
  120. *
  121. * Lines are essentially resizable vectors of char_t structs,
  122. * which represent single codepoints in the file.
  123. */
  124. typedef struct {
  125. uint32_t display_width:4;
  126. uint32_t flags:7;
  127. uint32_t codepoint:21;
  128. } __attribute__((packed)) char_t;
  129. /**
  130. * Lines have available and actual lengths, describing
  131. * how much space was allocated vs. how much is being
  132. * used at the moment.
  133. */
  134. typedef struct {
  135. int available;
  136. int actual;
  137. int istate;
  138. int is_current;
  139. int rev_status;
  140. char_t text[];
  141. } line_t;
  142. /**
  143. * Global configuration state
  144. *
  145. * At the moment, this is all in a global, but in the future
  146. * this should be passed around to various functions.
  147. */
  148. typedef struct {
  149. /* Terminal size */
  150. int term_width, term_height;
  151. int bottom_size;
  152. line_t ** yanks;
  153. size_t yank_count;
  154. int yank_is_full_lines;
  155. int tty_in;
  156. const char * bimrc_path;
  157. const char * syntax_fallback;
  158. uint32_t * search;
  159. int overlay_mode;
  160. line_t * command_buffer;
  161. int command_offset, command_col_no;
  162. struct syntax_definition * command_syn, * command_syn_back;
  163. int history_point;
  164. int search_direction;
  165. int prev_line, prev_col, prev_coffset, prev_offset;
  166. unsigned int highlight_on_open:1;
  167. unsigned int initial_file_is_read_only:1;
  168. unsigned int go_to_line:1;
  169. unsigned int break_from_selection:1;
  170. unsigned int can_scroll:1;
  171. unsigned int can_hideshow:1;
  172. unsigned int can_altscreen:1;
  173. unsigned int can_mouse:1;
  174. unsigned int can_unicode:1;
  175. unsigned int can_bright:1;
  176. unsigned int can_title:1;
  177. unsigned int can_bce:1;
  178. unsigned int can_24bit:1;
  179. unsigned int can_256color:1;
  180. unsigned int can_italic:1;
  181. unsigned int history_enabled:1;
  182. unsigned int highlight_parens:1;
  183. unsigned int smart_case:1;
  184. unsigned int highlight_current_line:1;
  185. unsigned int shift_scrolling:1;
  186. unsigned int check_git:1;
  187. unsigned int color_gutter:1;
  188. unsigned int relative_lines:1;
  189. unsigned int numbers:1;
  190. unsigned int horizontal_shift_scrolling:1;
  191. unsigned int hide_statusbar:1;
  192. unsigned int tabs_visible:1;
  193. unsigned int autohide_tabs:1;
  194. unsigned int smart_complete:1;
  195. unsigned int has_terminal:1;
  196. unsigned int use_sgr_mouse:1;
  197. int cursor_padding;
  198. int split_percent;
  199. int scroll_amount;
  200. int tab_offset;
  201. char * tab_indicator;
  202. char * space_indicator;
  203. } global_config_t;
  204. #define OVERLAY_MODE_NONE 0
  205. #define OVERLAY_MODE_READ_ONE 1
  206. #define OVERLAY_MODE_COMMAND 2
  207. #define OVERLAY_MODE_SEARCH 3
  208. #define OVERLAY_MODE_COMPLETE 4
  209. #define HISTORY_SENTINEL 0
  210. #define HISTORY_INSERT 1
  211. #define HISTORY_DELETE 2
  212. #define HISTORY_REPLACE 3
  213. #define HISTORY_REMOVE_LINE 4
  214. #define HISTORY_ADD_LINE 5
  215. #define HISTORY_REPLACE_LINE 6
  216. #define HISTORY_MERGE_LINES 7
  217. #define HISTORY_SPLIT_LINE 8
  218. #define HISTORY_BREAK 10
  219. typedef struct history {
  220. struct history * previous;
  221. struct history * next;
  222. int type;
  223. int line;
  224. int col;
  225. union {
  226. struct {
  227. int lineno;
  228. int offset;
  229. int codepoint;
  230. int old_codepoint;
  231. } insert_delete_replace;
  232. struct {
  233. int lineno;
  234. line_t * contents;
  235. line_t * old_contents;
  236. } remove_replace_line;
  237. struct {
  238. int lineno;
  239. int split;
  240. } add_merge_split_lines;
  241. } contents;
  242. } history_t;
  243. /**
  244. * Buffer data
  245. *
  246. * A buffer describes a file, and stores
  247. * its name as well as the editor state
  248. * (cursor offsets, etc.) and the actual
  249. * line buffers.
  250. */
  251. typedef struct _env {
  252. unsigned int loading:1;
  253. unsigned int tabs:1;
  254. unsigned int modified:1;
  255. unsigned int readonly:1;
  256. unsigned int indent:1;
  257. unsigned int checkgitstatusonwrite:1;
  258. unsigned int crnl:1;
  259. unsigned int numbers:1;
  260. unsigned int gutter:1;
  261. int highlighting_paren;
  262. int maxcolumn;
  263. short mode;
  264. short tabstop;
  265. char * file_name;
  266. int offset;
  267. int coffset;
  268. int line_no;
  269. int line_count;
  270. int line_avail;
  271. int col_no;
  272. int preferred_column;
  273. struct syntax_definition * syntax;
  274. line_t ** lines;
  275. history_t * history;
  276. history_t * last_save_history;
  277. int width;
  278. int left;
  279. int start_line;
  280. int sel_col;
  281. int start_col;
  282. int prev_line;
  283. } buffer_t;
  284. struct theme_def {
  285. const char * name;
  286. void (*load)(const char * name);
  287. };
  288. extern struct theme_def * themes;
  289. extern void add_colorscheme(struct theme_def theme);
  290. struct syntax_state {
  291. line_t * line;
  292. int line_no;
  293. int state;
  294. int i;
  295. };
  296. struct completion_match {
  297. char * string;
  298. char * file;
  299. char * search;
  300. };
  301. struct syntax_definition {
  302. char * name;
  303. char ** ext;
  304. int (*calculate)(struct syntax_state *);
  305. int prefers_spaces;
  306. int (*completion_qualifier)(int c);
  307. int (*completion_matcher)(uint32_t * comp, struct completion_match ** matches, int * matches_count, int complete_match, int * matches_len);
  308. };
  309. extern struct syntax_definition * syntaxes;
  310. /**
  311. * Editor mode states
  312. */
  313. #define MODE_NORMAL 0
  314. #define MODE_INSERT 1
  315. #define MODE_LINE_SELECTION 2
  316. #define MODE_REPLACE 3
  317. #define MODE_CHAR_SELECTION 4
  318. #define MODE_COL_SELECTION 5
  319. #define MODE_COL_INSERT 6
  320. #define MODE_DIRECTORY_BROWSE 7
  321. extern global_config_t global_config;
  322. extern const char * COLOR_FG;
  323. extern const char * COLOR_BG;
  324. extern const char * COLOR_ALT_FG;
  325. extern const char * COLOR_ALT_BG;
  326. extern const char * COLOR_NUMBER_FG;
  327. extern const char * COLOR_NUMBER_BG;
  328. extern const char * COLOR_STATUS_FG;
  329. extern const char * COLOR_STATUS_BG;
  330. extern const char * COLOR_STATUS_ALT;
  331. extern const char * COLOR_TABBAR_BG;
  332. extern const char * COLOR_TAB_BG;
  333. extern const char * COLOR_ERROR_FG;
  334. extern const char * COLOR_ERROR_BG;
  335. extern const char * COLOR_SEARCH_FG;
  336. extern const char * COLOR_SEARCH_BG;
  337. extern const char * COLOR_KEYWORD;
  338. extern const char * COLOR_STRING;
  339. extern const char * COLOR_COMMENT;
  340. extern const char * COLOR_TYPE;
  341. extern const char * COLOR_PRAGMA;
  342. extern const char * COLOR_NUMERAL;
  343. extern const char * COLOR_SELECTFG;
  344. extern const char * COLOR_SELECTBG;
  345. extern const char * COLOR_RED;
  346. extern const char * COLOR_GREEN;
  347. extern const char * COLOR_BOLD;
  348. extern const char * COLOR_LINK;
  349. extern const char * COLOR_ESCAPE;
  350. extern const char * current_theme;
  351. struct action_def {
  352. char * name;
  353. void (*action)();
  354. int options;
  355. const char * description;
  356. };
  357. extern struct action_def * mappable_actions;
  358. #define ARG_IS_INPUT 0x01 /* Takes the key that triggered it as the first argument */
  359. #define ARG_IS_CUSTOM 0x02 /* Takes a custom argument which is specific to the method */
  360. #define ARG_IS_PROMPT 0x04 /* Prompts for an argument. */
  361. #define ACTION_IS_RW 0x08 /* Needs to be able to write. */
  362. #define BIM_ACTION(name, options, description) \
  363. void name (); /* Define the action with unknown arguments */ \
  364. void __attribute__((constructor)) _install_ ## name (void) { \
  365. add_action((struct action_def){#name, name, options, description}); \
  366. } \
  367. void name
  368. struct command_def {
  369. char * name;
  370. int (*command)(char *, int, char * arg[]);
  371. const char * description;
  372. };
  373. #define BIM_COMMAND(cmd_name, cmd_str, description) \
  374. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  375. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  376. add_command((struct command_def){cmd_str, bim_command_ ## cmd_name, description}); \
  377. } \
  378. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  379. #define BIM_ALIAS(alias, alias_name, cmd_name) \
  380. void __attribute__((constructor)) _install_alias_ ## alias_name (void) { \
  381. add_command((struct command_def){alias, bim_command_ ## cmd_name, "Alias for " #cmd_name}); \
  382. }
  383. #define BIM_PREFIX_COMMAND(cmd_name, cmd_prefix, description) \
  384. int bim_command_ ## cmd_name (char * cmd, int argc, char * argv[]); \
  385. void __attribute__((constructor)) _install_cmd_ ## cmd_name (void) { \
  386. add_prefix_command((struct command_def){cmd_prefix, bim_command_ ## cmd_name, description}); \
  387. } \
  388. int bim_command_ ## cmd_name (char * cmd __attribute__((unused)), int argc __attribute__((unused)), char * argv[] __attribute__((unused)))
  389. extern buffer_t * env;
  390. extern buffer_t * left_buffer;
  391. extern buffer_t * right_buffer;
  392. #define NAV_BUFFER_MAX 10
  393. extern char nav_buf[NAV_BUFFER_MAX+1];
  394. extern int nav_buffer;
  395. extern int buffers_len;
  396. extern int buffers_avail;
  397. extern buffer_t ** buffers;
  398. extern const char * flag_to_color(int _flag);
  399. extern void redraw_line(int x);
  400. extern int git_examine(char * filename);
  401. extern void search_next(void);
  402. extern void set_preferred_column(void);
  403. extern void quit(const char * message);
  404. extern void close_buffer(void);
  405. extern void set_syntax_by_name(const char * name);
  406. extern void rehighlight_search(line_t * line);
  407. extern void try_to_center();
  408. extern int read_one_character(char * message);
  409. extern void bim_unget(int c);
  410. #define bim_getch() bim_getch_timeout(200)
  411. extern int bim_getch_timeout(int timeout);
  412. extern buffer_t * buffer_new(void);
  413. extern FILE * open_biminfo(void);
  414. extern int fetch_from_biminfo(buffer_t * buf);
  415. extern int update_biminfo(buffer_t * buf);
  416. extern buffer_t * buffer_close(buffer_t * buf);
  417. extern int to_eight(uint32_t codepoint, char * out);
  418. extern char * name_from_key(enum Key keycode);
  419. extern void add_action(struct action_def action);
  420. extern void open_file(char * file);
  421. extern void recalculate_selected_lines(void);
  422. extern void add_command(struct command_def command);
  423. extern void add_prefix_command(struct command_def command);
  424. extern void render_command_input_buffer(void);
  425. extern void unhighlight_matching_paren(void);
  426. extern void add_syntax(struct syntax_definition def);
  427. struct ColorName {
  428. const char * name;
  429. const char ** value;
  430. };
  431. extern struct ColorName color_names[];
  432. struct bim_function {
  433. char * command;
  434. struct bim_function * next;
  435. };
  436. extern struct bim_function ** user_functions;
  437. extern int run_function(char * name);
  438. extern int has_function(char * name);
  439. extern void find_matching_paren(int * out_line, int * out_col, int in_col);
  440. extern void render_error(char * message, ...);
  441. extern void pause_for_key(void);
  442. #define add_match(match_string, match_file, match_search) do { \
  443. if (*matches_count == *matches_len) { \
  444. (*matches_len) *= 2; \
  445. *matches = realloc(*matches, sizeof(struct completion_match) * (*matches_len)); \
  446. } \
  447. (*matches)[*matches_count].string = strdup(match_string); \
  448. (*matches)[*matches_count].file = strdup(match_file); \
  449. (*matches)[*matches_count].search = strdup(match_search); \
  450. (*matches_count)++; \
  451. } while (0)
  452. #define add_if_match(name,desc) do { \
  453. int i = 0; \
  454. while (comp[i] && comp[i] == (unsigned char)name[i]) i++; \
  455. if (comp[i] == '\0') { \
  456. add_match(name,desc,""); \
  457. } \
  458. } while (0)
  459. struct action_map {
  460. int key;
  461. void (*method)();
  462. int options;
  463. int arg;
  464. };
  465. #define opt_rep 0x1 /* This action will be repeated */
  466. #define opt_arg 0x2 /* This action will take a specified argument */
  467. #define opt_char 0x4 /* This action will read a character to pass as an argument */
  468. #define opt_nav 0x8 /* This action will consume the nav buffer as its argument */
  469. #define opt_rw 0x10 /* Must not be read-only */
  470. #define opt_norm 0x20 /* Returns to normal mode */
  471. #define opt_byte 0x40 /* Same as opt_char but forces a byte */
  472. struct mode_names {
  473. const char * description;
  474. const char * name;
  475. struct action_map ** mode;
  476. };
  477. extern struct mode_names mode_names[];
  478. /* End of bim-core.h */
  479. /* Included from bim-syntax.h */
  480. #define BIM_SYNTAX(name, spaces) \
  481. __attribute__((constructor)) static void _load_ ## name (void) { \
  482. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, NULL, NULL}); \
  483. } \
  484. #define BIM_SYNTAX_EXT(name, spaces, matcher) \
  485. __attribute__((constructor)) static void _load_ ## name (void) { \
  486. add_syntax((struct syntax_definition){#name, syn_ ## name ## _ext, syn_ ## name ## _calculate, spaces, matcher, _match_completions_ ## name}); \
  487. } \
  488. #define BIM_SYNTAX_COMPLETER(name) \
  489. static int _match_completions_ ## name ( \
  490. uint32_t * comp __attribute__((unused)), \
  491. struct completion_match **matches __attribute__((unused)), \
  492. int * matches_count __attribute__((unused)), \
  493. int complete_match __attribute__((unused)), \
  494. int *matches_len __attribute__((unused)))
  495. #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)
  496. #define charat() (state->i < state->line->actual ? state->line->text[(state->i)].codepoint : -1)
  497. #define nextchar() (state->i + 1 < state->line->actual ? state->line->text[(state->i+1)].codepoint : -1)
  498. #define lastchar() (state->i - 1 >= 0 ? state->line->text[(state->i-1)].codepoint : -1)
  499. #define skip() (state->i++)
  500. #define charrel(x) (state->i + (x) < state->line->actual ? state->line->text[(state->i+(x))].codepoint : -1)
  501. extern int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c));
  502. extern int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c));
  503. extern void paint_single_string(struct syntax_state * state);
  504. extern void paint_simple_string(struct syntax_state * state);
  505. extern int common_comment_buzzwords(struct syntax_state * state);
  506. extern int paint_comment(struct syntax_state * state);
  507. extern int match_forward(struct syntax_state * state, char * c);
  508. extern struct syntax_definition * find_syntax_calculator(const char * name);
  509. #define nest(lang, low) \
  510. do { \
  511. state->state = (state->state < 1 ? 0 : state->state - low); \
  512. do { state->state = lang(state); } while (state->state == 0); \
  513. if (state->state == -1) return low; \
  514. return state->state + low; \
  515. } while (0)
  516. /* Some of the C stuff is widely used */
  517. extern int c_keyword_qualifier(int c);
  518. extern int paint_c_numeral(struct syntax_state * state);
  519. extern int paint_c_comment(struct syntax_state * state);
  520. extern void paint_c_char(struct syntax_state * state);
  521. /* Hacky workaround for isdigit not really accepting Unicode stuff */
  522. static __attribute__((used)) int _isdigit(int c) { if (c > 128) return 0; return isdigit(c); }
  523. static __attribute__((used)) int _isxdigit(int c) { if (c > 128) return 0; return isxdigit(c); }
  524. #undef isdigit
  525. #undef isxdigit
  526. #define isdigit(c) _isdigit(c)
  527. #define isxdigit(c) _isxdigit(c)
  528. /* End of bim-syntax.h */
  529. global_config_t global_config = {
  530. /* State */
  531. .term_width = 0,
  532. .term_height = 0,
  533. .bottom_size = 2,
  534. .yanks = NULL,
  535. .yank_count = 0,
  536. .yank_is_full_lines = 0,
  537. .tty_in = STDIN_FILENO,
  538. .bimrc_path = "~/.bimrc",
  539. .syntax_fallback = NULL, /* syntax to fall back to if none other match applies */
  540. .search = NULL,
  541. .overlay_mode = OVERLAY_MODE_NONE,
  542. .command_buffer = NULL,
  543. .command_offset = 0,
  544. .command_col_no = 0,
  545. .history_point = -1,
  546. /* Bitset starts here */
  547. .highlight_on_open = 1,
  548. .initial_file_is_read_only = 0,
  549. .go_to_line = 1,
  550. .break_from_selection = 1,
  551. /* Terminal capabilities */
  552. .can_scroll = 1,
  553. .can_hideshow = 1,
  554. .can_altscreen = 1,
  555. .can_mouse = 1,
  556. .can_unicode = 1,
  557. .can_bright = 1,
  558. .can_title = 1,
  559. .can_bce = 1,
  560. .can_24bit = 1, /* can use 24-bit color */
  561. .can_256color = 1, /* can use 265 colors */
  562. .can_italic = 1, /* can use italics (without inverting) */
  563. /* Configuration options */
  564. .history_enabled = 1,
  565. .highlight_parens = 1, /* highlight parens/braces when cursor moves */
  566. .smart_case = 1, /* smart case-sensitivity while searching */
  567. .highlight_current_line = 1,
  568. .shift_scrolling = 1, /* shift rather than moving cursor*/
  569. .check_git = 0,
  570. .color_gutter = 1, /* shows modified lines */
  571. .relative_lines = 0,
  572. .numbers = 1,
  573. .horizontal_shift_scrolling = 0, /* Whether to shift the whole screen when scrolling horizontally */
  574. .hide_statusbar = 0,
  575. .tabs_visible = 1,
  576. .autohide_tabs = 0,
  577. .smart_complete = 0,
  578. .has_terminal = 0,
  579. .use_sgr_mouse = 0,
  580. /* Integer config values */
  581. .cursor_padding = 4,
  582. .split_percent = 50,
  583. .scroll_amount = 5,
  584. .tab_offset = 0,
  585. };
  586. struct key_name_map KeyNames[] = {
  587. {KEY_TIMEOUT, "[timeout]"},
  588. {KEY_BACKSPACE, "<backspace>"},
  589. {KEY_ENTER, "<enter>"},
  590. {KEY_ESCAPE, "<escape>"},
  591. {KEY_TAB, "<tab>"},
  592. {' ', "<space>"},
  593. /* These are mostly here for markdown output. */
  594. {'`', "<backtick>"},
  595. {'|', "<pipe>"},
  596. {KEY_DELETE, "<del>"},
  597. {KEY_MOUSE, "<mouse>"},
  598. {KEY_MOUSE_SGR, "<mouse-sgr>"},
  599. {KEY_F1, "<f1>"},{KEY_F2, "<f2>"},{KEY_F3, "<f3>"},{KEY_F4, "<f4>"},
  600. {KEY_F5, "<f5>"},{KEY_F6, "<f6>"},{KEY_F7, "<f7>"},{KEY_F8, "<f8>"},
  601. {KEY_F9, "<f9>"},{KEY_F10, "<f10>"},{KEY_F11, "<f11>"},{KEY_F12, "<f12>"},
  602. {KEY_HOME,"<home>"},{KEY_END,"<end>"},{KEY_PAGE_UP,"<page-up>"},{KEY_PAGE_DOWN,"<page-down>"},
  603. {KEY_UP, "<up>"},{KEY_DOWN, "<down>"},{KEY_RIGHT, "<right>"},{KEY_LEFT, "<left>"},
  604. {KEY_SHIFT_UP, "<shift-up>"},{KEY_SHIFT_DOWN, "<shift-down>"},{KEY_SHIFT_RIGHT, "<shift-right>"},{KEY_SHIFT_LEFT, "<shift-left>"},
  605. {KEY_CTRL_UP, "<ctrl-up>"},{KEY_CTRL_DOWN, "<ctrl-down>"},{KEY_CTRL_RIGHT, "<ctrl-right>"},{KEY_CTRL_LEFT, "<ctrl-left>"},
  606. {KEY_ALT_UP, "<alt-up>"},{KEY_ALT_DOWN, "<alt-down>"},{KEY_ALT_RIGHT, "<alt-right>"},{KEY_ALT_LEFT, "<alt-left>"},
  607. {KEY_ALT_SHIFT_UP, "<alt-shift-up>"},{KEY_ALT_SHIFT_DOWN, "<alt-shift-down>"},{KEY_ALT_SHIFT_RIGHT, "<alt-shift-right>"},{KEY_ALT_SHIFT_LEFT, "<alt-shift-left>"},
  608. {KEY_SHIFT_TAB,"<shift-tab>"},
  609. };
  610. char * name_from_key(enum Key keycode) {
  611. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  612. if (KeyNames[i].keycode == keycode) return KeyNames[i].name;
  613. }
  614. static char keyNameTmp[8] = {0};
  615. if (keycode <= KEY_CTRL_UNDERSCORE) {
  616. keyNameTmp[0] = '^';
  617. keyNameTmp[1] = '@' + keycode;
  618. keyNameTmp[2] = 0;
  619. return keyNameTmp;
  620. }
  621. to_eight(keycode, keyNameTmp);
  622. return keyNameTmp;
  623. }
  624. struct ColorName color_names[] = {
  625. {"text-fg", &COLOR_FG},
  626. {"text-bg", &COLOR_BG},
  627. {"alternate-fg", &COLOR_ALT_FG},
  628. {"alternate-bg", &COLOR_ALT_BG},
  629. {"number-fg", &COLOR_NUMBER_FG},
  630. {"number-bg", &COLOR_NUMBER_BG},
  631. {"status-fg", &COLOR_STATUS_FG},
  632. {"status-bg", &COLOR_STATUS_BG},
  633. {"status-alt", &COLOR_STATUS_ALT},
  634. {"tabbar-bg", &COLOR_TABBAR_BG},
  635. {"tab-bg", &COLOR_TAB_BG},
  636. {"error-fg", &COLOR_ERROR_FG},
  637. {"error-bg", &COLOR_ERROR_BG},
  638. {"search-fg", &COLOR_SEARCH_FG},
  639. {"search-bg", &COLOR_SEARCH_BG},
  640. {"keyword", &COLOR_KEYWORD},
  641. {"string", &COLOR_STRING},
  642. {"comment", &COLOR_COMMENT},
  643. {"type", &COLOR_TYPE},
  644. {"pragma", &COLOR_PRAGMA},
  645. {"numeral", &COLOR_NUMERAL},
  646. {"select-fg", &COLOR_SELECTFG},
  647. {"select-bg", &COLOR_SELECTBG},
  648. {"red", &COLOR_RED},
  649. {"green", &COLOR_GREEN},
  650. {"bold", &COLOR_BOLD},
  651. {"link", &COLOR_LINK},
  652. {"escape", &COLOR_ESCAPE},
  653. {NULL,NULL},
  654. };
  655. #define FLEXIBLE_ARRAY(name, add_name, type, zero) \
  656. int flex_ ## name ## _count = 0; \
  657. int flex_ ## name ## _space = 0; \
  658. type * name = NULL; \
  659. void add_name (type input) { \
  660. if (flex_ ## name ## _space == 0) { \
  661. flex_ ## name ## _space = 4; \
  662. name = calloc(sizeof(type), flex_ ## name ## _space); \
  663. } else if (flex_ ## name ## _count + 1 == flex_ ## name ## _space) { \
  664. flex_ ## name ## _space *= 2; \
  665. name = realloc(name, sizeof(type) * flex_ ## name ## _space); \
  666. for (int i = flex_ ## name ## _count; i < flex_ ## name ## _space; ++i) name[i] = zero; \
  667. } \
  668. name[flex_ ## name ## _count] = input; \
  669. flex_ ## name ## _count ++; \
  670. }
  671. FLEXIBLE_ARRAY(mappable_actions, add_action, struct action_def, ((struct action_def){NULL,NULL,0,NULL}))
  672. FLEXIBLE_ARRAY(regular_commands, add_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  673. FLEXIBLE_ARRAY(prefix_commands, add_prefix_command, struct command_def, ((struct command_def){NULL,NULL,NULL}))
  674. FLEXIBLE_ARRAY(themes, add_colorscheme, struct theme_def, ((struct theme_def){NULL,NULL}))
  675. FLEXIBLE_ARRAY(user_functions, add_user_function, struct bim_function *, NULL)
  676. /**
  677. * Special implementation of getch with a timeout
  678. */
  679. int _bim_unget = -1;
  680. void bim_unget(int c) {
  681. _bim_unget = c;
  682. }
  683. int bim_getch_timeout(int timeout) {
  684. fflush(stdout);
  685. if (_bim_unget != -1) {
  686. int out = _bim_unget;
  687. _bim_unget = -1;
  688. return out;
  689. }
  690. struct pollfd fds[1];
  691. fds[0].fd = global_config.tty_in;
  692. fds[0].events = POLLIN;
  693. int ret = poll(fds,1,timeout);
  694. if (ret > 0 && fds[0].revents & POLLIN) {
  695. unsigned char buf[1];
  696. read(global_config.tty_in, buf, 1);
  697. return buf[0];
  698. } else {
  699. return -1;
  700. }
  701. }
  702. /**
  703. * UTF-8 parser state
  704. */
  705. static uint32_t codepoint_r;
  706. static uint32_t state = 0;
  707. #define UTF8_ACCEPT 0
  708. #define UTF8_REJECT 1
  709. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  710. static int state_table[32] = {
  711. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  712. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  713. 2,2,2,2, /* 110xxxxx */
  714. 3,3, /* 1110xxxx */
  715. 4, /* 11110xxx */
  716. 1 /* 11111xxx */
  717. };
  718. static int mask_bytes[32] = {
  719. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  720. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  721. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  722. 0x1F,0x1F,0x1F,0x1F,
  723. 0x0F,0x0F,
  724. 0x07,
  725. 0x00
  726. };
  727. static int next[5] = {
  728. 0,
  729. 1,
  730. 0,
  731. 2,
  732. 3
  733. };
  734. if (*state == UTF8_ACCEPT) {
  735. *codep = byte & mask_bytes[byte >> 3];
  736. *state = state_table[byte >> 3];
  737. } else if (*state > 0) {
  738. *codep = (byte & 0x3F) | (*codep << 6);
  739. *state = next[*state];
  740. }
  741. return *state;
  742. }
  743. #define shift_key(i) _shift_key((i), this_buf, &timeout);
  744. int _shift_key(int i, int this_buf[20], int *timeout) {
  745. int thing = this_buf[*timeout-1];
  746. (*timeout) = 0;
  747. switch (thing) {
  748. /* There are other combinations we can handle... */
  749. case '2': return i + 4;
  750. case '5': return i + 8;
  751. case '3': return i + 12;
  752. case '4': return i + 16;
  753. default: return i;
  754. }
  755. }
  756. int bim_getkey(int read_timeout) {
  757. int timeout = 0;
  758. int this_buf[20];
  759. int cin;
  760. uint32_t c;
  761. uint32_t istate = 0;
  762. while ((cin = bim_getch_timeout(read_timeout))) {
  763. if (cin == -1) {
  764. if (timeout && this_buf[timeout-1] == '\033')
  765. return KEY_ESCAPE;
  766. return KEY_TIMEOUT;
  767. }
  768. if (!decode(&istate, &c, cin)) {
  769. if (timeout == 0) {
  770. switch (c) {
  771. case '\033':
  772. if (timeout == 0) {
  773. this_buf[timeout] = c;
  774. timeout++;
  775. }
  776. continue;
  777. case KEY_LINEFEED: return KEY_ENTER;
  778. case KEY_DELETE: return KEY_BACKSPACE;
  779. }
  780. return c;
  781. } else {
  782. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '\033') {
  783. bim_unget(c);
  784. timeout = 0;
  785. return KEY_ESCAPE;
  786. }
  787. if (timeout >= 1 && this_buf[0] == '\033' && c == 'O') {
  788. this_buf[timeout] = c;
  789. timeout++;
  790. continue;
  791. }
  792. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == 'O') {
  793. switch (c) {
  794. case 'P': timeout = 0; return KEY_F1;
  795. case 'Q': timeout = 0; return KEY_F2;
  796. case 'R': timeout = 0; return KEY_F3;
  797. case 'S': timeout = 0; return KEY_F4;
  798. }
  799. timeout = 0;
  800. continue;
  801. }
  802. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c != '[') {
  803. timeout = 0;
  804. bim_unget(c);
  805. return KEY_ESCAPE;
  806. }
  807. if (timeout >= 1 && this_buf[timeout-1] == '\033' && c == '[') {
  808. timeout = 1;
  809. this_buf[timeout] = c;
  810. timeout++;
  811. continue;
  812. }
  813. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  814. (isdigit(c) || (c == ';'))) {
  815. this_buf[timeout] = c;
  816. timeout++;
  817. continue;
  818. }
  819. if (timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  820. switch (c) {
  821. case 'M': timeout = 0; return KEY_MOUSE;
  822. case '<': timeout = 0; return KEY_MOUSE_SGR;
  823. case 'A': return shift_key(KEY_UP);
  824. case 'B': return shift_key(KEY_DOWN);
  825. case 'C': return shift_key(KEY_RIGHT);
  826. case 'D': return shift_key(KEY_LEFT);
  827. case 'H': timeout = 0; return KEY_HOME;
  828. case 'F': timeout = 0; return KEY_END;
  829. case 'I': timeout = 0; return KEY_PAGE_UP;
  830. case 'G': timeout = 0; return KEY_PAGE_DOWN;
  831. case 'Z': timeout = 0; return KEY_SHIFT_TAB;
  832. case '~':
  833. if (timeout == 3) {
  834. switch (this_buf[2]) {
  835. case '1': timeout = 0; return KEY_HOME;
  836. case '3': timeout = 0; return KEY_DELETE;
  837. case '4': timeout = 0; return KEY_END;
  838. case '5': timeout = 0; return KEY_PAGE_UP;
  839. case '6': timeout = 0; return KEY_PAGE_DOWN;
  840. }
  841. } else if (this_buf[2] == '1') {
  842. switch (this_buf[3]) {
  843. case '5': return KEY_F5;
  844. case '7': return KEY_F6;
  845. case '8': return KEY_F7;
  846. case '9': return KEY_F8;
  847. }
  848. } else if (this_buf[2] == '2') {
  849. switch (this_buf[3]) {
  850. case '0': return KEY_F9;
  851. case '1': return KEY_F10;
  852. case '3': return KEY_F11;
  853. case '4': return KEY_F12;
  854. }
  855. }
  856. break;
  857. }
  858. }
  859. timeout = 0;
  860. continue;
  861. }
  862. } else if (istate == UTF8_REJECT) {
  863. istate = 0;
  864. }
  865. }
  866. return KEY_TIMEOUT;
  867. }
  868. enum Key key_from_name(char * name) {
  869. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  870. if (!strcmp(KeyNames[i].name, name)) return KeyNames[i].keycode;
  871. }
  872. if (name[0] == '^' && name[1] && !name[2]) {
  873. return name[1] - '@';
  874. }
  875. if (!name[1]) return name[0];
  876. /* Try decoding */
  877. uint32_t c, state = 0;
  878. int candidate = -1;
  879. while (*name) {
  880. if (!decode(&state, &c, (unsigned char)*name)) {
  881. if (candidate == -1) candidate = c;
  882. else return -1; /* Multiple characters */
  883. } else if (state == UTF8_REJECT) {
  884. return -1;
  885. }
  886. }
  887. return candidate;
  888. }
  889. /**
  890. * Pointer to current active buffer
  891. */
  892. buffer_t * env = NULL;
  893. buffer_t * left_buffer = NULL;
  894. buffer_t * right_buffer = NULL;
  895. /**
  896. * A buffer for holding a number (line, repetition count)
  897. */
  898. char nav_buf[NAV_BUFFER_MAX+1];
  899. int nav_buffer = 0;
  900. /**
  901. * Available buffers
  902. */
  903. int buffers_len = 0;
  904. int buffers_avail = 0;
  905. buffer_t ** buffers = NULL;
  906. /**
  907. * Create a new buffer
  908. */
  909. buffer_t * buffer_new(void) {
  910. if (buffers_len == buffers_avail) {
  911. /* If we are out of buffer space, expand the buffers vector */
  912. buffers_avail *= 2;
  913. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  914. }
  915. /* TODO: Support having split buffers with more than two buffers open */
  916. if (left_buffer) {
  917. left_buffer->left = 0;
  918. left_buffer->width = global_config.term_width;
  919. right_buffer->left = 0;
  920. right_buffer->width = global_config.term_width;
  921. left_buffer = NULL;
  922. right_buffer = NULL;
  923. }
  924. /* Allocate a new buffer */
  925. buffers[buffers_len] = malloc(sizeof(buffer_t));
  926. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  927. buffers[buffers_len]->left = 0;
  928. buffers[buffers_len]->width = global_config.term_width;
  929. buffers[buffers_len]->highlighting_paren = -1;
  930. buffers[buffers_len]->numbers = global_config.numbers;
  931. buffers[buffers_len]->gutter = 1;
  932. buffers_len++;
  933. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  934. return buffers[buffers_len-1];
  935. }
  936. /**
  937. * Open the biminfo file.
  938. */
  939. FILE * open_biminfo(void) {
  940. /* TODO This should probably be configurable line bimrc */
  941. char * home = getenv("HOME");
  942. if (!home) {
  943. /* Since it's not, we need HOME */
  944. return NULL;
  945. }
  946. /* biminfo lives at ~/.biminfo */
  947. char biminfo_path[PATH_MAX+1] = {0};
  948. sprintf(biminfo_path,"%s/.biminfo",home);
  949. /* Try to open normally first... */
  950. FILE * biminfo = fopen(biminfo_path,"r+");
  951. if (!biminfo) {
  952. /* Otherwise, try to create it. */
  953. biminfo = fopen(biminfo_path,"w+");
  954. }
  955. return biminfo;
  956. }
  957. /**
  958. * Fetch the cursor position from a biminfo file
  959. */
  960. int fetch_from_biminfo(buffer_t * buf) {
  961. /* Can't fetch if we don't have a filename */
  962. if (!buf->file_name) return 1;
  963. /* Get the absolute name of the file */
  964. char tmp_path[PATH_MAX+2];
  965. if (!realpath(buf->file_name, tmp_path)) {
  966. return 1;
  967. }
  968. strcat(tmp_path," ");
  969. FILE * biminfo = open_biminfo();
  970. if (!biminfo) return 1;
  971. /* Scan */
  972. char line[PATH_MAX+64];
  973. while (!feof(biminfo)) {
  974. fpos_t start_of_line;
  975. fgetpos(biminfo, &start_of_line);
  976. fgets(line, PATH_MAX+63, biminfo);
  977. if (line[0] != '>') {
  978. continue;
  979. }
  980. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  981. /* Read */
  982. sscanf(line+1+strlen(tmp_path)+1,"%d",&buf->line_no);
  983. sscanf(line+1+strlen(tmp_path)+21,"%d",&buf->col_no);
  984. if (buf->line_no > buf->line_count) buf->line_no = buf->line_count;
  985. if (buf->col_no > buf->lines[buf->line_no-1]->actual) buf->col_no = buf->lines[buf->line_no-1]->actual;
  986. try_to_center();
  987. return 0;
  988. }
  989. }
  990. return 0;
  991. }
  992. /**
  993. * Write a file containing the last cursor position of a buffer.
  994. */
  995. int update_biminfo(buffer_t * buf) {
  996. if (!buf->file_name) return 1;
  997. /* Get the absolute name of the file */
  998. char tmp_path[PATH_MAX+1];
  999. if (!realpath(buf->file_name, tmp_path)) {
  1000. return 1;
  1001. }
  1002. strcat(tmp_path," ");
  1003. FILE * biminfo = open_biminfo();
  1004. if (!biminfo) return 1;
  1005. /* Scan */
  1006. char line[PATH_MAX+64];
  1007. while (!feof(biminfo)) {
  1008. fpos_t start_of_line;
  1009. fgetpos(biminfo, &start_of_line);
  1010. fgets(line, PATH_MAX+63, biminfo);
  1011. if (line[0] != '>') {
  1012. continue;
  1013. }
  1014. if (!strncmp(&line[1],tmp_path, strlen(tmp_path))) {
  1015. /* Update */
  1016. fsetpos(biminfo, &start_of_line);
  1017. fprintf(biminfo,">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1018. goto _done;
  1019. }
  1020. }
  1021. if (ftell(biminfo) == 0) {
  1022. /* New biminfo */
  1023. fprintf(biminfo, "# This is a biminfo file.\n");
  1024. fprintf(biminfo, "# It was generated by bim. Do not edit it by hand!\n");
  1025. fprintf(biminfo, "# Cursor positions and other state are stored here.\n");
  1026. }
  1027. /* Haven't found what we're looking for, should be at end of file */
  1028. fprintf(biminfo, ">%s %20d %20d\n", tmp_path, buf->line_no, buf->col_no);
  1029. _done:
  1030. fclose(biminfo);
  1031. return 0;
  1032. }
  1033. /**
  1034. * Close a buffer
  1035. */
  1036. buffer_t * buffer_close(buffer_t * buf) {
  1037. int i;
  1038. /* Locate the buffer in the buffer pointer vector */
  1039. for (i = 0; i < buffers_len; i++) {
  1040. if (buf == buffers[i])
  1041. break;
  1042. }
  1043. /* Invalid buffer? */
  1044. if (i == buffers_len) {
  1045. return env; /* wtf */
  1046. }
  1047. update_biminfo(buf);
  1048. /* Clean up lines used by old buffer */
  1049. for (int i = 0; i < buf->line_count; ++i) {
  1050. free(buf->lines[i]);
  1051. }
  1052. free(buf->lines);
  1053. if (buf->file_name) {
  1054. free(buf->file_name);
  1055. }
  1056. history_t * h = buf->history;
  1057. while (h->next) {
  1058. h = h->next;
  1059. }
  1060. while (h) {
  1061. history_t * x = h->previous;
  1062. free(h);
  1063. h = x;
  1064. }
  1065. /* Clean up the old buffer */
  1066. free(buf);
  1067. /* Remove the buffer from the vector, moving others up */
  1068. if (i != buffers_len - 1) {
  1069. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  1070. }
  1071. /* There is one less buffer */
  1072. buffers_len--;
  1073. if (buffers_len && global_config.tab_offset >= buffers_len) global_config.tab_offset--;
  1074. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  1075. if (!buffers_len) {
  1076. /* There are no more buffers. */
  1077. return NULL;
  1078. }
  1079. /* If this was the last buffer, return the previous last buffer */
  1080. if (i == buffers_len) {
  1081. return buffers[buffers_len-1];
  1082. }
  1083. /* Otherwise return the new last buffer */
  1084. return buffers[i];
  1085. }
  1086. /**
  1087. * Theming data
  1088. *
  1089. * This default set is pretty simple "default foreground on default background"
  1090. * except for search and selections which are black-on-white specifically.
  1091. *
  1092. * The theme colors get set by separate configurable themes.
  1093. */
  1094. const char * COLOR_FG = "@9";
  1095. const char * COLOR_BG = "@9";
  1096. const char * COLOR_ALT_FG = "@9";
  1097. const char * COLOR_ALT_BG = "@9";
  1098. const char * COLOR_NUMBER_FG = "@9";
  1099. const char * COLOR_NUMBER_BG = "@9";
  1100. const char * COLOR_STATUS_FG = "@9";
  1101. const char * COLOR_STATUS_BG = "@9";
  1102. const char * COLOR_STATUS_ALT= "@9";
  1103. const char * COLOR_TABBAR_BG = "@9";
  1104. const char * COLOR_TAB_BG = "@9";
  1105. const char * COLOR_ERROR_FG = "@9";
  1106. const char * COLOR_ERROR_BG = "@9";
  1107. const char * COLOR_SEARCH_FG = "@0";
  1108. const char * COLOR_SEARCH_BG = "@17";
  1109. const char * COLOR_KEYWORD = "@9";
  1110. const char * COLOR_STRING = "@9";
  1111. const char * COLOR_COMMENT = "@9";
  1112. const char * COLOR_TYPE = "@9";
  1113. const char * COLOR_PRAGMA = "@9";
  1114. const char * COLOR_NUMERAL = "@9";
  1115. const char * COLOR_SELECTFG = "@0";
  1116. const char * COLOR_SELECTBG = "@17";
  1117. const char * COLOR_RED = "@1";
  1118. const char * COLOR_GREEN = "@2";
  1119. const char * COLOR_BOLD = "@9";
  1120. const char * COLOR_LINK = "@9";
  1121. const char * COLOR_ESCAPE = "@9";
  1122. const char * current_theme = "none";
  1123. /**
  1124. * Convert syntax highlighting flag to color code
  1125. */
  1126. const char * flag_to_color(int _flag) {
  1127. int flag = _flag & 0xF;
  1128. switch (flag) {
  1129. case FLAG_KEYWORD:
  1130. return COLOR_KEYWORD;
  1131. case FLAG_STRING:
  1132. return COLOR_STRING;
  1133. case FLAG_COMMENT:
  1134. return COLOR_COMMENT;
  1135. case FLAG_TYPE:
  1136. return COLOR_TYPE;
  1137. case FLAG_NUMERAL:
  1138. return COLOR_NUMERAL;
  1139. case FLAG_PRAGMA:
  1140. return COLOR_PRAGMA;
  1141. case FLAG_DIFFPLUS:
  1142. return COLOR_GREEN;
  1143. case FLAG_DIFFMINUS:
  1144. return COLOR_RED;
  1145. case FLAG_SELECT:
  1146. return COLOR_FG;
  1147. case FLAG_BOLD:
  1148. return COLOR_BOLD;
  1149. case FLAG_LINK:
  1150. return COLOR_LINK;
  1151. case FLAG_ESCAPE:
  1152. return COLOR_ESCAPE;
  1153. default:
  1154. return COLOR_FG;
  1155. }
  1156. }
  1157. /**
  1158. * Find keywords from a list and paint them, assuming they aren't in the middle of other words.
  1159. * Returns 1 if a keyword from the last was found, otherwise 0.
  1160. */
  1161. int find_keywords(struct syntax_state * state, char ** keywords, int flag, int (*keyword_qualifier)(int c)) {
  1162. if (keyword_qualifier(lastchar())) return 0;
  1163. if (!keyword_qualifier(charat())) return 0;
  1164. for (char ** keyword = keywords; *keyword; ++keyword) {
  1165. int d = 0;
  1166. while (state->i + d < state->line->actual && state->line->text[state->i+d].codepoint == (*keyword)[d]) d++;
  1167. if ((*keyword)[d] == '\0' && (state->i + d >= state->line->actual || !keyword_qualifier(state->line->text[state->i+d].codepoint))) {
  1168. paint((int)strlen(*keyword), flag);
  1169. return 1;
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. /**
  1175. * Match and paint a single keyword. Returns 1 if the keyword was matched and 0 otherwise,
  1176. * so it can be used for prefix checking for things that need further special handling.
  1177. */
  1178. int match_and_paint(struct syntax_state * state, const char * keyword, int flag, int (*keyword_qualifier)(int c)) {
  1179. if (keyword_qualifier(lastchar())) return 0;
  1180. if (!keyword_qualifier(charat())) return 0;
  1181. int i = state->i;
  1182. int slen = 0;
  1183. while (i < state->line->actual || *keyword == '\0') {
  1184. if (*keyword == '\0' && (i >= state->line->actual || !keyword_qualifier(state->line->text[i].codepoint))) {
  1185. for (int j = 0; j < slen; ++j) {
  1186. paint(1, flag);
  1187. }
  1188. return 1;
  1189. }
  1190. if (*keyword != state->line->text[i].codepoint) return 0;
  1191. i++;
  1192. keyword++;
  1193. slen++;
  1194. }
  1195. return 0;
  1196. }
  1197. void paint_single_string(struct syntax_state * state) {
  1198. paint(1, FLAG_STRING);
  1199. while (charat() != -1) {
  1200. if (charat() == '\\' && nextchar() == '\'') {
  1201. paint(2, FLAG_ESCAPE);
  1202. } else if (charat() == '\'') {
  1203. paint(1, FLAG_STRING);
  1204. return;
  1205. } else if (charat() == '\\') {
  1206. paint(2, FLAG_ESCAPE);
  1207. } else {
  1208. paint(1, FLAG_STRING);
  1209. }
  1210. }
  1211. }
  1212. void paint_simple_string(struct syntax_state * state) {
  1213. /* Assumes you came in from a check of charat() == '"' */
  1214. paint(1, FLAG_STRING);
  1215. while (charat() != -1) {
  1216. if (charat() == '\\' && nextchar() == '"') {
  1217. paint(2, FLAG_ESCAPE);
  1218. } else if (charat() == '"') {
  1219. paint(1, FLAG_STRING);
  1220. return;
  1221. } else if (charat() == '\\') {
  1222. paint(2, FLAG_ESCAPE);
  1223. } else {
  1224. paint(1, FLAG_STRING);
  1225. }
  1226. }
  1227. }
  1228. /**
  1229. * This is a basic character matcher for "keyword" characters.
  1230. */
  1231. int simple_keyword_qualifier(int c) {
  1232. return isalnum(c) || (c == '_');
  1233. }
  1234. /**
  1235. * These words can appear in comments and should be highlighted.
  1236. * Since there are a lot of comment highlighters, let's break them out.
  1237. */
  1238. int common_comment_buzzwords(struct syntax_state * state) {
  1239. if (match_and_paint(state, "TODO", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1240. else if (match_and_paint(state, "XXX", FLAG_NOTICE, simple_keyword_qualifier)) { return 1; }
  1241. else if (match_and_paint(state, "FIXME", FLAG_ERROR, simple_keyword_qualifier)) { return 1; }
  1242. return 0;
  1243. }
  1244. /**
  1245. * Paint a comment until end of line, assumes this comment can not continue.
  1246. * (Some languages have comments that can continue with a \ - don't use this!)
  1247. * Assumes you've already painted your comment start characters.
  1248. */
  1249. int paint_comment(struct syntax_state * state) {
  1250. while (charat() != -1) {
  1251. if (common_comment_buzzwords(state)) continue;
  1252. else { paint(1, FLAG_COMMENT); }
  1253. }
  1254. return -1;
  1255. }
  1256. /**
  1257. * Match a word forward and return whether it was matched.
  1258. */
  1259. int match_forward(struct syntax_state * state, char * c) {
  1260. int i = 0;
  1261. while (1) {
  1262. if (charrel(i) == -1 && !*c) return 1;
  1263. if (charrel(i) != *c) return 0;
  1264. c++;
  1265. i++;
  1266. }
  1267. return 0;
  1268. }
  1269. /**
  1270. * Find and return a highlighter by name, or NULL
  1271. */
  1272. struct syntax_definition * find_syntax_calculator(const char * name) {
  1273. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  1274. if (!strcmp(s->name, name)) {
  1275. return s;
  1276. }
  1277. }
  1278. return NULL;
  1279. }
  1280. int syntax_count = 0;
  1281. int syntax_space = 0;
  1282. struct syntax_definition * syntaxes = NULL;
  1283. void add_syntax(struct syntax_definition def) {
  1284. if (syntax_space == 0) {
  1285. syntax_space = 4;
  1286. syntaxes = calloc(sizeof(struct syntax_definition), syntax_space);
  1287. } else if (syntax_count +1 == syntax_space) {
  1288. syntax_space *= 2;
  1289. syntaxes = realloc(syntaxes, sizeof(struct syntax_definition) * syntax_space);
  1290. for (int i = syntax_count; i < syntax_space; ++i) syntaxes[i].name = NULL;
  1291. }
  1292. syntaxes[syntax_count] = def;
  1293. syntax_count++;
  1294. }
  1295. /**
  1296. * Calculate syntax highlighting for the given line.
  1297. */
  1298. void recalculate_syntax(line_t * line, int line_no) {
  1299. /* Clear syntax for this line first */
  1300. int is_original = 1;
  1301. while (1) {
  1302. for (int i = 0; i < line->actual; ++i) {
  1303. line->text[i].flags = 0;
  1304. }
  1305. if (!env->syntax) {
  1306. if (line_no != -1) rehighlight_search(line);
  1307. return;
  1308. }
  1309. /* Start from the line's stored in initial state */
  1310. struct syntax_state state;
  1311. state.line = line;
  1312. state.line_no = line_no;
  1313. state.state = line->istate;
  1314. state.i = 0;
  1315. while (1) {
  1316. state.state = env->syntax->calculate(&state);
  1317. if (state.state != 0) {
  1318. if (line_no == -1) return;
  1319. rehighlight_search(line);
  1320. if (!is_original) {
  1321. redraw_line(line_no);
  1322. }
  1323. if (line_no + 1 < env->line_count && env->lines[line_no+1]->istate != state.state) {
  1324. line_no++;
  1325. line = env->lines[line_no];
  1326. line->istate = state.state;
  1327. if (env->loading) return;
  1328. is_original = 0;
  1329. goto _next;
  1330. }
  1331. return;
  1332. }
  1333. }
  1334. _next:
  1335. (void)0;
  1336. }
  1337. }
  1338. /**
  1339. * Recalculate tab widths.
  1340. */
  1341. void recalculate_tabs(line_t * line) {
  1342. if (env->loading) return;
  1343. int j = 0;
  1344. for (int i = 0; i < line->actual; ++i) {
  1345. if (line->text[i].codepoint == '\t') {
  1346. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1347. }
  1348. j += line->text[i].display_width;
  1349. }
  1350. }
  1351. /**
  1352. * TODO:
  1353. *
  1354. * The line editing functions should probably take a buffer_t *
  1355. * so that they can act on buffers other than the active one.
  1356. */
  1357. void recursive_history_free(history_t * root) {
  1358. if (!root->next) return;
  1359. history_t * n = root->next;
  1360. recursive_history_free(n);
  1361. switch (n->type) {
  1362. case HISTORY_REPLACE_LINE:
  1363. free(n->contents.remove_replace_line.contents);
  1364. /* fall-through */
  1365. case HISTORY_REMOVE_LINE:
  1366. free(n->contents.remove_replace_line.old_contents);
  1367. break;
  1368. default:
  1369. /* Nothing extra to free */
  1370. break;
  1371. }
  1372. free(n);
  1373. root->next = NULL;
  1374. }
  1375. #define HIST_APPEND(e) do { \
  1376. e->col = env->col_no; \
  1377. e->line = env->line_no; \
  1378. if (env->history) { \
  1379. e->previous = env->history; \
  1380. recursive_history_free(env->history); \
  1381. env->history->next = e; \
  1382. e->next = NULL; \
  1383. } \
  1384. env->history = e; \
  1385. } while (0)
  1386. /**
  1387. * Mark a point where a complete set of actions has ended.
  1388. */
  1389. void set_history_break(void) {
  1390. if (!global_config.history_enabled) return;
  1391. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1392. history_t * e = malloc(sizeof(history_t));
  1393. e->type = HISTORY_BREAK;
  1394. HIST_APPEND(e);
  1395. }
  1396. }
  1397. /**
  1398. * Insert a character into an existing line.
  1399. */
  1400. __attribute__((warn_unused_result)) line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1401. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1402. history_t * e = malloc(sizeof(history_t));
  1403. e->type = HISTORY_INSERT;
  1404. e->contents.insert_delete_replace.lineno = lineno;
  1405. e->contents.insert_delete_replace.offset = offset;
  1406. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1407. HIST_APPEND(e);
  1408. }
  1409. /* If there is not enough space... */
  1410. if (line->actual == line->available) {
  1411. /* Expand the line buffer */
  1412. if (line->available == 0) {
  1413. line->available = 8;
  1414. } else {
  1415. line->available *= 2;
  1416. }
  1417. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1418. }
  1419. /* If this was not the last character, then shift remaining characters forward. */
  1420. if (offset < line->actual) {
  1421. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1422. }
  1423. /* Insert the new character */
  1424. line->text[offset] = c;
  1425. /* There is one new character in the line */
  1426. line->actual += 1;
  1427. if (!env->loading) {
  1428. line->rev_status = 2; /* Modified */
  1429. recalculate_tabs(line);
  1430. recalculate_syntax(line, lineno);
  1431. }
  1432. return line;
  1433. }
  1434. /**
  1435. * Delete a character from a line
  1436. */
  1437. void line_delete(line_t * line, int offset, int lineno) {
  1438. /* Can't delete character before start of line. */
  1439. if (offset == 0) return;
  1440. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1441. history_t * e = malloc(sizeof(history_t));
  1442. e->type = HISTORY_DELETE;
  1443. e->contents.insert_delete_replace.lineno = lineno;
  1444. e->contents.insert_delete_replace.offset = offset;
  1445. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1446. HIST_APPEND(e);
  1447. }
  1448. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1449. if (offset < line->actual) {
  1450. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1451. }
  1452. /* The line is one character shorter */
  1453. line->actual -= 1;
  1454. line->rev_status = 2;
  1455. recalculate_tabs(line);
  1456. recalculate_syntax(line, lineno);
  1457. }
  1458. /**
  1459. * Replace a character in a line
  1460. */
  1461. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1462. if (!env->loading && global_config.history_enabled && lineno != -1) {
  1463. history_t * e = malloc(sizeof(history_t));
  1464. e->type = HISTORY_REPLACE;
  1465. e->contents.insert_delete_replace.lineno = lineno;
  1466. e->contents.insert_delete_replace.offset = offset;
  1467. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1468. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1469. HIST_APPEND(e);
  1470. }
  1471. line->text[offset] = _c;
  1472. if (!env->loading) {
  1473. line->rev_status = 2; /* Modified */
  1474. recalculate_tabs(line);
  1475. recalculate_syntax(line, lineno);
  1476. }
  1477. }
  1478. /**
  1479. * Remove a line from the active buffer
  1480. */
  1481. line_t ** remove_line(line_t ** lines, int offset) {
  1482. /* If there is only one line, clear it instead of removing it. */
  1483. if (env->line_count == 1) {
  1484. while (lines[offset]->actual > 0) {
  1485. line_delete(lines[offset], lines[offset]->actual, offset);
  1486. }
  1487. return lines;
  1488. }
  1489. if (!env->loading && global_config.history_enabled) {
  1490. history_t * e = malloc(sizeof(history_t));
  1491. e->type = HISTORY_REMOVE_LINE;
  1492. e->contents.remove_replace_line.lineno = offset;
  1493. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1494. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1495. HIST_APPEND(e);
  1496. }
  1497. /* Otherwise, free the data used by the line */
  1498. free(lines[offset]);
  1499. /* Move other lines up */
  1500. if (offset < env->line_count-1) {
  1501. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1502. lines[env->line_count-1] = NULL;
  1503. }
  1504. /* There is one less line */
  1505. env->line_count -= 1;
  1506. return lines;
  1507. }
  1508. /**
  1509. * Add a new line to the active buffer.
  1510. */
  1511. line_t ** add_line(line_t ** lines, int offset) {
  1512. /* Invalid offset? */
  1513. if (offset > env->line_count) return lines;
  1514. if (!env->loading && global_config.history_enabled) {
  1515. history_t * e = malloc(sizeof(history_t));
  1516. e->type = HISTORY_ADD_LINE;
  1517. e->contents.add_merge_split_lines.lineno = offset;
  1518. HIST_APPEND(e);
  1519. }
  1520. /* Not enough space */
  1521. if (env->line_count == env->line_avail) {
  1522. /* Allocate more space */
  1523. env->line_avail *= 2;
  1524. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1525. }
  1526. /* If this isn't the last line, move other lines down */
  1527. if (offset < env->line_count) {
  1528. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1529. }
  1530. /* Allocate the new line */
  1531. lines[offset] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1532. lines[offset]->available = 32;
  1533. /* There is one new line */
  1534. env->line_count += 1;
  1535. env->lines = lines;
  1536. if (!env->loading) {
  1537. lines[offset]->rev_status = 2; /* Modified */
  1538. }
  1539. if (offset > 0 && !env->loading) {
  1540. recalculate_syntax(lines[offset-1],offset-1);
  1541. }
  1542. return lines;
  1543. }
  1544. /**
  1545. * Replace a line with data from another line (used by paste to paste yanked lines)
  1546. */
  1547. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1548. if (!env->loading && global_config.history_enabled) {
  1549. history_t * e = malloc(sizeof(history_t));
  1550. e->type = HISTORY_REPLACE_LINE;
  1551. e->contents.remove_replace_line.lineno = offset;
  1552. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1553. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1554. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1555. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1556. HIST_APPEND(e);
  1557. }
  1558. if (lines[offset]->available < replacement->actual) {
  1559. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1560. lines[offset]->available = replacement->available;
  1561. }
  1562. lines[offset]->actual = replacement->actual;
  1563. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1564. if (!env->loading) {
  1565. lines[offset]->rev_status = 2;
  1566. recalculate_syntax(lines[offset],offset);
  1567. }
  1568. }
  1569. /**
  1570. * Merge two consecutive lines.
  1571. * lineb is the offset of the second line.
  1572. */
  1573. line_t ** merge_lines(line_t ** lines, int lineb) {
  1574. /* linea is the line immediately before lineb */
  1575. int linea = lineb - 1;
  1576. if (!env->loading && global_config.history_enabled) {
  1577. history_t * e = malloc(sizeof(history_t));
  1578. e->type = HISTORY_MERGE_LINES;
  1579. e->contents.add_merge_split_lines.lineno = lineb;
  1580. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1581. HIST_APPEND(e);
  1582. }
  1583. /* If there isn't enough space in linea hold both... */
  1584. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1585. /* ... allocate more space until it fits */
  1586. if (lines[linea]->available == 0) {
  1587. lines[linea]->available = 8;
  1588. } else {
  1589. lines[linea]->available *= 2;
  1590. }
  1591. /* XXX why not just do this once after calculating appropriate size */
  1592. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1593. }
  1594. /* Copy the second line into the first line */
  1595. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1596. /* The first line is now longer */
  1597. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1598. if (!env->loading) {
  1599. lines[linea]->rev_status = 2;
  1600. recalculate_tabs(lines[linea]);
  1601. recalculate_syntax(lines[linea], linea);
  1602. }
  1603. /* Remove the second line */
  1604. free(lines[lineb]);
  1605. /* Move other lines up */
  1606. if (lineb < env->line_count) {
  1607. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1608. lines[env->line_count-1] = NULL;
  1609. }
  1610. /* There is one less line */
  1611. env->line_count -= 1;
  1612. return lines;
  1613. }
  1614. /**
  1615. * Split a line into two lines at the given column
  1616. */
  1617. line_t ** split_line(line_t ** lines, int line, int split) {
  1618. /* If we're trying to split from the start, just add a new blank line before */
  1619. if (split == 0) {
  1620. return add_line(lines, line);
  1621. }
  1622. if (!env->loading && global_config.history_enabled) {
  1623. history_t * e = malloc(sizeof(history_t));
  1624. e->type = HISTORY_SPLIT_LINE;
  1625. e->contents.add_merge_split_lines.lineno = line;
  1626. e->contents.add_merge_split_lines.split = split;
  1627. HIST_APPEND(e);
  1628. }
  1629. /* Allocate more space as needed */
  1630. if (env->line_count == env->line_avail) {
  1631. env->line_avail *= 2;
  1632. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1633. }
  1634. if (!env->loading) {
  1635. unhighlight_matching_paren();
  1636. }
  1637. /* Shift later lines down */
  1638. if (line < env->line_count) {
  1639. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1640. }
  1641. /* I have no idea what this is doing */
  1642. int remaining = lines[line]->actual - split;
  1643. int v = remaining;
  1644. v--;
  1645. v |= v >> 1;
  1646. v |= v >> 2;
  1647. v |= v >> 4;
  1648. v |= v >> 8;
  1649. v |= v >> 16;
  1650. v++;
  1651. /* Allocate space for the new line */
  1652. lines[line+1] = calloc(sizeof(line_t) + sizeof(char_t) * v, 1);
  1653. lines[line+1]->available = v;
  1654. lines[line+1]->actual = remaining;
  1655. /* Move the data from the old line into the new line */
  1656. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1657. lines[line]->actual = split;
  1658. if (!env->loading) {
  1659. lines[line]->rev_status = 2;
  1660. lines[line+1]->rev_status = 2;
  1661. recalculate_tabs(lines[line]);
  1662. recalculate_tabs(lines[line+1]);
  1663. recalculate_syntax(lines[line], line);
  1664. recalculate_syntax(lines[line+1], line+1);
  1665. }
  1666. /* There is one new line */
  1667. env->line_count += 1;
  1668. /* We may have reallocated lines */
  1669. return lines;
  1670. }
  1671. /**
  1672. * Understand spaces and comments and check if the previous line
  1673. * ended with a brace or a colon.
  1674. */
  1675. int line_ends_with_brace(line_t * line) {
  1676. int i = line->actual-1;
  1677. while (i >= 0) {
  1678. if ((line->text[i].flags & 0x1F) == FLAG_COMMENT || line->text[i].codepoint == ' ') {
  1679. i--;
  1680. } else {
  1681. break;
  1682. }
  1683. }
  1684. if (i < 0) return 0;
  1685. return (line->text[i].codepoint == '{' || line->text[i].codepoint == ':') ? i+1 : 0;
  1686. }
  1687. int line_is_comment(line_t * line) {
  1688. if (!env->syntax) return 0;
  1689. if (!strcmp(env->syntax->name,"c")) {
  1690. if (line->istate == 1) return 1;
  1691. } else if (!strcmp(env->syntax->name,"java")) {
  1692. if (line->istate == 1) return 1;
  1693. } else if (!strcmp(env->syntax->name,"rust")) {
  1694. if (line->istate > 0) return 1;
  1695. }
  1696. return 0;
  1697. }
  1698. int find_brace_line_start(int line, int col) {
  1699. int ncol = col - 1;
  1700. while (ncol > 0) {
  1701. if (env->lines[line-1]->text[ncol-1].codepoint == ')') {
  1702. int t_line_no = env->line_no;
  1703. int t_col_no = env->col_no;
  1704. env->line_no = line;
  1705. env->col_no = ncol;
  1706. int paren_match_line = -1, paren_match_col = -1;
  1707. find_matching_paren(&paren_match_line, &paren_match_col, 1);
  1708. if (paren_match_line != -1) {
  1709. line = paren_match_line;
  1710. }
  1711. env->line_no = t_line_no;
  1712. env->col_no = t_col_no;
  1713. break;
  1714. } else if (env->lines[line-1]->text[ncol-1].codepoint == ' ') {
  1715. ncol--;
  1716. } else {
  1717. break;
  1718. }
  1719. }
  1720. return line;
  1721. }
  1722. /**
  1723. * Add indentation from the previous (temporally) line
  1724. */
  1725. void add_indent(int new_line, int old_line, int ignore_brace) {
  1726. if (env->indent) {
  1727. int changed = 0;
  1728. if (old_line < new_line && line_is_comment(env->lines[new_line])) {
  1729. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1730. if (env->lines[old_line]->text[i].codepoint == '/') {
  1731. if (env->lines[old_line]->text[i+1].codepoint == '*') {
  1732. /* Insert ' * ' */
  1733. char_t space = {1,FLAG_COMMENT,' '};
  1734. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1735. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1736. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1737. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1738. env->col_no += 3;
  1739. }
  1740. break;
  1741. } else if (env->lines[old_line]->text[i].codepoint == ' ' && env->lines[old_line]->text[i+1].codepoint == '*') {
  1742. /* Insert ' * ' */
  1743. char_t space = {1,FLAG_COMMENT,' '};
  1744. char_t asterisk = {1,FLAG_COMMENT,'*'};
  1745. env->lines[new_line] = line_insert(env->lines[new_line],space,i,new_line);
  1746. env->lines[new_line] = line_insert(env->lines[new_line],asterisk,i+1,new_line);
  1747. env->lines[new_line] = line_insert(env->lines[new_line],space,i+2,new_line);
  1748. env->col_no += 3;
  1749. break;
  1750. } else if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1751. env->lines[old_line]->text[i].codepoint == '\t' ||
  1752. env->lines[old_line]->text[i].codepoint == '*') {
  1753. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1754. env->col_no++;
  1755. changed = 1;
  1756. } else {
  1757. break;
  1758. }
  1759. }
  1760. } else {
  1761. int line_to_copy_from = old_line;
  1762. int col;
  1763. if (old_line < new_line &&
  1764. !ignore_brace &&
  1765. (col = line_ends_with_brace(env->lines[old_line])) &&
  1766. env->lines[old_line]->text[col-1].codepoint == '{') {
  1767. line_to_copy_from = find_brace_line_start(old_line+1, col)-1;
  1768. }
  1769. for (int i = 0; i < env->lines[line_to_copy_from]->actual; ++i) {
  1770. if (line_to_copy_from < new_line && i == env->lines[line_to_copy_from]->actual - 3 &&
  1771. env->lines[line_to_copy_from]->text[i].codepoint == ' ' &&
  1772. env->lines[line_to_copy_from]->text[i+1].codepoint == '*' &&
  1773. env->lines[line_to_copy_from]->text[i+2].codepoint == '/') {
  1774. break;
  1775. } else if (env->lines[line_to_copy_from]->text[i].codepoint == ' ' ||
  1776. env->lines[line_to_copy_from]->text[i].codepoint == '\t') {
  1777. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[line_to_copy_from]->text[i],i,new_line);
  1778. env->col_no++;
  1779. changed = 1;
  1780. } else {
  1781. break;
  1782. }
  1783. }
  1784. }
  1785. if (old_line < new_line && !ignore_brace && line_ends_with_brace(env->lines[old_line])) {
  1786. if (env->tabs) {
  1787. char_t c;
  1788. c.codepoint = '\t';
  1789. c.display_width = env->tabstop;
  1790. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1791. env->col_no++;
  1792. changed = 1;
  1793. } else {
  1794. for (int j = 0; j < env->tabstop; ++j) {
  1795. char_t c;
  1796. c.codepoint = ' ';
  1797. c.display_width = 1;
  1798. c.flags = FLAG_SELECT;
  1799. env->lines[new_line] = line_insert(env->lines[new_line], c, env->col_no-1, new_line);
  1800. env->col_no++;
  1801. }
  1802. changed = 1;
  1803. }
  1804. }
  1805. int was_whitespace = 1;
  1806. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1807. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1808. env->lines[old_line]->text[i].codepoint != '\t') {
  1809. was_whitespace = 0;
  1810. break;
  1811. }
  1812. }
  1813. if (was_whitespace) {
  1814. while (env->lines[old_line]->actual) {
  1815. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1816. }
  1817. }
  1818. if (changed) {
  1819. recalculate_syntax(env->lines[new_line],new_line);
  1820. }
  1821. }
  1822. }
  1823. /**
  1824. * Initialize a buffer with default values
  1825. */
  1826. void setup_buffer(buffer_t * env) {
  1827. /* If this buffer was already initialized, clear out its line data */
  1828. if (env->lines) {
  1829. for (int i = 0; i < env->line_count; ++i) {
  1830. free(env->lines[i]);
  1831. }
  1832. free(env->lines);
  1833. }
  1834. /* Default state parameters */
  1835. env->line_no = 1; /* Default cursor position */
  1836. env->col_no = 1;
  1837. env->line_count = 1; /* Buffers always have at least one line */
  1838. env->modified = 0;
  1839. env->readonly = 0;
  1840. env->offset = 0;
  1841. env->line_avail = 8; /* Default line buffer capacity */
  1842. env->tabs = 1; /* Tabs by default */
  1843. env->tabstop = 4; /* Tab stop width */
  1844. env->indent = 1; /* Auto-indent by default */
  1845. env->history = malloc(sizeof(struct history));
  1846. memset(env->history, 0, sizeof(struct history));
  1847. env->last_save_history = env->history;
  1848. /* Allocate line buffer */
  1849. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1850. /* Initialize the first line */
  1851. env->lines[0] = calloc(sizeof(line_t) + sizeof(char_t) * 32, 1);
  1852. env->lines[0]->available = 32;
  1853. }
  1854. /**
  1855. * Toggle buffered / unbuffered modes
  1856. */
  1857. struct termios old;
  1858. void get_initial_termios(void) {
  1859. tcgetattr(STDOUT_FILENO, &old);
  1860. }
  1861. void set_unbuffered(void) {
  1862. struct termios new = old;
  1863. new.c_iflag &= (~ICRNL) & (~IXON);
  1864. new.c_lflag &= (~ICANON) & (~ECHO) & (~ISIG);
  1865. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1866. }
  1867. void set_buffered(void) {
  1868. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1869. }
  1870. /**
  1871. * Convert codepoint to utf-8 string
  1872. */
  1873. int to_eight(uint32_t codepoint, char * out) {
  1874. memset(out, 0x00, 7);
  1875. if (codepoint < 0x0080) {
  1876. out[0] = (char)codepoint;
  1877. } else if (codepoint < 0x0800) {
  1878. out[0] = 0xC0 | (codepoint >> 6);
  1879. out[1] = 0x80 | (codepoint & 0x3F);
  1880. } else if (codepoint < 0x10000) {
  1881. out[0] = 0xE0 | (codepoint >> 12);
  1882. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1883. out[2] = 0x80 | (codepoint & 0x3F);
  1884. } else if (codepoint < 0x200000) {
  1885. out[0] = 0xF0 | (codepoint >> 18);
  1886. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1887. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1888. out[3] = 0x80 | ((codepoint) & 0x3F);
  1889. } else if (codepoint < 0x4000000) {
  1890. out[0] = 0xF8 | (codepoint >> 24);
  1891. out[1] = 0x80 | (codepoint >> 18);
  1892. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1893. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1894. out[4] = 0x80 | ((codepoint) & 0x3F);
  1895. } else {
  1896. out[0] = 0xF8 | (codepoint >> 30);
  1897. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1898. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1899. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1900. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1901. out[5] = 0x80 | ((codepoint) & 0x3F);
  1902. }
  1903. return strlen(out);
  1904. }
  1905. /**
  1906. * Get the presentation width of a codepoint
  1907. */
  1908. int codepoint_width(wchar_t codepoint) {
  1909. if (codepoint == '\t') {
  1910. return 1; /* Recalculate later */
  1911. }
  1912. if (codepoint < 32) {
  1913. /* We render these as ^@ */
  1914. return 2;
  1915. }
  1916. if (codepoint == 0x7F) {
  1917. /* Renders as ^? */
  1918. return 2;
  1919. }
  1920. if (codepoint > 0x7f && codepoint < 0xa0) {
  1921. /* Upper control bytes <xx> */
  1922. return 4;
  1923. }
  1924. if (codepoint == 0xa0) {
  1925. /* Non-breaking space _ */
  1926. return 1;
  1927. }
  1928. /* Skip wcwidth for anything under 256 */
  1929. if (codepoint > 256) {
  1930. if (global_config.can_unicode) {
  1931. /* Higher codepoints may be wider (eg. Japanese) */
  1932. int out = wcwidth(codepoint);
  1933. if (out >= 1) return out;
  1934. }
  1935. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1936. return (codepoint < 0x10000) ? 8 : 10;
  1937. }
  1938. return 1;
  1939. }
  1940. /**
  1941. * Move the terminal cursor
  1942. */
  1943. void place_cursor(int x, int y) {
  1944. printf("\033[%d;%dH", y, x);
  1945. }
  1946. char * color_string(const char * fg, const char * bg) {
  1947. static char output[100];
  1948. char * t = output;
  1949. t += sprintf(t,"\033[22;23;24;");
  1950. if (*bg == '@') {
  1951. int _bg = atoi(bg+1);
  1952. if (_bg < 10) {
  1953. t += sprintf(t, "4%d;", _bg);
  1954. } else {
  1955. t += sprintf(t, "10%d;", _bg-10);
  1956. }
  1957. } else {
  1958. t += sprintf(t, "48;%s;", bg);
  1959. }
  1960. if (*fg == '@') {
  1961. int _fg = atoi(fg+1);
  1962. if (_fg < 10) {
  1963. t += sprintf(t, "3%dm", _fg);
  1964. } else {
  1965. t += sprintf(t, "9%dm", _fg-10);
  1966. }
  1967. } else {
  1968. t += sprintf(t, "38;%sm", fg);
  1969. }
  1970. return output;
  1971. }
  1972. /**
  1973. * Set text colors
  1974. *
  1975. * Normally, text colors are just strings, but if they
  1976. * start with @ they will be parsed as integers
  1977. * representing one of the 16 standard colors, suitable
  1978. * for terminals without support for the 256- or 24-bit
  1979. * color modes.
  1980. */
  1981. void set_colors(const char * fg, const char * bg) {
  1982. printf("%s", color_string(fg, bg));
  1983. }
  1984. /**
  1985. * Set just the foreground color
  1986. *
  1987. * (See set_colors above)
  1988. */
  1989. void set_fg_color(const char * fg) {
  1990. printf("\033[22;23;24;");
  1991. if (*fg == '@') {
  1992. int _fg = atoi(fg+1);
  1993. if (_fg < 10) {
  1994. printf("3%dm", _fg);
  1995. } else {
  1996. printf("9%dm", _fg-10);
  1997. }
  1998. } else {
  1999. printf("38;%sm", fg);
  2000. }
  2001. }
  2002. /**
  2003. * Clear the rest of this line
  2004. */
  2005. void clear_to_end(void) {
  2006. if (global_config.can_bce) {
  2007. printf("\033[K");
  2008. }
  2009. }
  2010. /**
  2011. * For terminals without bce,
  2012. * prepaint the whole line, so we don't have to track
  2013. * where the cursor is for everything. Inefficient,
  2014. * but effective.
  2015. */
  2016. void paint_line(const char * bg) {
  2017. if (!global_config.can_bce) {
  2018. set_colors(COLOR_FG, bg);
  2019. for (int i = 0; i < global_config.term_width; ++i) {
  2020. printf(" ");
  2021. }
  2022. printf("\r");
  2023. }
  2024. }
  2025. /**
  2026. * Enable bold text display
  2027. */
  2028. void set_bold(void) {
  2029. printf("\033[1m");
  2030. }
  2031. /**
  2032. * Disable bold
  2033. */
  2034. void unset_bold(void) {
  2035. printf("\033[22m");
  2036. }
  2037. /**
  2038. * Enable underlined text display
  2039. */
  2040. void set_underline(void) {
  2041. printf("\033[4m");
  2042. }
  2043. /**
  2044. * Disable underlined text display
  2045. */
  2046. void unset_underline(void) {
  2047. printf("\033[24m");
  2048. }
  2049. /**
  2050. * Reset text display attributes
  2051. */
  2052. void reset(void) {
  2053. printf("\033[0m");
  2054. }
  2055. /**
  2056. * Clear the entire screen
  2057. */
  2058. void clear_screen(void) {
  2059. printf("\033[H\033[2J");
  2060. }
  2061. /**
  2062. * Hide the cursor
  2063. */
  2064. void hide_cursor(void) {
  2065. if (global_config.can_hideshow) {
  2066. printf("\033[?25l");
  2067. }
  2068. }
  2069. /**
  2070. * Show the cursor
  2071. */
  2072. void show_cursor(void) {
  2073. if (global_config.can_hideshow) {
  2074. printf("\033[?25h");
  2075. }
  2076. }
  2077. /**
  2078. * Store the cursor position
  2079. */
  2080. void store_cursor(void) {
  2081. printf("\0337");
  2082. }
  2083. /**
  2084. * Restore the cursor position.
  2085. */
  2086. void restore_cursor(void) {
  2087. printf("\0338");
  2088. }
  2089. /**
  2090. * Request mouse events
  2091. */
  2092. void mouse_enable(void) {
  2093. if (global_config.can_mouse) {
  2094. printf("\033[?1000h");
  2095. if (global_config.use_sgr_mouse) {
  2096. printf("\033[?1006h");
  2097. }
  2098. }
  2099. }
  2100. /**
  2101. * Stop mouse events
  2102. */
  2103. void mouse_disable(void) {
  2104. if (global_config.can_mouse) {
  2105. if (global_config.use_sgr_mouse) {
  2106. printf("\033[?1006l");
  2107. }
  2108. printf("\033[?1000l");
  2109. }
  2110. }
  2111. /**
  2112. * Shift the screen up one line
  2113. */
  2114. void shift_up(int amount) {
  2115. printf("\033[%dS", amount);
  2116. }
  2117. /**
  2118. * Shift the screen down one line.
  2119. */
  2120. void shift_down(int amount) {
  2121. printf("\033[%dT", amount);
  2122. }
  2123. /**
  2124. * Switch to the alternate terminal screen.
  2125. */
  2126. void set_alternate_screen(void) {
  2127. if (global_config.can_altscreen) {
  2128. printf("\033[?1049h");
  2129. }
  2130. }
  2131. /**
  2132. * Restore the standard terminal screen.
  2133. */
  2134. void unset_alternate_screen(void) {
  2135. if (global_config.can_altscreen) {
  2136. printf("\033[?1049l");
  2137. }
  2138. }
  2139. /**
  2140. * Get the name of just a file from a full path.
  2141. * Returns a pointer within the original string.
  2142. */
  2143. char * file_basename(char * file) {
  2144. char * c = strrchr(file, '/');
  2145. if (!c) return file;
  2146. return (c+1);
  2147. }
  2148. /**
  2149. * Print a tab name with fixed width and modifiers
  2150. * into an output buffer and return the written width.
  2151. */
  2152. int draw_tab_name(buffer_t * _env, char * out, int max_width, int * width) {
  2153. uint32_t c, state = 0;
  2154. char * t = _env->file_name ? file_basename(_env->file_name) : "[No Name]";
  2155. #define ADD(c) do { \
  2156. *o = c; \
  2157. o++; \
  2158. *o = '\0'; \
  2159. bytes++; \
  2160. } while (0)
  2161. char * o = out;
  2162. *o = '\0';
  2163. int bytes = 0;
  2164. if (max_width < 2) return 1;
  2165. ADD(' ');
  2166. (*width)++;
  2167. if (_env->modified) {
  2168. if (max_width < 4) return 1;
  2169. ADD('+');
  2170. (*width)++;
  2171. ADD(' ');
  2172. (*width)++;
  2173. }
  2174. while (*t) {
  2175. if (!decode(&state, &c, (unsigned char)*t)) {
  2176. char tmp[7];
  2177. int size = to_eight(c, tmp);
  2178. if (bytes + size > 62) break;
  2179. if (*width + size >= max_width) return 1;
  2180. for (int i = 0; i < size; ++i) {
  2181. ADD(tmp[i]);
  2182. }
  2183. (*width) += codepoint_width(c);
  2184. } else if (state == UTF8_REJECT) {
  2185. state = 0;
  2186. }
  2187. t++;
  2188. }
  2189. if (max_width == *width + 1) return 1;
  2190. ADD(' ');
  2191. (*width)++;
  2192. #undef ADD
  2193. return 0;
  2194. }
  2195. /**
  2196. * Redaw the tabbar, with a tab for each buffer.
  2197. *
  2198. * The active buffer is highlighted.
  2199. */
  2200. void redraw_tabbar(void) {
  2201. if (!global_config.tabs_visible) return;
  2202. /* Hide cursor while rendering UI */
  2203. hide_cursor();
  2204. /* Move to upper left */
  2205. place_cursor(1,1);
  2206. paint_line(COLOR_TABBAR_BG);
  2207. /* For each buffer... */
  2208. int offset = 0;
  2209. if (global_config.tab_offset) {
  2210. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2211. printf("<");
  2212. offset++;
  2213. }
  2214. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  2215. buffer_t * _env = buffers[i];
  2216. if (_env == env) {
  2217. /* If this is the active buffer, highlight it */
  2218. reset();
  2219. set_colors(COLOR_FG, COLOR_BG);
  2220. set_bold();
  2221. } else {
  2222. /* Otherwise use default tab color */
  2223. reset();
  2224. set_colors(COLOR_FG, COLOR_TAB_BG);
  2225. set_underline();
  2226. }
  2227. char title[64];
  2228. int size = 0;
  2229. int filled = draw_tab_name(_env, title, global_config.term_width - offset, &size);
  2230. if (filled) {
  2231. offset += size;
  2232. printf("%s", title);
  2233. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2234. while (offset != global_config.term_width - 1) {
  2235. printf(" ");
  2236. offset++;
  2237. }
  2238. printf(">");
  2239. break;
  2240. }
  2241. printf("%s", title);
  2242. offset += size;
  2243. }
  2244. /* Reset bold/underline */
  2245. reset();
  2246. /* Fill the rest of the tab bar */
  2247. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2248. clear_to_end();
  2249. }
  2250. /**
  2251. * Braindead log10 implementation for the line numbers
  2252. */
  2253. int log_base_10(unsigned int v) {
  2254. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2255. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2256. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2257. return r;
  2258. }
  2259. /**
  2260. * Render a line of text
  2261. *
  2262. * This handles rendering the actual text content. A full line of text
  2263. * also includes a line number and some padding.
  2264. *
  2265. * width: width of the text display region (term width - line number width)
  2266. * offset: how many cells into the line to start rendering at
  2267. */
  2268. void render_line(line_t * line, int width, int offset, int line_no) {
  2269. int i = 0; /* Offset in char_t line data entries */
  2270. int j = 0; /* Offset in terminal cells */
  2271. const char * last_color = NULL;
  2272. int was_selecting = 0, was_searching = 0;
  2273. /* Set default text colors */
  2274. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2275. /*
  2276. * When we are rendering in the middle of a wide character,
  2277. * we render -'s to fill the remaining amount of the
  2278. * charater's width
  2279. */
  2280. int remainder = 0;
  2281. int is_spaces = 1;
  2282. /* For each character in the line ... */
  2283. while (i < line->actual) {
  2284. /* If there is remaining text... */
  2285. if (remainder) {
  2286. /* If we should be drawing by now... */
  2287. if (j >= offset) {
  2288. /* Fill remainder with -'s */
  2289. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2290. printf("-");
  2291. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2292. }
  2293. /* One less remaining width cell to fill */
  2294. remainder--;
  2295. /* Terminal offset moves forward */
  2296. j++;
  2297. /*
  2298. * If this was the last remaining character, move to
  2299. * the next codepoint in the line
  2300. */
  2301. if (remainder == 0) {
  2302. i++;
  2303. }
  2304. continue;
  2305. }
  2306. /* Get the next character to draw */
  2307. char_t c = line->text[i];
  2308. if (c.codepoint != ' ') is_spaces = 0;
  2309. /* If we should be drawing by now... */
  2310. if (j >= offset) {
  2311. /* If this character is going to fall off the edge of the screen... */
  2312. if (j - offset + c.display_width >= width) {
  2313. /* We draw this with special colors so it isn't ambiguous */
  2314. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2315. /* If it's wide, draw ---> as needed */
  2316. while (j - offset < width - 1) {
  2317. printf("-");
  2318. j++;
  2319. }
  2320. /* End the line with a > to show it overflows */
  2321. printf(">");
  2322. set_colors(COLOR_FG, COLOR_BG);
  2323. return;
  2324. }
  2325. /* Syntax highlighting */
  2326. const char * color = flag_to_color(c.flags);
  2327. if (c.flags & FLAG_SELECT) {
  2328. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2329. was_selecting = 1;
  2330. } else if ((c.flags & FLAG_SEARCH) || (c.flags == FLAG_NOTICE)) {
  2331. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2332. was_searching = 1;
  2333. } else if (c.flags == FLAG_ERROR) {
  2334. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2335. was_searching = 1; /* co-opting this should work... */
  2336. } else {
  2337. if (was_selecting || was_searching) {
  2338. was_selecting = 0;
  2339. was_searching = 0;
  2340. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2341. last_color = color;
  2342. } else if (!last_color || strcmp(color, last_color)) {
  2343. set_fg_color(color);
  2344. last_color = color;
  2345. }
  2346. }
  2347. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2348. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2349. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2350. ((j == env->sel_col) ||
  2351. (j < env->sel_col && j + c.display_width > env->sel_col))) {
  2352. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2353. was_selecting = 1;
  2354. }
  2355. #define _set_colors(fg,bg) \
  2356. if (!(c.flags & FLAG_SELECT) && !(c.flags & FLAG_SEARCH) && !(was_selecting)) { \
  2357. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2358. }
  2359. /* Render special characters */
  2360. if (c.codepoint == '\t') {
  2361. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2362. printf("%s", global_config.tab_indicator);
  2363. for (int i = 1; i < c.display_width; ++i) {
  2364. printf("%s" ,global_config.space_indicator);
  2365. }
  2366. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2367. } else if (c.codepoint < 32) {
  2368. /* Codepoints under 32 to get converted to ^@ escapes */
  2369. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2370. printf("^%c", '@' + c.codepoint);
  2371. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2372. } else if (c.codepoint == 0x7f) {
  2373. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2374. printf("^?");
  2375. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2376. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2377. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2378. printf("<%2x>", c.codepoint);
  2379. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2380. } else if (c.codepoint == 0xa0) {
  2381. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2382. printf("_");
  2383. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2384. } else if (c.display_width == 8) {
  2385. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2386. printf("[U+%04x]", c.codepoint);
  2387. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2388. } else if (c.display_width == 10) {
  2389. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2390. printf("[U+%06x]", c.codepoint);
  2391. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2392. } else if (i > 0 && is_spaces && c.codepoint == ' ' && !(i % env->tabstop)) {
  2393. _set_colors(COLOR_ALT_FG, COLOR_BG); /* Normal background so this is more subtle */
  2394. if (global_config.can_unicode) {
  2395. printf("▏");
  2396. } else {
  2397. printf("|");
  2398. }
  2399. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2400. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2401. /* Special case: space at end of line */
  2402. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2403. printf("%s",global_config.space_indicator);
  2404. _set_colors(COLOR_FG, COLOR_BG);
  2405. } else {
  2406. /* Normal characters get output */
  2407. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2408. to_eight(c.codepoint, tmp);
  2409. printf("%s", tmp);
  2410. }
  2411. /* Advance the terminal cell offset by the render width of this character */
  2412. j += c.display_width;
  2413. /* Advance to the next character */
  2414. i++;
  2415. } else if (c.display_width > 1) {
  2416. /*
  2417. * If this is a wide character but we aren't ready to render yet,
  2418. * we may need to draw some filler text for the remainder of its
  2419. * width to ensure we don't jump around when horizontally scrolling
  2420. * past wide characters.
  2421. */
  2422. remainder = c.display_width - 1;
  2423. j++;
  2424. } else {
  2425. /* Regular character, not ready to draw, advance without doing anything */
  2426. j++;
  2427. i++;
  2428. }
  2429. }
  2430. if (env->mode != MODE_LINE_SELECTION) {
  2431. if (line->is_current) {
  2432. set_colors(COLOR_FG, COLOR_ALT_BG);
  2433. } else {
  2434. set_colors(COLOR_FG, COLOR_BG);
  2435. }
  2436. } else {
  2437. if (!line->actual) {
  2438. if (env->line_no == line_no ||
  2439. (env->start_line > env->line_no &&
  2440. (line_no >= env->line_no && line_no <= env->start_line)) ||
  2441. (env->start_line < env->line_no &&
  2442. (line_no >= env->start_line && line_no <= env->line_no))) {
  2443. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2444. }
  2445. }
  2446. }
  2447. if ((env->mode == MODE_COL_SELECTION || env->mode == MODE_COL_INSERT) &&
  2448. line_no >= ((env->start_line < env->line_no) ? env->start_line : env->line_no) &&
  2449. line_no <= ((env->start_line < env->line_no) ? env->line_no : env->start_line) &&
  2450. j <= env->sel_col &&
  2451. env->sel_col < width) {
  2452. set_colors(COLOR_FG, COLOR_BG);
  2453. while (j < env->sel_col) {
  2454. printf(" ");
  2455. j++;
  2456. }
  2457. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2458. printf(" ");
  2459. j++;
  2460. set_colors(COLOR_FG, COLOR_BG);
  2461. }
  2462. if (env->maxcolumn && line_no > -1 /* ensures we don't do this for command line */) {
  2463. /* Fill out the normal background */
  2464. if (j < offset) j = offset;
  2465. for (; j < width + offset && j < env->maxcolumn; ++j) {
  2466. printf(" ");
  2467. }
  2468. /* Draw the line */
  2469. if (j < width + offset && j == env->maxcolumn) {
  2470. j++;
  2471. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2472. if (global_config.can_unicode) {
  2473. printf("▏");
  2474. } else {
  2475. printf("|");
  2476. }
  2477. }
  2478. /* Fill the rest with the alternate background color */
  2479. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2480. }
  2481. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2482. clear_to_end();
  2483. } else {
  2484. /* Paint the rest of the line */
  2485. if (j < offset) j = offset;
  2486. for (; j < width + offset; ++j) {
  2487. printf(" ");
  2488. }
  2489. }
  2490. }
  2491. /**
  2492. * Get the width of the line number region
  2493. */
  2494. int num_width(void) {
  2495. if (!env->numbers) return 0;
  2496. int w = log_base_10(env->line_count) + 3;
  2497. if (w < 4) return 4;
  2498. return w;
  2499. }
  2500. /**
  2501. * Display width of the revision status gutter.
  2502. */
  2503. int gutter_width(void) {
  2504. return env->gutter;
  2505. }
  2506. /**
  2507. * Draw the gutter and line numbers.
  2508. */
  2509. void draw_line_number(int x) {
  2510. if (!env->numbers) return;
  2511. /* Draw the line number */
  2512. if (env->lines[x]->is_current) {
  2513. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2514. } else {
  2515. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2516. }
  2517. if (global_config.relative_lines && x+1 != env->line_no) {
  2518. x = x+1 - env->line_no;
  2519. x = ((x < 0) ? -x : x)-1;
  2520. }
  2521. int num_size = num_width() - 2; /* Padding */
  2522. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2523. printf(" ");
  2524. }
  2525. printf("%d%c", x + 1, ((x+1 == env->line_no || global_config.horizontal_shift_scrolling) && env->coffset > 0) ? '<' : ' ');
  2526. }
  2527. /**
  2528. * Used to highlight the current line after moving the cursor.
  2529. */
  2530. void recalculate_current_line(void) {
  2531. int something_changed = 0;
  2532. if (global_config.highlight_current_line) {
  2533. for (int i = 0; i < env->line_count; ++i) {
  2534. if (env->lines[i]->is_current && i != env->line_no-1) {
  2535. env->lines[i]->is_current = 0;
  2536. something_changed = 1;
  2537. redraw_line(i);
  2538. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2539. env->lines[i]->is_current = 1;
  2540. something_changed = 1;
  2541. redraw_line(i);
  2542. }
  2543. }
  2544. } else {
  2545. something_changed = 1;
  2546. }
  2547. if (something_changed && global_config.relative_lines) {
  2548. for (int i = env->offset; i < env->offset + global_config.term_height - global_config.bottom_size - 1 && i < env->line_count; ++i) {
  2549. /* Place cursor for line number */
  2550. place_cursor(1 + gutter_width() + env->left, (i)-env->offset + 1 + global_config.tabs_visible);
  2551. draw_line_number(i);
  2552. }
  2553. }
  2554. }
  2555. /**
  2556. * Redraw line.
  2557. *
  2558. * This draws the line number as well as the actual text.
  2559. */
  2560. void redraw_line(int x) {
  2561. if (env->loading) return;
  2562. /* Determine if this line is visible. */
  2563. if (x - env->offset < 0 || x - env->offset > global_config.term_height - global_config.bottom_size - 1 - global_config.tabs_visible) {
  2564. return;
  2565. }
  2566. /* Calculate offset in screen */
  2567. int j = x - env->offset;
  2568. /* Hide cursor when drawing */
  2569. hide_cursor();
  2570. /* Move cursor to upper left most cell of this line */
  2571. place_cursor(1 + env->left,1 + global_config.tabs_visible + j);
  2572. /* Draw a gutter on the left. */
  2573. if (env->gutter) {
  2574. switch (env->lines[x]->rev_status) {
  2575. case 1:
  2576. set_colors(COLOR_NUMBER_FG, COLOR_GREEN);
  2577. printf(" ");
  2578. break;
  2579. case 2:
  2580. set_colors(COLOR_NUMBER_FG, global_config.color_gutter ? COLOR_SEARCH_BG : COLOR_ALT_FG);
  2581. printf(" ");
  2582. break;
  2583. case 3:
  2584. set_colors(COLOR_NUMBER_FG, COLOR_KEYWORD);
  2585. printf(" ");
  2586. break;
  2587. case 4:
  2588. set_colors(COLOR_ALT_FG, COLOR_RED);
  2589. printf("▆");
  2590. break;
  2591. case 5:
  2592. set_colors(COLOR_KEYWORD, COLOR_RED);
  2593. printf("▆");
  2594. break;
  2595. default:
  2596. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2597. printf(" ");
  2598. break;
  2599. }
  2600. }
  2601. draw_line_number(x);
  2602. /*
  2603. * Draw the line text
  2604. * If this is the active line, the current character cell offset should be used.
  2605. * (Non-active lines are not shifted and always render from the start of the line)
  2606. */
  2607. render_line(env->lines[x], env->width - gutter_width() - num_width(), (x + 1 == env->line_no || global_config.horizontal_shift_scrolling) ? env->coffset : 0, x+1);
  2608. }
  2609. /**
  2610. * Draw a ~ line where there is no buffer text.
  2611. */
  2612. void draw_excess_line(int j) {
  2613. place_cursor(1+env->left,1 + global_config.tabs_visible + j);
  2614. paint_line(COLOR_ALT_BG);
  2615. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2616. printf("~");
  2617. if (env->left + env->width == global_config.term_width && global_config.can_bce) {
  2618. clear_to_end();
  2619. } else {
  2620. /* Paint the rest of the line */
  2621. for (int x = 1; x < env->width; ++x) {
  2622. printf(" ");
  2623. }
  2624. }
  2625. }
  2626. /**
  2627. * Redraw the entire text area
  2628. */
  2629. void redraw_text(void) {
  2630. if (!env) return;
  2631. if (!global_config.has_terminal) return;
  2632. /* Hide cursor while rendering */
  2633. hide_cursor();
  2634. /* Figure out the available size of the text region */
  2635. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  2636. int j = 0;
  2637. /* Draw each line */
  2638. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2639. redraw_line(x);
  2640. j++;
  2641. }
  2642. /* Draw the rest of the text region as ~ lines */
  2643. for (; j < l; ++j) {
  2644. draw_excess_line(j);
  2645. }
  2646. }
  2647. static int view_left_offset = 0;
  2648. static int view_right_offset = 0;
  2649. /**
  2650. * When in split view, draw the other buffer.
  2651. * Has special handling for when the split is
  2652. * on a single buffer.
  2653. */
  2654. void redraw_alt_buffer(buffer_t * buf) {
  2655. if (left_buffer == right_buffer) {
  2656. /* draw the opposite view */
  2657. int left, width, offset;
  2658. left = env->left;
  2659. width = env->width;
  2660. offset = env->offset;
  2661. if (left == 0) {
  2662. /* Draw the right side */
  2663. env->left = width;
  2664. env->width = global_config.term_width - width;
  2665. env->offset = view_right_offset;
  2666. view_left_offset = offset;
  2667. } else {
  2668. env->left = 0;
  2669. env->width = global_config.term_width * global_config.split_percent / 100;
  2670. env->offset = view_left_offset;
  2671. view_right_offset = offset;
  2672. }
  2673. redraw_text();
  2674. env->left = left;
  2675. env->width = width;
  2676. env->offset = offset;
  2677. }
  2678. /* Swap out active buffer */
  2679. buffer_t * tmp = env;
  2680. env = buf;
  2681. /* Redraw text */
  2682. redraw_text();
  2683. /* Return original active buffer */
  2684. env = tmp;
  2685. }
  2686. /**
  2687. * Basically wcswidth() but implemented internally using our
  2688. * own utf-8 decoder to ensure it works properly.
  2689. */
  2690. int display_width_of_string(char * str) {
  2691. uint8_t * s = (uint8_t *)str;
  2692. int out = 0;
  2693. uint32_t c, state = 0;
  2694. while (*s) {
  2695. if (!decode(&state, &c, *s)) {
  2696. out += codepoint_width(c);
  2697. } else if (state == UTF8_REJECT) {
  2698. state = 0;
  2699. }
  2700. s++;
  2701. }
  2702. return out;
  2703. }
  2704. int statusbar_append_status(int *remaining_width, char * output, char * base, ...) {
  2705. va_list args;
  2706. va_start(args, base);
  2707. char tmp[100]; /* should be big enough */
  2708. vsnprintf(tmp, 100, base, args);
  2709. va_end(args);
  2710. int width = display_width_of_string(tmp) + 2;
  2711. if (width < *remaining_width) {
  2712. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2713. strcat(output,"[");
  2714. strcat(output,color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2715. strcat(output, tmp);
  2716. strcat(output,color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2717. strcat(output,"]");
  2718. (*remaining_width) -= width;
  2719. return width;
  2720. } else {
  2721. return 0;
  2722. }
  2723. }
  2724. int statusbar_build_right(char * right_hand) {
  2725. char tmp[1024];
  2726. sprintf(tmp, " Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2727. int out = display_width_of_string(tmp);
  2728. char * s = right_hand;
  2729. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2730. s += sprintf(s, " Line ");
  2731. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2732. s += sprintf(s, "%d/%d ", env->line_no, env->line_count);
  2733. s += sprintf(s, "%s", color_string(COLOR_STATUS_ALT, COLOR_STATUS_BG));
  2734. s += sprintf(s, " Col: ");
  2735. s += sprintf(s, "%s", color_string(COLOR_STATUS_FG, COLOR_STATUS_BG));
  2736. s += sprintf(s, "%d ", env->col_no);
  2737. return out;
  2738. }
  2739. /**
  2740. * Draw the status bar
  2741. *
  2742. * The status bar shows the name of the file, whether it has modifications,
  2743. * and (in the future) what syntax highlighting mode is enabled.
  2744. *
  2745. * The right side of the tatus bar shows the line number and column.
  2746. */
  2747. void redraw_statusbar(void) {
  2748. if (global_config.hide_statusbar) return;
  2749. if (!env) return;
  2750. /* Hide cursor while rendering */
  2751. hide_cursor();
  2752. /* Move cursor to the status bar line (second from bottom */
  2753. place_cursor(1, global_config.term_height - 1);
  2754. /* Set background colors for status line */
  2755. paint_line(COLOR_STATUS_BG);
  2756. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2757. /* Pre-render the right hand side of the status bar */
  2758. char right_hand[1024];
  2759. int right_width = statusbar_build_right(right_hand);
  2760. char status_bits[1024] = {0}; /* Sane maximum */
  2761. int status_bits_width = 0;
  2762. int remaining_width = global_config.term_width - right_width;
  2763. #define ADD(...) do { status_bits_width += statusbar_append_status(&remaining_width, status_bits, __VA_ARGS__); } while (0)
  2764. if (env->syntax) {
  2765. ADD("%s",env->syntax->name);
  2766. }
  2767. /* Print file status indicators */
  2768. if (env->modified) {
  2769. ADD("+");
  2770. }
  2771. if (env->readonly) {
  2772. ADD("ro");
  2773. }
  2774. if (env->crnl) {
  2775. ADD("crnl");
  2776. }
  2777. if (env->tabs) {
  2778. ADD("tabs");
  2779. } else {
  2780. ADD("spaces=%d", env->tabstop);
  2781. }
  2782. if (global_config.yanks) {
  2783. ADD("y:%ld", global_config.yank_count);
  2784. }
  2785. if (env->indent) {
  2786. ADD("indent");
  2787. }
  2788. if (global_config.smart_complete) {
  2789. ADD("complete");
  2790. }
  2791. #undef ADD
  2792. uint8_t * file_name = (uint8_t *)(env->file_name ? env->file_name : "[No Name]");
  2793. int file_name_width = display_width_of_string((char*)file_name);
  2794. if (remaining_width > 3) {
  2795. int is_chopped = 0;
  2796. while (remaining_width < file_name_width + 3) {
  2797. is_chopped = 1;
  2798. if ((*file_name & 0xc0) == 0xc0) { /* First byte of a multibyte character */
  2799. file_name++;
  2800. while ((*file_name & 0xc0) == 0x80) file_name++;
  2801. } else {
  2802. file_name++;
  2803. }
  2804. file_name_width = display_width_of_string((char*)file_name);
  2805. }
  2806. if (is_chopped) {
  2807. set_colors(COLOR_ALT_FG, COLOR_STATUS_BG);
  2808. printf("<");
  2809. }
  2810. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2811. printf("%s ", file_name);
  2812. }
  2813. printf("%s", status_bits);
  2814. /* Clear the rest of the status bar */
  2815. clear_to_end();
  2816. /* Move the cursor appropriately to draw it */
  2817. place_cursor(global_config.term_width - right_width, global_config.term_height - 1);
  2818. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2819. printf("%s",right_hand);
  2820. }
  2821. /**
  2822. * Redraw the navigation numbers on the right side of the command line
  2823. */
  2824. void redraw_nav_buffer() {
  2825. if (nav_buffer) {
  2826. store_cursor();
  2827. place_cursor(global_config.term_width - nav_buffer - 2, global_config.term_height);
  2828. printf("%s", nav_buf);
  2829. clear_to_end();
  2830. restore_cursor();
  2831. }
  2832. }
  2833. /**
  2834. * Draw the command line
  2835. *
  2836. * The command line either has input from the user (:quit, :!make, etc.)
  2837. * or shows the INSERT (or VISUAL in the future) mode name.
  2838. */
  2839. void redraw_commandline(void) {
  2840. if (!env) return;
  2841. /* Hide cursor while rendering */
  2842. hide_cursor();
  2843. /* Move cursor to the last line */
  2844. place_cursor(1, global_config.term_height);
  2845. /* Set background color */
  2846. paint_line(COLOR_BG);
  2847. set_colors(COLOR_FG, COLOR_BG);
  2848. /* If we are in an edit mode, note that. */
  2849. if (env->mode == MODE_INSERT) {
  2850. set_bold();
  2851. printf("-- INSERT --");
  2852. clear_to_end();
  2853. unset_bold();
  2854. } else if (env->mode == MODE_LINE_SELECTION) {
  2855. set_bold();
  2856. printf("-- LINE SELECTION -- (%d:%d)",
  2857. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2858. (env->start_line < env->line_no) ? env->line_no : env->start_line
  2859. );
  2860. clear_to_end();
  2861. unset_bold();
  2862. } else if (env->mode == MODE_COL_SELECTION) {
  2863. set_bold();
  2864. printf("-- COL SELECTION -- (%d:%d %d)",
  2865. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2866. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2867. (env->sel_col)
  2868. );
  2869. clear_to_end();
  2870. unset_bold();
  2871. } else if (env->mode == MODE_COL_INSERT) {
  2872. set_bold();
  2873. printf("-- COL INSERT -- (%d:%d %d)",
  2874. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  2875. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  2876. (env->sel_col)
  2877. );
  2878. clear_to_end();
  2879. unset_bold();
  2880. } else if (env->mode == MODE_REPLACE) {
  2881. set_bold();
  2882. printf("-- REPLACE --");
  2883. clear_to_end();
  2884. unset_bold();
  2885. } else if (env->mode == MODE_CHAR_SELECTION) {
  2886. set_bold();
  2887. printf("-- CHAR SELECTION -- ");
  2888. clear_to_end();
  2889. unset_bold();
  2890. } else if (env->mode == MODE_DIRECTORY_BROWSE) {
  2891. set_bold();
  2892. printf("-- DIRECTORY BROWSE --");
  2893. clear_to_end();
  2894. unset_bold();
  2895. } else {
  2896. clear_to_end();
  2897. }
  2898. redraw_nav_buffer();
  2899. }
  2900. /**
  2901. * Draw a message on the command line.
  2902. */
  2903. void render_commandline_message(char * message, ...) {
  2904. /* varargs setup */
  2905. va_list args;
  2906. va_start(args, message);
  2907. char buf[1024];
  2908. /* Process format string */
  2909. vsnprintf(buf, 1024, message, args);
  2910. va_end(args);
  2911. /* Hide cursor while rendering */
  2912. hide_cursor();
  2913. /* Move cursor to the last line */
  2914. place_cursor(1, global_config.term_height);
  2915. /* Set background color */
  2916. paint_line(COLOR_BG);
  2917. set_colors(COLOR_FG, COLOR_BG);
  2918. printf("%s", buf);
  2919. /* Clear the rest of the status bar */
  2920. clear_to_end();
  2921. redraw_nav_buffer();
  2922. }
  2923. BIM_ACTION(redraw_all, 0,
  2924. "Repaint the screen."
  2925. )(void) {
  2926. if (!env) return;
  2927. redraw_tabbar();
  2928. redraw_text();
  2929. if (left_buffer) {
  2930. redraw_alt_buffer(left_buffer == env ? right_buffer : left_buffer);
  2931. }
  2932. redraw_statusbar();
  2933. redraw_commandline();
  2934. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND || global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  2935. render_command_input_buffer();
  2936. }
  2937. }
  2938. void pause_for_key(void) {
  2939. int c;
  2940. while ((c = bim_getch())== -1);
  2941. bim_unget(c);
  2942. redraw_all();
  2943. }
  2944. /**
  2945. * Redraw all screen elements except the other split view.
  2946. */
  2947. void redraw_most(void) {
  2948. redraw_tabbar();
  2949. redraw_text();
  2950. redraw_statusbar();
  2951. redraw_commandline();
  2952. }
  2953. /**
  2954. * Disable screen splitting.
  2955. */
  2956. void unsplit(void) {
  2957. if (left_buffer) {
  2958. left_buffer->left = 0;
  2959. left_buffer->width = global_config.term_width;
  2960. }
  2961. if (right_buffer) {
  2962. right_buffer->left = 0;
  2963. right_buffer->width = global_config.term_width;
  2964. }
  2965. left_buffer = NULL;
  2966. right_buffer = NULL;
  2967. redraw_all();
  2968. }
  2969. /**
  2970. * Update the terminal title bar
  2971. */
  2972. void update_title(void) {
  2973. if (!global_config.can_title) return;
  2974. char cwd[1024] = {'/',0};
  2975. getcwd(cwd, 1024);
  2976. for (int i = 1; i < 3; ++i) {
  2977. printf("\033]%d;%s%s (%s) - Bim\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2978. }
  2979. }
  2980. /**
  2981. * Mark this buffer as modified and
  2982. * redraw the status and tabbar if needed.
  2983. */
  2984. void set_modified(void) {
  2985. /* If it was already marked modified, no need to do anything */
  2986. if (env->modified) return;
  2987. /* Mark as modified */
  2988. env->modified = 1;
  2989. /* Redraw some things */
  2990. update_title();
  2991. redraw_tabbar();
  2992. redraw_statusbar();
  2993. }
  2994. /**
  2995. * Draw a message on the status line
  2996. */
  2997. void render_status_message(char * message, ...) {
  2998. if (!env) return; /* Don't print when there's no active environment; this usually means a bimrc command tried to print something */
  2999. /* varargs setup */
  3000. va_list args;
  3001. va_start(args, message);
  3002. char buf[1024];
  3003. /* Process format string */
  3004. vsnprintf(buf, 1024, message, args);
  3005. va_end(args);
  3006. /* Hide cursor while rendering */
  3007. hide_cursor();
  3008. /* Move cursor to the status bar line (second from bottom */
  3009. place_cursor(1, global_config.term_height - 1);
  3010. /* Set background colors for status line */
  3011. paint_line(COLOR_STATUS_BG);
  3012. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  3013. printf("%s", buf);
  3014. /* Clear the rest of the status bar */
  3015. clear_to_end();
  3016. }
  3017. /**
  3018. * Draw an errormessage to the command line.
  3019. */
  3020. void render_error(char * message, ...) {
  3021. /* varargs setup */
  3022. va_list args;
  3023. va_start(args, message);
  3024. char buf[1024];
  3025. /* Process format string */
  3026. vsnprintf(buf, 1024, message, args);
  3027. va_end(args);
  3028. if (env) {
  3029. /* Hide cursor while rendering */
  3030. hide_cursor();
  3031. /* Move cursor to the command line */
  3032. place_cursor(1, global_config.term_height);
  3033. /* Set appropriate error message colors */
  3034. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  3035. /* Draw the message */
  3036. printf("%s", buf);
  3037. } else {
  3038. printf("bim: error during startup: %s\n", buf);
  3039. }
  3040. }
  3041. char * paren_pairs = "()[]{}<>";
  3042. int is_paren(int c) {
  3043. char * p = paren_pairs;
  3044. while (*p) {
  3045. if (c == *p) return 1;
  3046. p++;
  3047. }
  3048. return 0;
  3049. }
  3050. #define _rehighlight_parens() do { \
  3051. if (i < 0 || i >= env->line_count) break; \
  3052. for (int j = 0; j < env->lines[i]->actual; ++j) { \
  3053. if (i == line-1 && j == col-1) { \
  3054. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT; \
  3055. continue; \
  3056. } else { \
  3057. env->lines[i]->text[j].flags &= (~FLAG_SELECT); \
  3058. } \
  3059. } \
  3060. redraw_line(i); \
  3061. } while (0)
  3062. /**
  3063. * If the config option is enabled, find the matching
  3064. * paren character and highlight it with the SELECT
  3065. * colors, clearing out other SELECT values. As we
  3066. * co-opt the SELECT flag, don't do this in selection
  3067. * modes - only in normal and insert modes.
  3068. */
  3069. void highlight_matching_paren(void) {
  3070. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  3071. if (!global_config.highlight_parens) return;
  3072. int line = -1, col = -1;
  3073. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  3074. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  3075. find_matching_paren(&line, &col, 1);
  3076. } 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)) {
  3077. find_matching_paren(&line, &col, 2);
  3078. }
  3079. if (env->highlighting_paren == -1 && line == -1) return;
  3080. if (env->highlighting_paren > 0) {
  3081. int i = env->highlighting_paren - 1;
  3082. _rehighlight_parens();
  3083. }
  3084. if (env->highlighting_paren != line && line != -1) {
  3085. int i = line - 1;
  3086. _rehighlight_parens();
  3087. }
  3088. env->highlighting_paren = line;
  3089. }
  3090. /**
  3091. * Recalculate syntax for the matched paren.
  3092. * Useful when entering selection modes.
  3093. */
  3094. void unhighlight_matching_paren(void) {
  3095. if (env->highlighting_paren > 0 && env->highlighting_paren <= env->line_count) {
  3096. for (int i = env->highlighting_paren - 1; i <= env->highlighting_paren + 1; ++i) {
  3097. if (i >= 1 && i <= env->line_count) {
  3098. recalculate_syntax(env->lines[i-1], i-1);
  3099. redraw_line(i-1);
  3100. }
  3101. }
  3102. env->highlighting_paren = -1;
  3103. }
  3104. }
  3105. /**
  3106. * Move the cursor to the appropriate location based
  3107. * on where it is in the text region.
  3108. *
  3109. * This does some additional math to set the text
  3110. * region horizontal offset.
  3111. */
  3112. void place_cursor_actual(void) {
  3113. /* Invalid positions */
  3114. if (env->line_no < 1) env->line_no = 1;
  3115. if (env->col_no < 1) env->col_no = 1;
  3116. /* Account for the left hand gutter */
  3117. int num_size = num_width() + gutter_width();
  3118. int x = num_size + 1 - env->coffset;
  3119. /* Determine where the cursor is physically */
  3120. for (int i = 0; i < env->col_no - 1; ++i) {
  3121. char_t * c = &env->lines[env->line_no-1]->text[i];
  3122. x += c->display_width;
  3123. }
  3124. /* y is a bit easier to calculate */
  3125. int y = env->line_no - env->offset + 1;
  3126. int needs_redraw = 0;
  3127. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  3128. y++;
  3129. env->offset--;
  3130. needs_redraw = 1;
  3131. }
  3132. while (y > 1 + global_config.term_height - global_config.bottom_size - global_config.cursor_padding - global_config.tabs_visible) {
  3133. y--;
  3134. env->offset++;
  3135. needs_redraw = 1;
  3136. }
  3137. if (needs_redraw) {
  3138. redraw_text();
  3139. redraw_tabbar();
  3140. redraw_statusbar();
  3141. redraw_commandline();
  3142. }
  3143. /* If the cursor has gone off screen to the right... */
  3144. if (x > env->width - 1) {
  3145. /* Adjust the offset appropriately to scroll horizontally */
  3146. int diff = x - (env->width - 1);
  3147. env->coffset += diff;
  3148. x -= diff;
  3149. redraw_text();
  3150. }
  3151. /* Same for scrolling horizontally to the left */
  3152. if (x < num_size + 1) {
  3153. int diff = (num_size + 1) - x;
  3154. env->coffset -= diff;
  3155. x += diff;
  3156. redraw_text();
  3157. }
  3158. highlight_matching_paren();
  3159. recalculate_current_line();
  3160. /* Move the actual terminal cursor */
  3161. place_cursor(x+env->left,y - !global_config.tabs_visible);
  3162. /* Show the cursor */
  3163. show_cursor();
  3164. }
  3165. /**
  3166. * If the screen is split, update the split sizes based
  3167. * on the new terminal width and the user's split_percent setting.
  3168. */
  3169. void update_split_size(void) {
  3170. if (!left_buffer) return;
  3171. if (left_buffer == right_buffer) {
  3172. if (left_buffer->left == 0) {
  3173. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3174. } else {
  3175. right_buffer->left = global_config.term_width * global_config.split_percent / 100;
  3176. right_buffer->width = global_config.term_width - right_buffer->left;
  3177. }
  3178. return;
  3179. }
  3180. left_buffer->left = 0;
  3181. left_buffer->width = global_config.term_width * global_config.split_percent / 100;
  3182. right_buffer->left = left_buffer->width;
  3183. right_buffer->width = global_config.term_width - left_buffer->width;
  3184. }
  3185. /**
  3186. * Update screen size
  3187. */
  3188. void update_screen_size(void) {
  3189. struct winsize w;
  3190. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  3191. global_config.term_width = w.ws_col;
  3192. global_config.term_height = w.ws_row;
  3193. if (env) {
  3194. if (left_buffer) {
  3195. update_split_size();
  3196. } else if (env != left_buffer && env != right_buffer) {
  3197. env->width = w.ws_col;
  3198. }
  3199. }
  3200. for (int i = 0; i < buffers_len; ++i) {
  3201. if (buffers[i] != left_buffer && buffers[i] != right_buffer) {
  3202. buffers[i]->width = w.ws_col;
  3203. }
  3204. }
  3205. }
  3206. /**
  3207. * Handle terminal size changes
  3208. */
  3209. void SIGWINCH_handler(int sig) {
  3210. (void)sig;
  3211. update_screen_size();
  3212. redraw_all();
  3213. signal(SIGWINCH, SIGWINCH_handler);
  3214. }
  3215. /**
  3216. * Handle suspend
  3217. */
  3218. void SIGTSTP_handler(int sig) {
  3219. (void)sig;
  3220. mouse_disable();
  3221. set_buffered();
  3222. reset();
  3223. clear_screen();
  3224. show_cursor();
  3225. unset_alternate_screen();
  3226. fflush(stdout);
  3227. signal(SIGTSTP, SIG_DFL);
  3228. raise(SIGTSTP);
  3229. }
  3230. void SIGCONT_handler(int sig) {
  3231. (void)sig;
  3232. set_alternate_screen();
  3233. set_unbuffered();
  3234. update_screen_size();
  3235. mouse_enable();
  3236. redraw_all();
  3237. update_title();
  3238. signal(SIGCONT, SIGCONT_handler);
  3239. signal(SIGTSTP, SIGTSTP_handler);
  3240. }
  3241. void try_to_center() {
  3242. int half_a_screen = (global_config.term_height - 3) / 2;
  3243. if (half_a_screen < env->line_no) {
  3244. env->offset = env->line_no - half_a_screen;
  3245. } else {
  3246. env->offset = 0;
  3247. }
  3248. }
  3249. BIM_ACTION(suspend, 0,
  3250. "Suspend bim and the rest of the job it was run in."
  3251. )(void) {
  3252. kill(0, SIGTSTP);
  3253. }
  3254. /**
  3255. * Move the cursor to a specific line.
  3256. */
  3257. BIM_ACTION(goto_line, ARG_IS_CUSTOM,
  3258. "Jump to the requested line."
  3259. )(int line) {
  3260. if (line == -1) line = env->line_count;
  3261. /* Respect file bounds */
  3262. if (line < 1) line = 1;
  3263. if (line > env->line_count) line = env->line_count;
  3264. /* Move the cursor / text region offsets */
  3265. env->coffset = 0;
  3266. env->line_no = line;
  3267. env->col_no = 1;
  3268. if (!env->loading) {
  3269. if (line > env->offset && line < env->offset + global_config.term_height - global_config.bottom_size) {
  3270. place_cursor_actual();
  3271. } else {
  3272. try_to_center();
  3273. }
  3274. redraw_most();
  3275. } else {
  3276. try_to_center();
  3277. }
  3278. }
  3279. /**
  3280. * Processs (part of) a file and add it to a buffer.
  3281. */
  3282. void add_buffer(uint8_t * buf, int size) {
  3283. for (int i = 0; i < size; ++i) {
  3284. if (!decode(&state, &codepoint_r, buf[i])) {
  3285. uint32_t c = codepoint_r;
  3286. if (c == '\n') {
  3287. if (!env->crnl && env->lines[env->line_no-1]->actual && env->lines[env->line_no-1]->text[env->lines[env->line_no-1]->actual-1].codepoint == '\r') {
  3288. env->lines[env->line_no-1]->actual--;
  3289. env->crnl = 1;
  3290. }
  3291. env->lines = add_line(env->lines, env->line_no);
  3292. env->col_no = 1;
  3293. env->line_no += 1;
  3294. } else if (env->crnl && c == '\r') {
  3295. continue;
  3296. } else {
  3297. char_t _c;
  3298. _c.codepoint = (uint32_t)c;
  3299. _c.flags = 0;
  3300. _c.display_width = codepoint_width((wchar_t)c);
  3301. line_t * line = env->lines[env->line_no - 1];
  3302. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  3303. if (line != nline) {
  3304. env->lines[env->line_no - 1] = nline;
  3305. }
  3306. env->col_no += 1;
  3307. }
  3308. } else if (state == UTF8_REJECT) {
  3309. state = 0;
  3310. }
  3311. }
  3312. }
  3313. /**
  3314. * Add a raw string to a buffer. Convenience wrapper
  3315. * for add_buffer for nil-terminated strings.
  3316. */
  3317. void add_string(char * string) {
  3318. add_buffer((uint8_t*)string,strlen(string));
  3319. }
  3320. int str_ends_with(const char * haystack, const char * needle) {
  3321. int i = strlen(haystack);
  3322. int j = strlen(needle);
  3323. do {
  3324. if (haystack[i] != needle[j]) return 0;
  3325. if (j == 0) return 1;
  3326. if (i == 0) return 0;
  3327. i--;
  3328. j--;
  3329. } while (1);
  3330. }
  3331. /**
  3332. * Find a syntax highlighter for the given filename.
  3333. */
  3334. struct syntax_definition * match_syntax(char * file) {
  3335. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3336. for (char ** ext = s->ext; *ext; ++ext) {
  3337. if (str_ends_with(file, *ext)) return s;
  3338. }
  3339. }
  3340. return NULL;
  3341. }
  3342. /**
  3343. * Set the syntax configuration by the name of the syntax highlighter.
  3344. */
  3345. void set_syntax_by_name(const char * name) {
  3346. if (!strcmp(name,"none")) {
  3347. for (int i = 0; i < env->line_count; ++i) {
  3348. env->lines[i]->istate = -1;
  3349. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3350. env->lines[i]->text[j].flags = 0;
  3351. }
  3352. }
  3353. env->syntax = NULL;
  3354. redraw_all();
  3355. return;
  3356. }
  3357. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  3358. if (!strcmp(name,s->name)) {
  3359. env->syntax = s;
  3360. for (int i = 0; i < env->line_count; ++i) {
  3361. env->lines[i]->istate = -1;
  3362. }
  3363. for (int i = 0; i < env->line_count; ++i) {
  3364. recalculate_syntax(env->lines[i],i);
  3365. }
  3366. redraw_all();
  3367. return;
  3368. }
  3369. }
  3370. render_error("unrecognized syntax type");
  3371. }
  3372. /**
  3373. * Check if a string is all numbers.
  3374. */
  3375. int is_all_numbers(const char * c) {
  3376. while (*c) {
  3377. if (!isdigit(*c)) return 0;
  3378. c++;
  3379. }
  3380. return 1;
  3381. }
  3382. struct file_listing {
  3383. int type;
  3384. char * filename;
  3385. };
  3386. int sort_files(const void * a, const void * b) {
  3387. struct file_listing * _a = (struct file_listing *)a;
  3388. struct file_listing * _b = (struct file_listing *)b;
  3389. if (_a->type == _b->type) {
  3390. return strcmp(_a->filename, _b->filename);
  3391. } else {
  3392. return _a->type - _b->type;
  3393. }
  3394. }
  3395. void read_directory_into_buffer(char * file) {
  3396. DIR * dirp = opendir(file);
  3397. if (!dirp) {
  3398. env->loading = 0;
  3399. return;
  3400. }
  3401. add_string("# Directory listing for `");
  3402. add_string(file);
  3403. add_string("`\n");
  3404. /* Flexible array to hold directory contents */
  3405. int available = 32;
  3406. int count = 0;
  3407. struct file_listing * files = calloc(sizeof(struct file_listing), available);
  3408. /* Read directory */
  3409. struct dirent * ent = readdir(dirp);
  3410. while (ent) {
  3411. struct stat statbuf;
  3412. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);
  3413. snprintf(tmp, strlen(file) + 1 + strlen(ent->d_name) + 1, "%s/%s", file, ent->d_name);
  3414. stat(tmp, &statbuf);
  3415. int type = (S_ISDIR(statbuf.st_mode)) ? 'd' : 'f';
  3416. if (count + 1 == available) {
  3417. available *= 2; \
  3418. files = realloc(files, sizeof(struct file_listing) * available); \
  3419. } \
  3420. files[count].type = type;
  3421. files[count].filename = strdup(ent->d_name);
  3422. count++;
  3423. ent = readdir(dirp);
  3424. }
  3425. closedir(dirp);
  3426. /* Sort directory entries */
  3427. qsort(files, count, sizeof(struct file_listing), sort_files);
  3428. for (int i = 0; i < count; ++i) {
  3429. add_string(files[i].type == 'd' ? "d" : "f");
  3430. add_string(" ");
  3431. add_string(files[i].filename);
  3432. add_string("\n");
  3433. free(files[i].filename);
  3434. }
  3435. free(files);
  3436. env->file_name = strdup(file);
  3437. env->syntax = find_syntax_calculator("dirent");
  3438. for (int i = 0; i < env->line_count; ++i) {
  3439. recalculate_syntax(env->lines[i],i);
  3440. }
  3441. env->readonly = 1;
  3442. env->loading = 0;
  3443. env->mode = MODE_DIRECTORY_BROWSE;
  3444. env->line_no = 1;
  3445. redraw_all();
  3446. }
  3447. BIM_ACTION(open_file_from_line, 0,
  3448. "When browsing a directory, open the file under the cursor."
  3449. )(void) {
  3450. if (env->lines[env->line_no-1]->actual < 1) return;
  3451. if (env->lines[env->line_no-1]->text[0].codepoint != 'd' &&
  3452. env->lines[env->line_no-1]->text[0].codepoint != 'f') return;
  3453. /* Collect file name */
  3454. char * tmp = malloc(strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7); /* Should be enough */
  3455. memset(tmp, 0, strlen(env->file_name) + 1 + env->lines[env->line_no-1]->actual * 7);
  3456. char * t = tmp;
  3457. /* Start by copying the filename */
  3458. t += sprintf(t, "%s/", env->file_name);
  3459. /* Start from character 2 to skip d/f and space */
  3460. for (int i = 2; i < env->lines[env->line_no-1]->actual; ++i) {
  3461. t += to_eight(env->lines[env->line_no-1]->text[i].codepoint, t);
  3462. }
  3463. *t = '\0';
  3464. /* Normalize */
  3465. char tmp_path[PATH_MAX+1];
  3466. if (!realpath(tmp, tmp_path)) {
  3467. free(tmp);
  3468. return;
  3469. }
  3470. free(tmp);
  3471. /* Open file */
  3472. buffer_t * old_buffer = env;
  3473. open_file(tmp_path);
  3474. buffer_close(old_buffer);
  3475. update_title();
  3476. redraw_all();
  3477. }
  3478. int line_matches(line_t * line, char * string) {
  3479. uint32_t c, state = 0;
  3480. int i = 0;
  3481. while (*string) {
  3482. if (!decode(&state, &c, *string)) {
  3483. if (i >= line->actual) return 0;
  3484. if (line->text[i].codepoint != c) return 0;
  3485. string++;
  3486. i++;
  3487. } else if (state == UTF8_REJECT) {
  3488. state = 0;
  3489. }
  3490. }
  3491. return 1;
  3492. }
  3493. void run_onload(buffer_t * env) {
  3494. if (has_function("onload:*")) {
  3495. run_function("onload:*");
  3496. }
  3497. if (env->syntax) {
  3498. char tmp[512];
  3499. sprintf(tmp, "onload:%s", env->syntax->name);
  3500. if (has_function(tmp)) {
  3501. run_function(tmp);
  3502. }
  3503. }
  3504. }
  3505. /**
  3506. * Create a new buffer from a file.
  3507. */
  3508. void open_file(char * file) {
  3509. env = buffer_new();
  3510. env->width = global_config.term_width;
  3511. env->left = 0;
  3512. env->loading = 1;
  3513. setup_buffer(env);
  3514. FILE * f;
  3515. int init_line = -1;
  3516. if (!strcmp(file,"-")) {
  3517. /**
  3518. * Read file from stdin. stderr provides terminal input.
  3519. */
  3520. if (isatty(STDIN_FILENO)) {
  3521. if (buffers_len == 1) {
  3522. quit("stdin is a terminal and you tried to open -; not letting you do that");
  3523. }
  3524. close_buffer();
  3525. render_error("stdin is a terminal and you tried to open -; not letting you do that");
  3526. return;
  3527. }
  3528. f = stdin;
  3529. env->modified = 1;
  3530. } else {
  3531. char * l = strrchr(file, ':');
  3532. if (l && is_all_numbers(l+1)) {
  3533. *l = '\0';
  3534. l++;
  3535. init_line = atoi(l);
  3536. }
  3537. char * _file = file;
  3538. if (file[0] == '~') {
  3539. char * home = getenv("HOME");
  3540. if (home) {
  3541. _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  3542. sprintf(_file, "%s%s", home, file+1);
  3543. }
  3544. }
  3545. struct stat statbuf;
  3546. if (!stat(_file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  3547. read_directory_into_buffer(_file);
  3548. if (file != _file) free(_file);
  3549. return;
  3550. }
  3551. f = fopen(_file, "r");
  3552. if (file != _file) free(_file);
  3553. env->file_name = strdup(file);
  3554. }
  3555. if (!f) {
  3556. if (global_config.highlight_on_open) {
  3557. env->syntax = match_syntax(file);
  3558. }
  3559. env->loading = 0;
  3560. if (global_config.go_to_line) {
  3561. goto_line(1);
  3562. }
  3563. if (env->syntax && env->syntax->prefers_spaces) {
  3564. env->tabs = 0;
  3565. }
  3566. run_onload(env);
  3567. return;
  3568. }
  3569. uint8_t buf[BLOCK_SIZE];
  3570. state = 0;
  3571. while (!feof(f) && !ferror(f)) {
  3572. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  3573. add_buffer(buf, r);
  3574. }
  3575. if (ferror(f)) {
  3576. env->loading = 0;
  3577. return;
  3578. }
  3579. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  3580. /* Remove blank line from end */
  3581. env->lines = remove_line(env->lines, env->line_no-1);
  3582. }
  3583. if (global_config.highlight_on_open) {
  3584. env->syntax = match_syntax(file);
  3585. if (!env->syntax) {
  3586. if (line_matches(env->lines[0], "<?xml")) set_syntax_by_name("xml");
  3587. else if (line_matches(env->lines[0], "<!doctype")) set_syntax_by_name("xml");
  3588. else if (line_matches(env->lines[0], "#!/usr/bin/env bash")) set_syntax_by_name("bash");
  3589. else if (line_matches(env->lines[0], "#!/bin/bash")) set_syntax_by_name("bash");
  3590. else if (line_matches(env->lines[0], "#!/bin/sh")) set_syntax_by_name("bash");
  3591. else if (line_matches(env->lines[0], "#!/usr/bin/env python")) set_syntax_by_name("py");
  3592. else if (line_matches(env->lines[0], "#!/usr/bin/env groovy")) set_syntax_by_name("groovy");
  3593. }
  3594. if (!env->syntax && global_config.syntax_fallback) {
  3595. set_syntax_by_name(global_config.syntax_fallback);
  3596. }
  3597. for (int i = 0; i < env->line_count; ++i) {
  3598. recalculate_syntax(env->lines[i],i);
  3599. }
  3600. }
  3601. /* Try to automatically figure out tabs vs. spaces */
  3602. int tabs = 0, spaces = 0;
  3603. for (int i = 0; i < env->line_count; ++i) {
  3604. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  3605. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  3606. if (env->lines[i]->text[0].codepoint == ' ' &&
  3607. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  3608. spaces++;
  3609. }
  3610. }
  3611. if (spaces > tabs) {
  3612. env->tabs = 0;
  3613. } else if (spaces == tabs && env->syntax) {
  3614. env->tabs = env->syntax->prefers_spaces;
  3615. }
  3616. /* TODO figure out tabstop for spaces? */
  3617. env->loading = 0;
  3618. if (global_config.check_git) {
  3619. env->checkgitstatusonwrite = 1;
  3620. git_examine(file);
  3621. }
  3622. for (int i = 0; i < env->line_count; ++i) {
  3623. recalculate_tabs(env->lines[i]);
  3624. }
  3625. if (global_config.go_to_line) {
  3626. if (init_line != -1) {
  3627. goto_line(init_line);
  3628. } else {
  3629. env->line_no = 1;
  3630. env->col_no = 1;
  3631. fetch_from_biminfo(env);
  3632. place_cursor_actual();
  3633. redraw_all();
  3634. set_preferred_column();
  3635. }
  3636. }
  3637. fclose(f);
  3638. run_onload(env);
  3639. }
  3640. /**
  3641. * Clean up the terminal and exit the editor.
  3642. */
  3643. void quit(const char * message) {
  3644. mouse_disable();
  3645. set_buffered();
  3646. reset();
  3647. clear_screen();
  3648. show_cursor();
  3649. unset_alternate_screen();
  3650. if (message) {
  3651. fprintf(stdout, "%s\n", message);
  3652. }
  3653. exit(0);
  3654. }
  3655. /**
  3656. * Try to quit, but don't continue if there are
  3657. * modified buffers open.
  3658. */
  3659. void try_quit(void) {
  3660. for (int i = 0; i < buffers_len; i++ ) {
  3661. buffer_t * _env = buffers[i];
  3662. if (_env->modified) {
  3663. if (_env->file_name) {
  3664. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  3665. } else {
  3666. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  3667. }
  3668. return;
  3669. }
  3670. }
  3671. /* Close all buffers */
  3672. while (buffers_len) {
  3673. buffer_close(buffers[0]);
  3674. }
  3675. quit(NULL);
  3676. }
  3677. /**
  3678. * Switch to the previous buffer
  3679. */
  3680. BIM_ACTION(previous_tab, 0,
  3681. "Switch the previoius tab"
  3682. )(void) {
  3683. buffer_t * last = NULL;
  3684. for (int i = 0; i < buffers_len; i++) {
  3685. buffer_t * _env = buffers[i];
  3686. if (_env == env) {
  3687. if (last) {
  3688. /* Wrap around */
  3689. env = last;
  3690. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3691. redraw_all();
  3692. update_title();
  3693. return;
  3694. } else {
  3695. env = buffers[buffers_len-1];
  3696. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3697. redraw_all();
  3698. update_title();
  3699. return;
  3700. }
  3701. }
  3702. last = _env;
  3703. }
  3704. }
  3705. /**
  3706. * Switch to the next buffer
  3707. */
  3708. BIM_ACTION(next_tab, 0,
  3709. "Switch to the next tab"
  3710. )(void) {
  3711. for (int i = 0; i < buffers_len; i++) {
  3712. buffer_t * _env = buffers[i];
  3713. if (_env == env) {
  3714. if (i != buffers_len - 1) {
  3715. env = buffers[i+1];
  3716. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3717. redraw_all();
  3718. update_title();
  3719. return;
  3720. } else {
  3721. /* Wrap around */
  3722. env = buffers[0];
  3723. if (left_buffer && (left_buffer != env && right_buffer != env)) unsplit();
  3724. redraw_all();
  3725. update_title();
  3726. return;
  3727. }
  3728. }
  3729. }
  3730. }
  3731. /**
  3732. * Check for modified lines in a file by examining `git diff` output.
  3733. * This can be enabled globally in bimrc or per environment with the 'git' option.
  3734. */
  3735. int git_examine(char * filename) {
  3736. if (env->modified) return 1;
  3737. int fds[2];
  3738. pipe(fds);
  3739. int child = fork();
  3740. if (child == 0) {
  3741. FILE * dev_null = fopen("/dev/null","w");
  3742. close(fds[0]);
  3743. dup2(fds[1], STDOUT_FILENO);
  3744. dup2(fileno(dev_null), STDERR_FILENO);
  3745. char * args[] = {"git","--no-pager","diff","-U0","--no-color","--",filename,NULL};
  3746. exit(execvp("git",args));
  3747. } else if (child < 0) {
  3748. return 1;
  3749. }
  3750. close(fds[1]);
  3751. FILE * f = fdopen(fds[0],"r");
  3752. int line_offset = 0;
  3753. while (!feof(f)) {
  3754. int c = fgetc(f);
  3755. if (c < 0) break;
  3756. if (c == '@' && line_offset == 0) {
  3757. /* Read line offset, count */
  3758. if (fgetc(f) == '@' && fgetc(f) == ' ' && fgetc(f) == '-') {
  3759. /* This algorithm is borrowed from Kakoune and only requires us to parse the @@ line */
  3760. int from_line = 0;
  3761. int from_count = 0;
  3762. int to_line = 0;
  3763. int to_count = 0;
  3764. fscanf(f,"%d",&from_line);
  3765. if (fgetc(f) == ',') {
  3766. fscanf(f,"%d",&from_count);
  3767. } else {
  3768. from_count = 1;
  3769. }
  3770. fscanf(f,"%d",&to_line);
  3771. if (fgetc(f) == ',') {
  3772. fscanf(f,"%d",&to_count);
  3773. } else {
  3774. to_count = 1;
  3775. }
  3776. if (to_line > env->line_count) continue;
  3777. if (from_count == 0 && to_count > 0) {
  3778. /* No -, all + means all of to_count is green */
  3779. for (int i = 0; i < to_count; ++i) {
  3780. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3781. }
  3782. } else if (from_count > 0 && to_count == 0) {
  3783. /*
  3784. * No +, all - means we have a deletion. We mark the next line such that it has a red bar at the top
  3785. * Note that to_line is one lower than the affacted line, so we don't need to mes with indexes.
  3786. */
  3787. if (to_line >= env->line_count) continue;
  3788. env->lines[to_line]->rev_status = 4; /* Red */
  3789. } else if (from_count > 0 && from_count == to_count) {
  3790. /* from = to, all modified */
  3791. for (int i = 0; i < to_count; ++i) {
  3792. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3793. }
  3794. } else if (from_count > 0 && from_count < to_count) {
  3795. /* from < to, some modified, some added */
  3796. for (int i = 0; i < from_count; ++i) {
  3797. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3798. }
  3799. for (int i = from_count; i < to_count; ++i) {
  3800. env->lines[to_line+i-1]->rev_status = 1; /* Green */
  3801. }
  3802. } else if (to_count > 0 && from_count > to_count) {
  3803. /* from > to, we deleted but also modified some lines */
  3804. env->lines[to_line-1]->rev_status = 5; /* Red + Blue */
  3805. for (int i = 1; i < to_count; ++i) {
  3806. env->lines[to_line+i-1]->rev_status = 3; /* Blue */
  3807. }
  3808. }
  3809. }
  3810. }
  3811. if (c == '\n') {
  3812. line_offset = 0;
  3813. continue;
  3814. }
  3815. line_offset++;
  3816. }
  3817. fclose(f);
  3818. return 0;
  3819. }
  3820. /**
  3821. * Write file contents to FILE
  3822. */
  3823. void output_file(buffer_t * env, FILE * f) {
  3824. int i, j;
  3825. for (i = 0; i < env->line_count; ++i) {
  3826. line_t * line = env->lines[i];
  3827. line->rev_status = 0;
  3828. for (j = 0; j < line->actual; j++) {
  3829. char_t c = line->text[j];
  3830. if (c.codepoint == 0) {
  3831. char buf[1] = {0};
  3832. fwrite(buf, 1, 1, f);
  3833. } else {
  3834. char tmp[8] = {0};
  3835. int i = to_eight(c.codepoint, tmp);
  3836. fwrite(tmp, i, 1, f);
  3837. }
  3838. }
  3839. if (env->crnl) fputc('\r', f);
  3840. fputc('\n', f);
  3841. }
  3842. }
  3843. /**
  3844. * Write active buffer to file
  3845. */
  3846. void write_file(char * file) {
  3847. if (!file) {
  3848. render_error("Need a file to write to.");
  3849. return;
  3850. }
  3851. FILE * f = fopen(file, "w+");
  3852. if (!f) {
  3853. render_error("Failed to open file for writing.");
  3854. return;
  3855. }
  3856. /* Go through each line and convert it back to UTF-8 */
  3857. output_file(env, f);
  3858. fclose(f);
  3859. /* Mark it no longer modified */
  3860. env->modified = 0;
  3861. env->last_save_history = env->history;
  3862. /* If there was no file name set, set one */
  3863. if (!env->file_name) {
  3864. env->file_name = malloc(strlen(file) + 1);
  3865. memcpy(env->file_name, file, strlen(file) + 1);
  3866. }
  3867. if (env->checkgitstatusonwrite) {
  3868. git_examine(file);
  3869. }
  3870. update_title();
  3871. redraw_all();
  3872. }
  3873. /**
  3874. * Close the active buffer
  3875. */
  3876. void close_buffer(void) {
  3877. buffer_t * previous_env = env;
  3878. buffer_t * new_env = buffer_close(env);
  3879. if (new_env == previous_env) {
  3880. /* ?? Failed to close buffer */
  3881. render_error("lolwat");
  3882. }
  3883. if (left_buffer && env == left_buffer) {
  3884. left_buffer = NULL;
  3885. right_buffer->left = 0;
  3886. right_buffer->width = global_config.term_width;
  3887. right_buffer = NULL;
  3888. } else if (left_buffer && env == right_buffer) {
  3889. right_buffer = NULL;
  3890. left_buffer->left = 0;
  3891. left_buffer->width = global_config.term_width;
  3892. left_buffer = NULL;
  3893. }
  3894. /* No more buffers, exit */
  3895. if (!new_env) {
  3896. quit(NULL);
  3897. }
  3898. /* Set the new active buffer */
  3899. env = new_env;
  3900. /* Redraw the screen */
  3901. redraw_all();
  3902. update_title();
  3903. }
  3904. /**
  3905. * Set the visual column the cursor should attempt to keep
  3906. * when moving up and down based on where the cursor currently is.
  3907. * This should happen whenever the user intentionally changes
  3908. * the cursor's horizontal positioning, such as with left/right
  3909. * arrow keys, word-move, search, mouse, etc.
  3910. */
  3911. void set_preferred_column(void) {
  3912. int c = 0;
  3913. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3914. c += env->lines[env->line_no-1]->text[i].display_width;
  3915. }
  3916. env->preferred_column = c;
  3917. }
  3918. BIM_ACTION(cursor_down, 0,
  3919. "Move the cursor one line down."
  3920. )(void) {
  3921. /* If this isn't already the last line... */
  3922. if (env->line_no < env->line_count) {
  3923. /* Move the cursor down */
  3924. env->line_no += 1;
  3925. /* Try to place the cursor horizontally at the preferred column */
  3926. int _x = 0;
  3927. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3928. char_t * c = &env->lines[env->line_no-1]->text[i];
  3929. _x += c->display_width;
  3930. env->col_no = i+1;
  3931. if (_x > env->preferred_column) {
  3932. break;
  3933. }
  3934. }
  3935. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3936. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3937. }
  3938. /*
  3939. * If the horizontal cursor position exceeds the width the new line,
  3940. * then move the cursor left to the extent of the new line.
  3941. *
  3942. * If we're in insert mode, we can go one cell beyond the end of the line
  3943. */
  3944. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3945. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3946. if (env->col_no == 0) env->col_no = 1;
  3947. }
  3948. if (env->loading) return;
  3949. /*
  3950. * If the screen was scrolled horizontally, unscroll it;
  3951. * if it will be scrolled on this line as well, that will
  3952. * be handled by place_cursor_actual
  3953. */
  3954. int redraw = 0;
  3955. if (env->coffset != 0) {
  3956. env->coffset = 0;
  3957. redraw = 1;
  3958. }
  3959. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3960. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  3961. env->offset += 1;
  3962. /* Tell terminal to scroll */
  3963. if (global_config.can_scroll && !left_buffer) {
  3964. shift_up(1);
  3965. /* A new line appears on screen at the bottom, draw it */
  3966. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  3967. if (env->offset + l < env->line_count + 1) {
  3968. redraw_line(env->offset + l-1);
  3969. } else {
  3970. draw_excess_line(l - 1);
  3971. }
  3972. } else {
  3973. redraw_text();
  3974. }
  3975. redraw_tabbar();
  3976. redraw_statusbar();
  3977. redraw_commandline();
  3978. place_cursor_actual();
  3979. return;
  3980. } else if (redraw) {
  3981. /* Otherwise, if we need to redraw because of coffset change, do that */
  3982. redraw_text();
  3983. }
  3984. set_history_break();
  3985. /* Update the status bar */
  3986. redraw_statusbar();
  3987. /* Place the terminal cursor again */
  3988. place_cursor_actual();
  3989. }
  3990. }
  3991. BIM_ACTION(cursor_up, 0,
  3992. "Move the cursor up one line."
  3993. )(void) {
  3994. /* If this isn't the first line already */
  3995. if (env->line_no > 1) {
  3996. /* Move the cursor down */
  3997. env->line_no -= 1;
  3998. /* Try to place the cursor horizontally at the preferred column */
  3999. int _x = 0;
  4000. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  4001. char_t * c = &env->lines[env->line_no-1]->text[i];
  4002. _x += c->display_width;
  4003. env->col_no = i+1;
  4004. if (_x > env->preferred_column) {
  4005. break;
  4006. }
  4007. }
  4008. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  4009. env->col_no = env->lines[env->line_no-1]->actual + 1;
  4010. }
  4011. /*
  4012. * If the horizontal cursor position exceeds the width the new line,
  4013. * then move the cursor left to the extent of the new line.
  4014. *
  4015. * If we're in insert mode, we can go one cell beyond the end of the line
  4016. */
  4017. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  4018. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  4019. if (env->col_no == 0) env->col_no = 1;
  4020. }
  4021. if (env->loading) return;
  4022. /*
  4023. * If the screen was scrolled horizontally, unscroll it;
  4024. * if it will be scrolled on this line as well, that will
  4025. * be handled by place_cursor_actual
  4026. */
  4027. int redraw = 0;
  4028. if (env->coffset != 0) {
  4029. env->coffset = 0;
  4030. redraw = 1;
  4031. }
  4032. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  4033. if (env->line_no <= e) {
  4034. env->offset -= 1;
  4035. /* Tell terminal to scroll */
  4036. if (global_config.can_scroll && !left_buffer) {
  4037. shift_down(1);
  4038. /*
  4039. * The line at the top of the screen should always be real
  4040. * so we can just call redraw_line here
  4041. */
  4042. redraw_line(env->offset);
  4043. } else {
  4044. redraw_text();
  4045. }
  4046. redraw_tabbar();
  4047. redraw_statusbar();
  4048. redraw_commandline();
  4049. place_cursor_actual();
  4050. return;
  4051. } else if (redraw) {
  4052. /* Otherwise, if we need to redraw because of coffset change, do that */
  4053. redraw_text();
  4054. }
  4055. set_history_break();
  4056. /* Update the status bar */
  4057. redraw_statusbar();
  4058. /* Place the terminal cursor again */
  4059. place_cursor_actual();
  4060. }
  4061. }
  4062. BIM_ACTION(cursor_left, 0,
  4063. "Move the cursor one character to the left."
  4064. )(void) {
  4065. if (env->col_no > 1) {
  4066. env->col_no -= 1;
  4067. /* Update the status bar */
  4068. redraw_statusbar();
  4069. /* Place the terminal cursor again */
  4070. place_cursor_actual();
  4071. }
  4072. set_history_break();
  4073. set_preferred_column();
  4074. }
  4075. BIM_ACTION(cursor_right, 0,
  4076. "Move the cursor one character to the right."
  4077. )(void) {
  4078. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  4079. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  4080. env->col_no += 1;
  4081. /* Update the status bar */
  4082. redraw_statusbar();
  4083. /* Place the terminal cursor again */
  4084. place_cursor_actual();
  4085. }
  4086. set_history_break();
  4087. set_preferred_column();
  4088. }
  4089. BIM_ACTION(cursor_home, 0,
  4090. "Move the cursor to the beginning of the line."
  4091. )(void) {
  4092. env->col_no = 1;
  4093. set_history_break();
  4094. set_preferred_column();
  4095. /* Update the status bar */
  4096. redraw_statusbar();
  4097. /* Place the terminal cursor again */
  4098. place_cursor_actual();
  4099. }
  4100. BIM_ACTION(cursor_end, 0,
  4101. "Move the cursor to the end of the line, or past the end in insert mode."
  4102. )(void) {
  4103. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  4104. set_history_break();
  4105. set_preferred_column();
  4106. /* Update the status bar */
  4107. redraw_statusbar();
  4108. /* Place the terminal cursor again */
  4109. place_cursor_actual();
  4110. }
  4111. BIM_ACTION(leave_insert, 0,
  4112. "Leave insert modes and return to normal mode."
  4113. )(void) {
  4114. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4115. env->col_no = env->lines[env->line_no-1]->actual;
  4116. if (env->col_no == 0) env->col_no = 1;
  4117. set_preferred_column();
  4118. }
  4119. set_history_break();
  4120. env->mode = MODE_NORMAL;
  4121. redraw_commandline();
  4122. }
  4123. /**
  4124. * Helper for handling smart case sensitivity.
  4125. */
  4126. int search_matches(uint32_t a, uint32_t b, int mode) {
  4127. if (mode == 0) {
  4128. return a == b;
  4129. } else if (mode == 1) {
  4130. return tolower(a) == tolower(b);
  4131. }
  4132. return 0;
  4133. }
  4134. int subsearch_matches(line_t * line, int j, uint32_t * needle, int ignorecase, int *len) {
  4135. int k = j;
  4136. uint32_t * match = needle;
  4137. if (*match == '^') {
  4138. if (j != 0) return 0;
  4139. match++;
  4140. }
  4141. while (k < line->actual + 1) {
  4142. if (*match == '\0') {
  4143. if (len) *len = k - j;
  4144. return 1;
  4145. }
  4146. if (*match == '$') {
  4147. if (k != line->actual) return 0;
  4148. match++;
  4149. continue;
  4150. }
  4151. if (*match == '.') {
  4152. if (match[1] == '*') {
  4153. int greedy = !(match[2] == '?');
  4154. /* Short-circuit chained .*'s */
  4155. if (match[greedy ? 2 : 3] == '.' && match[greedy ? 3 : 4] == '*') {
  4156. int _len;
  4157. if (subsearch_matches(line, k, &match[greedy ? 2 : 3], ignorecase, &_len)) {
  4158. if (len) *len = _len + k - j;
  4159. return 1;
  4160. }
  4161. return 0;
  4162. }
  4163. int _j = greedy ? line->actual : k;
  4164. int _break = -1;
  4165. int _len = -1;
  4166. if (!match[greedy ? 2 : 3]) {
  4167. _len = greedy ? (line->actual - _j) : 0;
  4168. _break = _j;
  4169. } else {
  4170. while (_j < line->actual + 1 && _j >= k) {
  4171. int len;
  4172. if (subsearch_matches(line, _j, &match[greedy ? 2 : 3], ignorecase, &len)) {
  4173. _break = _j;
  4174. _len = len;
  4175. break;
  4176. }
  4177. _j += (greedy ? -1 : 1);
  4178. }
  4179. }
  4180. if (_break != -1) {
  4181. if (len) *len = (_break - j) + _len;
  4182. return 1;
  4183. }
  4184. return 0;
  4185. } else {
  4186. if (k >= line->actual) return 0;
  4187. match++;
  4188. k++;
  4189. continue;
  4190. }
  4191. }
  4192. if (*match == '\\' && (match[1] == '$' || match[1] == '^' || match[1] == '/' || match[1] == '\\' || match[1] == '.')) {
  4193. match++;
  4194. } else if (*match == '\\' && match[1] == 't') {
  4195. if (line->text[k].codepoint != '\t') break;
  4196. match += 2;
  4197. k++;
  4198. continue;
  4199. }
  4200. if (k == line->actual) break;
  4201. if (!search_matches(*match, line->text[k].codepoint, ignorecase)) break;
  4202. match++;
  4203. k++;
  4204. }
  4205. return 0;
  4206. }
  4207. /**
  4208. * Replace text on a given line with other text.
  4209. */
  4210. void perform_replacement(int line_no, uint32_t * needle, uint32_t * replacement, int col, int ignorecase, int *out_col) {
  4211. line_t * line = env->lines[line_no-1];
  4212. int j = col;
  4213. while (j < line->actual + 1) {
  4214. int match_len;
  4215. if (subsearch_matches(line,j,needle,ignorecase,&match_len)) {
  4216. /* Perform replacement */
  4217. for (int i = 0; i < match_len; ++i) {
  4218. line_delete(line, j+1, line_no-1);
  4219. }
  4220. int t = 0;
  4221. for (uint32_t * r = replacement; *r; ++r) {
  4222. char_t _c;
  4223. _c.codepoint = *r;
  4224. _c.flags = 0;
  4225. _c.display_width = codepoint_width(*r);
  4226. line_t * nline = line_insert(line, _c, j + t, line_no -1);
  4227. if (line != nline) {
  4228. env->lines[line_no-1] = nline;
  4229. line = nline;
  4230. }
  4231. t++;
  4232. }
  4233. *out_col = j + t;
  4234. set_modified();
  4235. return;
  4236. }
  4237. j++;
  4238. }
  4239. *out_col = -1;
  4240. }
  4241. #define COMMAND_HISTORY_MAX 255
  4242. unsigned char * command_history[COMMAND_HISTORY_MAX] = {NULL};
  4243. /**
  4244. * Add a command to the history. If that command was
  4245. * already in history, it is moved to the front of the list;
  4246. * otherwise, the whole list is shifted backwards and
  4247. * overflow is freed up.
  4248. */
  4249. void insert_command_history(char * cmd) {
  4250. /* See if this is already in the history. */
  4251. size_t amount_to_shift = COMMAND_HISTORY_MAX - 1;
  4252. for (int i = 0; i < COMMAND_HISTORY_MAX && command_history[i]; ++i) {
  4253. if (!strcmp((char*)command_history[i], cmd)) {
  4254. free(command_history[i]);
  4255. amount_to_shift = i;
  4256. break;
  4257. }
  4258. }
  4259. /* Remove last entry that will roll off the stack */
  4260. if (amount_to_shift == COMMAND_HISTORY_MAX - 1) {
  4261. if (command_history[COMMAND_HISTORY_MAX-1]) free(command_history[COMMAND_HISTORY_MAX-1]);
  4262. }
  4263. /* Roll the history */
  4264. memmove(&command_history[1], &command_history[0], sizeof(char *) * (amount_to_shift));
  4265. command_history[0] = (unsigned char*)strdup(cmd);
  4266. }
  4267. static uint32_t term_colors[] = {
  4268. 0x000000, 0xcc0000, 0x3e9a06, 0xc4a000, 0x3465a4, 0x75507b, 0x06989a, 0xeeeeec, 0x555753, 0xef2929, 0x8ae234, 0xfce94f, 0x729fcf, 0xad7fa8, 0x34e2e2,
  4269. 0xFFFFFF, 0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff, 0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff, 0x008700, 0x00875f,
  4270. 0x008787, 0x0087af, 0x0087d7, 0x0087ff, 0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff, 0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7,
  4271. 0x00d7ff, 0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff, 0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff, 0x5f5f00, 0x5f5f5f,
  4272. 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff, 0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff, 0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7,
  4273. 0x5fafff, 0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff, 0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff, 0x870000, 0x87005f,
  4274. 0x870087, 0x8700af, 0x8700d7, 0x8700ff, 0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff, 0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7,
  4275. 0x8787ff, 0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff, 0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff, 0x87ff00, 0x87ff5f,
  4276. 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff, 0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff, 0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7,
  4277. 0xaf5fff, 0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff, 0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff, 0xafd700, 0xafd75f,
  4278. 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff, 0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff, 0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7,
  4279. 0xd700ff, 0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff, 0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff, 0xd7af00, 0xd7af5f,
  4280. 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff, 0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff, 0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7,
  4281. 0xd7ffff, 0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff, 0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff, 0xff8700, 0xff875f,
  4282. 0xff8787, 0xff87af, 0xff87d7, 0xff87ff, 0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff, 0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7,
  4283. 0xffd7ff, 0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff, 0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a, 0x444444, 0x4e4e4e,
  4284. 0x585858, 0x626262, 0x6c6c6c, 0x767676, 0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2, 0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4,
  4285. 0xeeeeee,
  4286. };
  4287. /**
  4288. * Convert a color setting from terminal format
  4289. * to a hexadecimal color code and add it to the current
  4290. * buffer. This is used for HTML conversion, but could
  4291. * possibly be used for other purposes.
  4292. */
  4293. static void html_convert_color(const char * color_string) {
  4294. char tmp[100];
  4295. if (!strncmp(color_string,"2;",2)) {
  4296. /* 24-bit color */
  4297. int red, green, blue;
  4298. sscanf(color_string+2,"%d;%d;%d",&red,&green,&blue);
  4299. sprintf(tmp, "#%02x%02x%02x;", red,green,blue);
  4300. } else if (!strncmp(color_string,"5;",2)) {
  4301. /* 256 colors; needs lookup table */
  4302. int index;
  4303. sscanf(color_string+2,"%d",&index);
  4304. sprintf(tmp,"#%06x;", (unsigned int)term_colors[(index >= 0 && index <= 255) ? index : 0]);
  4305. } else {
  4306. /* 16 colors; needs lookup table */
  4307. int index;
  4308. uint32_t color;
  4309. sscanf(color_string+1,"%d",&index);
  4310. if (index >= 10) {
  4311. index -= 10;
  4312. color = term_colors[index+8];
  4313. } else if (index == 9) {
  4314. color = term_colors[0];
  4315. } else {
  4316. color = term_colors[index];
  4317. }
  4318. sprintf(tmp,"#%06x;", (unsigned int)color);
  4319. }
  4320. add_string(tmp);
  4321. char * italic = strstr(color_string,";3");
  4322. if (italic && italic[2] == '\0') {
  4323. add_string(" font-style: oblique;");
  4324. }
  4325. char * bold = strstr(color_string,";1");
  4326. if (bold && bold[2] == '\0') {
  4327. add_string(" font-weight: bold;");
  4328. }
  4329. char * underline = strstr(color_string,";4");
  4330. if (underline && underline[2] == '\0') {
  4331. add_string(" font-decoration: underline;");
  4332. }
  4333. }
  4334. int convert_to_html(void) {
  4335. buffer_t * old = env;
  4336. env = buffer_new();
  4337. setup_buffer(env);
  4338. env->loading = 1;
  4339. add_string("<!doctype html>\n");
  4340. add_string("<html>\n");
  4341. add_string(" <head>\n");
  4342. add_string(" <meta charset=\"UTF-8\">\n");
  4343. if (old->file_name) {
  4344. add_string(" <title>");
  4345. add_string(file_basename(old->file_name));
  4346. add_string("</title>\n");
  4347. }
  4348. add_string(" <style>\n");
  4349. add_string(" body {\n");
  4350. add_string(" margin: 0;\n");
  4351. add_string(" -webkit-text-size-adjust: none;\n");
  4352. add_string(" counter-reset: line-no;\n");
  4353. add_string(" background-color: ");
  4354. /* Convert color */
  4355. html_convert_color(COLOR_BG);
  4356. add_string("\n");
  4357. add_string(" }\n");
  4358. for (int i = 0; i < 15; ++i) {
  4359. /* For each of the relevant flags... */
  4360. char tmp[20];
  4361. sprintf(tmp," .s%d { color: ", i);
  4362. add_string(tmp);
  4363. /* These are special */
  4364. if (i == FLAG_NOTICE) {
  4365. html_convert_color(COLOR_SEARCH_FG);
  4366. add_string(" background-color: ");
  4367. html_convert_color(COLOR_SEARCH_BG);
  4368. } else if (i == FLAG_ERROR) {
  4369. html_convert_color(COLOR_ERROR_FG);
  4370. add_string(" background-color: ");
  4371. html_convert_color(COLOR_ERROR_BG);
  4372. } else {
  4373. html_convert_color(flag_to_color(i));
  4374. }
  4375. add_string("}\n");
  4376. }
  4377. add_string(" pre {\n");
  4378. add_string(" margin: 0;\n");
  4379. add_string(" white-space: pre-wrap;\n");
  4380. add_string(" font-family: \"DejaVu Sans Mono\", Courier, monospace;\n");
  4381. add_string(" font-size: 10pt;\n");
  4382. add_string(" }\n");
  4383. add_string(" pre>span {\n");
  4384. add_string(" display: inline-block;\n");
  4385. add_string(" width: 100%;\n");
  4386. add_string(" }\n");
  4387. add_string(" pre>span>a::before {\n");
  4388. add_string(" counter-increment: line-no;\n");
  4389. add_string(" content: counter(line-no);\n");
  4390. add_string(" padding-right: 1em;\n");
  4391. add_string(" width: 3em;\n");
  4392. add_string(" display: inline-block;\n");
  4393. add_string(" text-align: right;\n");
  4394. add_string(" background-color: ");
  4395. html_convert_color(COLOR_NUMBER_BG);
  4396. add_string("\n");
  4397. add_string(" color: ");
  4398. html_convert_color(COLOR_NUMBER_FG);
  4399. add_string("\n");
  4400. add_string(" }\n");
  4401. add_string(" pre>span:target {\n");
  4402. add_string(" background-color: ");
  4403. html_convert_color(COLOR_ALT_BG);
  4404. add_string("\n");
  4405. add_string(" }\n");
  4406. add_string(" pre>span:target>a::before {\n");
  4407. add_string(" background-color: ");
  4408. html_convert_color(COLOR_NUMBER_FG);
  4409. add_string("\n");
  4410. add_string(" color: ");
  4411. html_convert_color(COLOR_NUMBER_BG);
  4412. add_string("\n");
  4413. add_string(" }\n");
  4414. for (int i = 1; i <= env->tabstop; ++i) {
  4415. char tmp[10];
  4416. sprintf(tmp, ".tab%d", i);
  4417. add_string(" ");
  4418. add_string(tmp);
  4419. add_string(">span {\n");
  4420. add_string(" display: inline-block;\n");
  4421. add_string(" overflow: hidden;\n");
  4422. add_string(" width: 0;\n");
  4423. add_string(" height: 0;\n");
  4424. add_string(" }\n");
  4425. add_string(" ");
  4426. add_string(tmp);
  4427. add_string("::after {\n");
  4428. add_string(" content: '»");
  4429. for (int j = 1; j < i; ++j) {
  4430. add_string("·");
  4431. }
  4432. add_string("';\n");
  4433. add_string(" background-color: ");
  4434. html_convert_color(COLOR_ALT_BG);
  4435. add_string("\n");
  4436. add_string(" color: ");
  4437. html_convert_color(COLOR_ALT_FG);
  4438. add_string("\n");
  4439. add_string(" }\n");
  4440. }
  4441. add_string(" .space {\n");
  4442. add_string(" border-left: 1px solid ");
  4443. html_convert_color(COLOR_ALT_FG);
  4444. add_string("\n");
  4445. add_string(" margin-left: -1px;\n");
  4446. add_string(" }\n");
  4447. add_string(" </style>\n");
  4448. add_string(" </head>\n");
  4449. add_string(" <body><pre>\n");
  4450. for (int i = 0; i < old->line_count; ++i) {
  4451. char tmp[100];
  4452. sprintf(tmp, "<span id=\"L%d\"><a href=\"#L%d\"></a>", i+1, i+1);
  4453. add_string(tmp);
  4454. int last_flag = -1;
  4455. int opened = 0;
  4456. int all_spaces = 1;
  4457. for (int j = 0; j < old->lines[i]->actual; ++j) {
  4458. char_t c = old->lines[i]->text[j];
  4459. if (c.codepoint != ' ') all_spaces = 0;
  4460. if (last_flag == -1 || last_flag != (c.flags & 0x1F)) {
  4461. if (opened) add_string("</span>");
  4462. opened = 1;
  4463. char tmp[100];
  4464. sprintf(tmp, "<span class=\"s%d\">", c.flags & 0x1F);
  4465. add_string(tmp);
  4466. last_flag = (c.flags & 0x1F);
  4467. }
  4468. if (c.codepoint == '<') {
  4469. add_string("&lt;");
  4470. } else if (c.codepoint == '>') {
  4471. add_string("&gt;");
  4472. } else if (c.codepoint == '&') {
  4473. add_string("&amp;");
  4474. } else if (c.codepoint == '\t') {
  4475. char tmp[100];
  4476. sprintf(tmp, "<span class=\"tab%d\"><span> </span></span>",c.display_width);
  4477. add_string(tmp);
  4478. } else if (j > 0 && c.codepoint == ' ' && all_spaces && !(j % old->tabstop)) {
  4479. add_string("<span class=\"space\"> </span>");
  4480. } else {
  4481. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  4482. to_eight(c.codepoint, tmp);
  4483. add_string(tmp);
  4484. }
  4485. }
  4486. if (opened) {
  4487. add_string("</span>");
  4488. } else {
  4489. add_string("<wbr>");
  4490. }
  4491. add_string("</span>\n");
  4492. }
  4493. add_string("</pre></body>\n");
  4494. add_string("</html>\n");
  4495. env->loading = 0;
  4496. env->modified = 1;
  4497. if (old->file_name) {
  4498. char * base = file_basename(old->file_name);
  4499. char * tmp = malloc(strlen(base) + 5);
  4500. *tmp = '\0';
  4501. strcat(tmp, base);
  4502. strcat(tmp, ".htm");
  4503. env->file_name = tmp;
  4504. }
  4505. for (int i = 0; i < env->line_count; ++i) {
  4506. recalculate_tabs(env->lines[i]);
  4507. }
  4508. env->syntax = match_syntax(".htm");
  4509. for (int i = 0; i < env->line_count; ++i) {
  4510. recalculate_syntax(env->lines[i],i);
  4511. }
  4512. return 0;
  4513. }
  4514. /**
  4515. * Based on vim's :TOhtml
  4516. * Convert syntax-highlighted buffer contents to HTML.
  4517. */
  4518. BIM_COMMAND(tohtml,"tohtml","Convert the document to an HTML representation with syntax highlighting.") {
  4519. convert_to_html();
  4520. redraw_all();
  4521. return 0;
  4522. }
  4523. BIM_ALIAS("TOhtml",tohtml,tohtml)
  4524. int _prefix_command_run_script(char * cmd) {
  4525. if (env->mode == MODE_LINE_SELECTION) {
  4526. int range_top, range_bot;
  4527. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4528. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4529. int in[2];
  4530. pipe(in);
  4531. int out[2];
  4532. pipe(out);
  4533. int child = fork();
  4534. /* Open child process and set up pipes */
  4535. if (child == 0) {
  4536. FILE * dev_null = fopen("/dev/null","w"); /* for stderr */
  4537. close(out[0]);
  4538. close(in[1]);
  4539. dup2(out[1], STDOUT_FILENO);
  4540. dup2(in[0], STDIN_FILENO);
  4541. dup2(fileno(dev_null), STDERR_FILENO);
  4542. if (*cmd == '!') {
  4543. system(&cmd[1]); /* Yes we can just do this */
  4544. } else {
  4545. char * const args[] = {"python3","-c",&cmd[1],NULL};
  4546. execvp("python3",args);
  4547. }
  4548. exit(1);
  4549. } else if (child < 0) {
  4550. render_error("Failed to fork");
  4551. return 1;
  4552. }
  4553. close(out[1]);
  4554. close(in[0]);
  4555. /* Write lines to child process */
  4556. FILE * f = fdopen(in[1],"w");
  4557. for (int i = range_top; i <= range_bot; ++i) {
  4558. line_t * line = env->lines[i-1];
  4559. for (int j = 0; j < line->actual; j++) {
  4560. char_t c = line->text[j];
  4561. if (c.codepoint == 0) {
  4562. char buf[1] = {0};
  4563. fwrite(buf, 1, 1, f);
  4564. } else {
  4565. char tmp[8] = {0};
  4566. int i = to_eight(c.codepoint, tmp);
  4567. fwrite(tmp, i, 1, f);
  4568. }
  4569. }
  4570. fputc('\n', f);
  4571. }
  4572. fclose(f);
  4573. close(in[1]);
  4574. /* Read results from child process into a new buffer */
  4575. FILE * result = fdopen(out[0],"r");
  4576. buffer_t * old = env;
  4577. env = buffer_new();
  4578. setup_buffer(env);
  4579. env->loading = 1;
  4580. uint8_t buf[BLOCK_SIZE];
  4581. state = 0;
  4582. while (!feof(result) && !ferror(result)) {
  4583. size_t r = fread(buf, 1, BLOCK_SIZE, result);
  4584. add_buffer(buf, r);
  4585. }
  4586. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  4587. env->lines = remove_line(env->lines, env->line_no-1);
  4588. }
  4589. fclose(result);
  4590. env->loading = 0;
  4591. /* Return to the original buffer and replace the selected lines with the output */
  4592. buffer_t * new = env;
  4593. env = old;
  4594. for (int i = range_top; i <= range_bot; ++i) {
  4595. /* Remove the existing lines */
  4596. env->lines = remove_line(env->lines, range_top-1);
  4597. }
  4598. for (int i = 0; i < new->line_count; ++i) {
  4599. /* Add the new lines */
  4600. env->lines = add_line(env->lines, range_top + i - 1);
  4601. replace_line(env->lines, range_top + i - 1, new->lines[i]);
  4602. recalculate_tabs(env->lines[range_top+i-1]);
  4603. }
  4604. env->modified = 1;
  4605. /* Close the temporary buffer */
  4606. buffer_close(new);
  4607. } else {
  4608. /* Reset and draw some line feeds */
  4609. reset();
  4610. printf("\n\n");
  4611. /* Set buffered for shell application */
  4612. set_buffered();
  4613. /* Call the shell and wait for completion */
  4614. if (*cmd == '!') {
  4615. system(&cmd[1]);
  4616. } else {
  4617. setenv("PYCMD",&cmd[1],1);
  4618. system("python3 -c \"$PYCMD\"");
  4619. }
  4620. /* Return to the editor, wait for user to press enter. */
  4621. set_unbuffered();
  4622. printf("\n\nPress ENTER to continue.");
  4623. int c;
  4624. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  4625. /* Redraw the screen */
  4626. redraw_all();
  4627. }
  4628. /* Done processing command */
  4629. return 0;
  4630. }
  4631. BIM_PREFIX_COMMAND(bang,"!","Executes shell commands.") {
  4632. (void)argc, (void)argv;
  4633. return _prefix_command_run_script(cmd);
  4634. }
  4635. BIM_PREFIX_COMMAND(tick,"`","Executes Python commands.") {
  4636. (void)argc, (void)argv;
  4637. return _prefix_command_run_script(cmd);
  4638. }
  4639. int replace_text(int range_top, int range_bot, char divider, char * needle) {
  4640. char * c = needle;
  4641. char * replacement = NULL;
  4642. char * options = "";
  4643. while (*c) {
  4644. if (*c == divider) {
  4645. *c = '\0';
  4646. replacement = c + 1;
  4647. break;
  4648. }
  4649. c++;
  4650. }
  4651. if (!replacement) {
  4652. render_error("nothing to replace with");
  4653. return 1;
  4654. }
  4655. c = replacement;
  4656. while (*c) {
  4657. if (*c == divider) {
  4658. *c = '\0';
  4659. options = c + 1;
  4660. break;
  4661. }
  4662. c++;
  4663. }
  4664. int global = 0;
  4665. int case_insensitive = 0;
  4666. /* Parse options */
  4667. while (*options) {
  4668. switch (*options) {
  4669. case 'g':
  4670. global = 1;
  4671. break;
  4672. case 'i':
  4673. case_insensitive = 1;
  4674. break;
  4675. }
  4676. options++;
  4677. }
  4678. uint32_t * needle_c = malloc(sizeof(uint32_t) * (strlen(needle) + 1));
  4679. uint32_t * replacement_c = malloc(sizeof(uint32_t) * (strlen(replacement) + 1));
  4680. {
  4681. int i = 0;
  4682. uint32_t c, state = 0;
  4683. for (char * cin = needle; *cin; cin++) {
  4684. if (!decode(&state, &c, *cin)) {
  4685. needle_c[i] = c;
  4686. i++;
  4687. } else if (state == UTF8_REJECT) {
  4688. state = 0;
  4689. }
  4690. }
  4691. needle_c[i] = 0;
  4692. i = 0;
  4693. c = 0;
  4694. state = 0;
  4695. for (char * cin = replacement; *cin; cin++) {
  4696. if (!decode(&state, &c, *cin)) {
  4697. replacement_c[i] = c;
  4698. i++;
  4699. } else if (state == UTF8_REJECT) {
  4700. state = 0;
  4701. }
  4702. }
  4703. replacement_c[i] = 0;
  4704. }
  4705. int replacements = 0;
  4706. for (int line = range_top; line <= range_bot; ++line) {
  4707. int col = 0;
  4708. while (col != -1) {
  4709. perform_replacement(line, needle_c, replacement_c, col, case_insensitive, &col);
  4710. if (col != -1) replacements++;
  4711. if (!global) break;
  4712. }
  4713. }
  4714. free(needle_c);
  4715. free(replacement_c);
  4716. if (replacements) {
  4717. render_status_message("replaced %d instance%s of %s", replacements, replacements == 1 ? "" : "s", needle);
  4718. set_history_break();
  4719. redraw_text();
  4720. } else {
  4721. render_error("Pattern not found: %s", needle);
  4722. }
  4723. return 0;
  4724. }
  4725. BIM_PREFIX_COMMAND(repsome,"s","Perform a replacement over selected lines") {
  4726. int range_top, range_bot;
  4727. if (env->mode == MODE_LINE_SELECTION) {
  4728. range_top = env->start_line < env->line_no ? env->start_line : env->line_no;
  4729. range_bot = env->start_line < env->line_no ? env->line_no : env->start_line;
  4730. } else {
  4731. range_top = env->line_no;
  4732. range_bot = env->line_no;
  4733. }
  4734. return replace_text(range_top, range_bot, cmd[1], &cmd[2]);
  4735. }
  4736. BIM_PREFIX_COMMAND(repall,"%s","Perform a replacement over the entire file.") {
  4737. return replace_text(1, env->line_count, cmd[2], &cmd[3]);
  4738. }
  4739. BIM_COMMAND(e,"e","Open a file") {
  4740. if (argc > 1) {
  4741. /* This actually opens a new tab */
  4742. open_file(argv[1]);
  4743. update_title();
  4744. } else {
  4745. if (env->modified) {
  4746. render_error("File is modified, can not reload.");
  4747. return 1;
  4748. }
  4749. buffer_t * old_env = env;
  4750. open_file(env->file_name);
  4751. buffer_t * new_env = env;
  4752. env = old_env;
  4753. #define SWAP(T,a,b) do { T x = a; a = b; b = x; } while (0)
  4754. SWAP(line_t **, env->lines, new_env->lines);
  4755. SWAP(int, env->line_count, new_env->line_count);
  4756. SWAP(int, env->line_avail, new_env->line_avail);
  4757. SWAP(history_t *, env->history, new_env->history);
  4758. buffer_close(new_env); /* Should probably also free, this needs editing. */
  4759. redraw_all();
  4760. }
  4761. return 0;
  4762. }
  4763. BIM_COMMAND(tabnew,"tabnew","Open a new tab") {
  4764. if (argc > 1) {
  4765. open_file(argv[1]);
  4766. update_title();
  4767. } else {
  4768. env = buffer_new();
  4769. setup_buffer(env);
  4770. redraw_all();
  4771. update_title();
  4772. }
  4773. return 0;
  4774. }
  4775. BIM_COMMAND(w,"w","Write a file") {
  4776. /* w: write file */
  4777. if (argc > 1) {
  4778. write_file(argv[1]);
  4779. } else {
  4780. write_file(env->file_name);
  4781. }
  4782. return 0;
  4783. }
  4784. BIM_COMMAND(wq,"wq","Write and close buffer") {
  4785. write_file(env->file_name);
  4786. close_buffer();
  4787. return 0;
  4788. }
  4789. BIM_COMMAND(history,"history","Display command history") {
  4790. render_commandline_message(""); /* To clear command line */
  4791. for (int i = COMMAND_HISTORY_MAX; i > 1; --i) {
  4792. if (command_history[i-1]) render_commandline_message("%d:%s\n", i-1, command_history[i-1]);
  4793. }
  4794. render_commandline_message("\n");
  4795. redraw_tabbar();
  4796. redraw_commandline();
  4797. pause_for_key();
  4798. return 0;
  4799. }
  4800. BIM_COMMAND(q,"q","Close buffer") {
  4801. if (left_buffer && left_buffer == right_buffer) {
  4802. unsplit();
  4803. return 0;
  4804. }
  4805. if (env->modified) {
  4806. render_error("No write since last change. Use :q! to force exit.");
  4807. } else {
  4808. close_buffer();
  4809. }
  4810. update_title();
  4811. return 0;
  4812. }
  4813. BIM_COMMAND(qbang,"q!","Force close buffer") {
  4814. close_buffer();
  4815. update_title();
  4816. return 0;
  4817. }
  4818. BIM_COMMAND(qa,"qa","Try to close all buffers") {
  4819. try_quit();
  4820. return 0;
  4821. }
  4822. BIM_ALIAS("qall",qall,qa)
  4823. BIM_COMMAND(qabang,"qa!","Force exit") {
  4824. /* Forcefully exit editor */
  4825. while (buffers_len) {
  4826. buffer_close(buffers[0]);
  4827. }
  4828. quit(NULL);
  4829. return 1; /* doesn't return */
  4830. }
  4831. BIM_COMMAND(tabp,"tabp","Previous tab") {
  4832. previous_tab();
  4833. update_title();
  4834. return 0;
  4835. }
  4836. BIM_COMMAND(tabn,"tabn","Next tab") {
  4837. next_tab();
  4838. update_title();
  4839. return 0;
  4840. }
  4841. BIM_COMMAND(tabindicator,"tabindicator","Set the tab indicator") {
  4842. if (argc < 2) {
  4843. render_status_message("tabindicator=%s", global_config.tab_indicator);
  4844. return 0;
  4845. }
  4846. if (display_width_of_string(argv[1]) != 1) {
  4847. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4848. return 1;
  4849. }
  4850. if (global_config.tab_indicator) free(global_config.tab_indicator);
  4851. global_config.tab_indicator = strdup(argv[1]);
  4852. return 0;
  4853. }
  4854. BIM_COMMAND(spaceindicator,"spaceindicator","Set the space indicator") {
  4855. if (argc < 2) {
  4856. render_status_message("spaceindicator=%s", global_config.space_indicator);
  4857. return 0;
  4858. }
  4859. if (display_width_of_string(argv[1]) != 1) {
  4860. render_error("Can't set '%s' as indicator, must be one cell wide.", argv[1]);
  4861. return 1;
  4862. }
  4863. if (global_config.space_indicator) free(global_config.space_indicator);
  4864. global_config.space_indicator = strdup(argv[1]);
  4865. return 0;
  4866. }
  4867. BIM_COMMAND(global_sgr,"global.sgr_mouse","Enable SGR mouse escapes") {
  4868. if (argc < 2) {
  4869. render_status_message("global.sgr_mouse=%d", global_config.use_sgr_mouse);
  4870. } else {
  4871. mouse_disable();
  4872. global_config.use_sgr_mouse = !!atoi(argv[1]);
  4873. mouse_enable();
  4874. }
  4875. return 0;
  4876. }
  4877. BIM_COMMAND(global_git,"global.git","Show or change the default status of git integration") {
  4878. if (argc < 2) {
  4879. render_status_message("global.git=%d", global_config.check_git);
  4880. } else {
  4881. global_config.check_git = !!atoi(argv[1]);
  4882. }
  4883. return 0;
  4884. }
  4885. BIM_COMMAND(git,"git","Show or change status of git integration") {
  4886. if (!env) {
  4887. render_error("requires environment (did you mean global.git?)");
  4888. return 1;
  4889. }
  4890. if (argc < 2) {
  4891. render_status_message("git=%d", env->checkgitstatusonwrite);
  4892. } else {
  4893. env->checkgitstatusonwrite = !!atoi(argv[1]);
  4894. if (env->checkgitstatusonwrite && !env->modified && env->file_name) {
  4895. git_examine(env->file_name);
  4896. redraw_text();
  4897. }
  4898. }
  4899. return 0;
  4900. }
  4901. BIM_COMMAND(colorgutter,"colorgutter","Show or change status of gutter colorization for unsaved modifications") {
  4902. if (argc < 2) {
  4903. render_status_message("colorgutter=%d", global_config.color_gutter);
  4904. } else {
  4905. global_config.color_gutter = !!atoi(argv[1]);
  4906. redraw_text();
  4907. }
  4908. return 0;
  4909. }
  4910. BIM_COMMAND(indent,"indent","Enable smart indentation") {
  4911. env->indent = 1;
  4912. redraw_statusbar();
  4913. return 0;
  4914. }
  4915. BIM_COMMAND(noindent,"noindent","Disable smrat indentation") {
  4916. env->indent = 0;
  4917. redraw_statusbar();
  4918. return 0;
  4919. }
  4920. /* TODO: global.maxcolumn */
  4921. BIM_COMMAND(maxcolumn,"maxcolumn","Highlight past the given column to indicate maximum desired line length") {
  4922. if (argc < 2) {
  4923. render_status_message("maxcolumn=%d",env->maxcolumn);
  4924. return 0;
  4925. }
  4926. env->maxcolumn = atoi(argv[1]);
  4927. redraw_text();
  4928. return 0;
  4929. }
  4930. BIM_COMMAND(cursorcolumn,"cursorcolumn","Show the visual column offset of the cursor.") {
  4931. render_status_message("cursorcolumn=%d", env->preferred_column);
  4932. return 0;
  4933. }
  4934. BIM_COMMAND(noh,"noh","Clear search term") {
  4935. if (global_config.search) {
  4936. free(global_config.search);
  4937. global_config.search = NULL;
  4938. for (int i = 0; i < env->line_count; ++i) {
  4939. recalculate_syntax(env->lines[i],i);
  4940. }
  4941. redraw_text();
  4942. }
  4943. return 0;
  4944. }
  4945. BIM_COMMAND(help,"help","Show help text.") {
  4946. if (argc < 2) {
  4947. render_commandline_message(""); /* To clear command line */
  4948. render_commandline_message("\n");
  4949. render_commandline_message(" \033[1mbim - a text editor \033[22m\n");
  4950. render_commandline_message("\n");
  4951. render_commandline_message(" Available commands:\n");
  4952. 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");
  4953. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  4954. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  4955. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  4956. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  4957. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  4958. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  4959. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  4960. render_commandline_message("\n");
  4961. render_commandline_message(" Bim %s%s\n", BIM_VERSION, BIM_BUILD_DATE);
  4962. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  4963. render_commandline_message("\n");
  4964. } else {
  4965. int found = 0;
  4966. for (struct command_def * c = regular_commands; !found && regular_commands && c->name; ++c) {
  4967. if (!strcmp(c->name, argv[1])) {
  4968. render_commandline_message(""); /* To clear command line */
  4969. render_commandline_message("Help description for `%s`:\n", c->name);
  4970. render_commandline_message(" %s\n", c->description);
  4971. found = 1;
  4972. break;
  4973. }
  4974. }
  4975. for (struct command_def * c = prefix_commands; !found && prefix_commands && c->name; ++c) {
  4976. if (!strcmp(c->name, argv[1])) {
  4977. render_commandline_message(""); /* To clear command line */
  4978. render_commandline_message("Help description for `%s`:\n", c->name);
  4979. render_commandline_message(" %s\n", c->description);
  4980. found = 1;
  4981. break;
  4982. }
  4983. }
  4984. if (!found) {
  4985. render_error("Unknown command: %s", argv[1]);
  4986. return 1;
  4987. }
  4988. }
  4989. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  4990. redraw_tabbar();
  4991. redraw_commandline();
  4992. /* Wait for a character so we can redraw the screen before continuing */
  4993. pause_for_key();
  4994. return 0;
  4995. }
  4996. BIM_COMMAND(version,"version","Show version information.") {
  4997. render_status_message("Bim %s%s", BIM_VERSION, BIM_BUILD_DATE);
  4998. return 0;
  4999. }
  5000. void load_colorscheme_script(const char * name) {
  5001. static char name_copy[512];
  5002. char tmp[1024];
  5003. snprintf(tmp, 1023, "theme:%s", name);
  5004. if (!run_function(tmp)) {
  5005. sprintf(name_copy, "%s", name);
  5006. current_theme = name_copy;
  5007. }
  5008. }
  5009. BIM_COMMAND(theme,"theme","Set color theme") {
  5010. if (argc < 2) {
  5011. render_status_message("theme=%s", current_theme);
  5012. } else {
  5013. for (struct theme_def * d = themes; themes && d->name; ++d) {
  5014. if (!strcmp(argv[1], d->name)) {
  5015. d->load(d->name);
  5016. redraw_all();
  5017. return 0;
  5018. }
  5019. }
  5020. }
  5021. return 0;
  5022. }
  5023. BIM_ALIAS("colorscheme",colorscheme,theme)
  5024. BIM_COMMAND(splitpercent,"splitpercent","Display or change view split") {
  5025. if (argc < 2) {
  5026. render_status_message("splitpercent=%d", global_config.split_percent);
  5027. return 0;
  5028. } else {
  5029. global_config.split_percent = atoi(argv[1]);
  5030. if (left_buffer) {
  5031. update_split_size();
  5032. redraw_all();
  5033. }
  5034. }
  5035. return 0;
  5036. }
  5037. BIM_COMMAND(split,"split","Split the current view.") {
  5038. buffer_t * original = env;
  5039. if (argc > 1) {
  5040. int is_not_number = 0;
  5041. for (char * c = argv[1]; *c; ++c) is_not_number |= !isdigit(*c);
  5042. if (is_not_number) {
  5043. /* Open a file for the new split */
  5044. open_file(argv[1]);
  5045. right_buffer = buffers[buffers_len-1];
  5046. } else {
  5047. /* Use an existing buffer for the new split */
  5048. int other = atoi(argv[1]);
  5049. if (other >= buffers_len || other < 0) {
  5050. render_error("Invalid buffer number: %d", other);
  5051. return 1;
  5052. }
  5053. right_buffer = buffers[other];
  5054. }
  5055. } else {
  5056. /* Use the current buffer for the new split */
  5057. right_buffer = original;
  5058. }
  5059. left_buffer = original;
  5060. update_split_size();
  5061. redraw_all();
  5062. return 0;
  5063. }
  5064. BIM_COMMAND(unsplit,"unsplit","Show only one buffer on screen") {
  5065. unsplit();
  5066. return 0;
  5067. }
  5068. BIM_COMMAND(horizontalscrolling,"horizontalscrolling","Set the horizontal scrolling mode") {
  5069. if (argc < 2) {
  5070. render_status_message("horizontalscrolling=%d", global_config.horizontal_shift_scrolling);
  5071. return 0;
  5072. } else {
  5073. global_config.horizontal_shift_scrolling = !!atoi(argv[1]);
  5074. redraw_all();
  5075. }
  5076. return 0;
  5077. }
  5078. BIM_COMMAND(syntax,"syntax","Show or set the active syntax highlighter") {
  5079. if (argc < 2) {
  5080. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  5081. } else {
  5082. set_syntax_by_name(argv[1]);
  5083. }
  5084. return 0;
  5085. }
  5086. BIM_COMMAND(recalc,"recalc","Recalculate syntax for the entire file.") {
  5087. for (int i = 0; i < env->line_count; ++i) {
  5088. env->lines[i]->istate = -1;
  5089. }
  5090. env->loading = 1;
  5091. for (int i = 0; i < env->line_count; ++i) {
  5092. recalculate_syntax(env->lines[i],i);
  5093. }
  5094. env->loading = 0;
  5095. redraw_all();
  5096. return 0;
  5097. }
  5098. BIM_COMMAND(tabs,"tabs","Use tabs for indentation") {
  5099. env->tabs = 1;
  5100. redraw_statusbar();
  5101. return 0;
  5102. }
  5103. BIM_COMMAND(spaces,"spaces","Use spaces for indentation") {
  5104. env->tabs = 0;
  5105. redraw_statusbar();
  5106. return 0;
  5107. }
  5108. BIM_COMMAND(tabstop,"tabstop","Show or set the tabstop (width of an indentation unit)") {
  5109. if (argc < 2) {
  5110. render_status_message("tabstop=%d", env->tabstop);
  5111. } else {
  5112. int t = atoi(argv[1]);
  5113. if (t > 0 && t < 32) {
  5114. env->tabstop = t;
  5115. for (int i = 0; i < env->line_count; ++i) {
  5116. recalculate_tabs(env->lines[i]);
  5117. }
  5118. redraw_all();
  5119. } else {
  5120. render_error("Invalid tabstop: %s", argv[1]);
  5121. }
  5122. }
  5123. return 0;
  5124. }
  5125. BIM_COMMAND(clearyear,"clearyank","Clear the yank buffer") {
  5126. if (global_config.yanks) {
  5127. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5128. free(global_config.yanks[i]);
  5129. }
  5130. free(global_config.yanks);
  5131. global_config.yanks = NULL;
  5132. global_config.yank_count = 0;
  5133. redraw_statusbar();
  5134. }
  5135. return 0;
  5136. }
  5137. BIM_COMMAND(padding,"padding","Show or set cursor padding when scrolling vertically") {
  5138. if (argc < 2) {
  5139. render_status_message("padding=%d", global_config.cursor_padding);
  5140. } else {
  5141. global_config.cursor_padding = atoi(argv[1]);
  5142. if (env) {
  5143. place_cursor_actual();
  5144. }
  5145. }
  5146. return 0;
  5147. }
  5148. BIM_COMMAND(smartcase,"smartcase","Show or set the status of the smartcase search option") {
  5149. if (argc < 2) {
  5150. render_status_message("smartcase=%d", global_config.smart_case);
  5151. } else {
  5152. global_config.smart_case = atoi(argv[1]);
  5153. if (env) place_cursor_actual();
  5154. }
  5155. return 0;
  5156. }
  5157. BIM_COMMAND(hlparen,"hlparen","Show or set the configuration option to highlight matching braces") {
  5158. if (argc < 2) {
  5159. render_status_message("hlparen=%d", global_config.highlight_parens);
  5160. } else {
  5161. global_config.highlight_parens = atoi(argv[1]);
  5162. if (env) {
  5163. for (int i = 0; i < env->line_count; ++i) {
  5164. recalculate_syntax(env->lines[i],i);
  5165. }
  5166. redraw_text();
  5167. place_cursor_actual();
  5168. }
  5169. }
  5170. return 0;
  5171. }
  5172. BIM_COMMAND(hlcurrent,"hlcurrent","Show or set the configuration option to highlight the current line") {
  5173. if (argc < 2) {
  5174. render_status_message("hlcurrent=%d", global_config.highlight_current_line);
  5175. } else {
  5176. global_config.highlight_current_line = atoi(argv[1]);
  5177. if (env) {
  5178. if (!global_config.highlight_current_line) {
  5179. for (int i = 0; i < env->line_count; ++i) {
  5180. env->lines[i]->is_current = 0;
  5181. }
  5182. }
  5183. redraw_text();
  5184. place_cursor_actual();
  5185. }
  5186. }
  5187. return 0;
  5188. }
  5189. BIM_COMMAND(crnl,"crnl","Show or set the line ending mode") {
  5190. if (argc < 2) {
  5191. render_status_message("crnl=%d", env->crnl);
  5192. } else {
  5193. env->crnl = !!atoi(argv[1]);
  5194. redraw_statusbar();
  5195. }
  5196. return 0;
  5197. }
  5198. BIM_COMMAND(global_numbers,"global.numbers","Set whether numbers are displayed by default") {
  5199. if (argc < 2) {
  5200. render_status_message("global.numbers=%d", global_config.numbers);
  5201. } else {
  5202. global_config.numbers = !!atoi(argv[1]);
  5203. redraw_all();
  5204. }
  5205. return 0;
  5206. }
  5207. BIM_COMMAND(global_statusbar,"global.statusbar","Show or set whether to display the statusbar") {
  5208. if (argc < 2) {
  5209. render_status_message("global.statusbar=%d",!global_config.hide_statusbar);
  5210. } else {
  5211. global_config.hide_statusbar = !atoi(argv[1]);
  5212. global_config.bottom_size = global_config.hide_statusbar ? 1 : 2;
  5213. redraw_all();
  5214. }
  5215. return 0;
  5216. }
  5217. BIM_COMMAND(smartcomplete,"smartcomplete","Enable autocompletion while typing") {
  5218. if (argc < 2) {
  5219. render_status_message("smartcomplete=%d",global_config.smart_complete);
  5220. } else {
  5221. global_config.smart_complete = !!atoi(argv[1]);
  5222. }
  5223. return 0;
  5224. }
  5225. BIM_COMMAND(global_autohide_tabs,"global.autohidetabs","Whether to show the tab bar when there is only one tab") {
  5226. if (argc < 2) {
  5227. render_status_message("global.autohidetabs=%d", global_config.autohide_tabs);
  5228. } else {
  5229. global_config.autohide_tabs = !!atoi(argv[1]);
  5230. global_config.tabs_visible = (!global_config.autohide_tabs) || (buffers_len > 1);
  5231. redraw_all();
  5232. }
  5233. return 0;
  5234. }
  5235. BIM_COMMAND(numbers,"numbers","Show or set the display of line numbers") {
  5236. if (argc < 2) {
  5237. render_status_message("numbers=%d", env->numbers);
  5238. } else {
  5239. env->numbers = !!atoi(argv[1]);
  5240. redraw_all();
  5241. }
  5242. return 0;
  5243. }
  5244. BIM_COMMAND(relativenumbers,"relativenumbers","Show or set the display of relative line numbers") {
  5245. if (argc < 2) {
  5246. render_status_message("relativenumber=%d", global_config.relative_lines);
  5247. } else {
  5248. global_config.relative_lines = atoi(argv[1]);
  5249. if (env) {
  5250. if (!global_config.relative_lines) {
  5251. for (int i = 0; i < env->line_count; ++i) {
  5252. env->lines[i]->is_current = 0;
  5253. }
  5254. }
  5255. redraw_text();
  5256. place_cursor_actual();
  5257. }
  5258. }
  5259. return 0;
  5260. }
  5261. BIM_COMMAND(buffers,"buffers","Show the open buffers") {
  5262. for (int i = 0; i < buffers_len; ++i) {
  5263. render_commandline_message("%d: %s\n", i, buffers[i]->file_name ? buffers[i]->file_name : "(no name)");
  5264. }
  5265. redraw_tabbar();
  5266. redraw_commandline();
  5267. pause_for_key();
  5268. return 0;
  5269. }
  5270. BIM_COMMAND(keyname,"keyname","Press and key and get its name.") {
  5271. int c;
  5272. render_commandline_message("(press a key)");
  5273. while ((c = bim_getkey(200)) == KEY_TIMEOUT);
  5274. render_commandline_message("%d = %s", c, name_from_key(c));
  5275. return 0;
  5276. }
  5277. /**
  5278. * Process a user command.
  5279. */
  5280. int process_command(char * cmd) {
  5281. if (*cmd == '#') return 0;
  5282. /* First, check prefix commands */
  5283. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5284. if (strstr(cmd, c->name) == cmd &&
  5285. (!isalpha(cmd[strlen(c->name)]) || !isalpha(cmd[0]))) {
  5286. return c->command(cmd, 0, NULL);
  5287. }
  5288. }
  5289. char * argv[3] = {NULL, NULL, NULL};
  5290. int argc = !!(*cmd);
  5291. char cmd_name[512] = {0};
  5292. for (char * c = cmd; *c; ++c) {
  5293. if (c-cmd == 511) break;
  5294. if (*c == ' ') {
  5295. cmd_name[c-cmd] = '\0';
  5296. argv[1] = c+1;
  5297. if (*argv[1]) argc++;
  5298. break;
  5299. }
  5300. cmd_name[c-cmd] = *c;
  5301. }
  5302. argv[0] = cmd_name;
  5303. argv[argc] = NULL;
  5304. if (argc < 1) {
  5305. /* no op */
  5306. return 0;
  5307. }
  5308. /* Now check regular commands */
  5309. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5310. if (!strcmp(argv[0], c->name)) {
  5311. return c->command(cmd, argc, argv);
  5312. }
  5313. }
  5314. global_config.break_from_selection = 1;
  5315. if (argv[0][0] == '-' && isdigit(argv[0][1])) {
  5316. goto_line(env->line_no-atoi(&argv[0][1]));
  5317. return 0;
  5318. } else if (argv[0][0] == '+' && isdigit(argv[0][1])) {
  5319. goto_line(env->line_no+atoi(&argv[0][1]));
  5320. return 0;
  5321. } else if (isdigit(*argv[0])) {
  5322. goto_line(atoi(argv[0]));
  5323. return 0;
  5324. } else {
  5325. render_error("Not an editor command: %s", argv[0]);
  5326. return 1;
  5327. }
  5328. }
  5329. /**
  5330. * Wrap strcmp for use with qsort.
  5331. */
  5332. int compare_str(const void * a, const void * b) {
  5333. return strcmp(*(const char **)a, *(const char **)b);
  5334. }
  5335. /**
  5336. * List of file extensions to ignore when tab completing.
  5337. */
  5338. const char * tab_complete_ignore[] = {".o",NULL};
  5339. /**
  5340. * Tab completion for command mode.
  5341. */
  5342. void command_tab_complete(char * buffer) {
  5343. /* Figure out which argument this is and where it starts */
  5344. int arg = 0;
  5345. char * buf = strdup(buffer);
  5346. char * b = buf;
  5347. char * args[32];
  5348. int candidate_count= 0;
  5349. int candidate_space = 4;
  5350. char ** candidates = malloc(sizeof(char*)*candidate_space);
  5351. /* Accept whitespace before first argument */
  5352. while (*b == ' ') b++;
  5353. char * start = b;
  5354. args[0] = start;
  5355. while (*b && *b != ' ') b++;
  5356. while (*b) {
  5357. while (*b == ' ') {
  5358. *b = '\0';
  5359. b++;
  5360. }
  5361. start = b;
  5362. arg++;
  5363. args[arg] = start;
  5364. break;
  5365. }
  5366. /**
  5367. * Check a possible candidate and add it to the
  5368. * candidates list, expanding as necessary,
  5369. * if it matches for the current argument.
  5370. */
  5371. #define add_candidate(candidate) \
  5372. do { \
  5373. char * _arg = args[arg]; \
  5374. int r = strncmp(_arg, candidate, strlen(_arg)); \
  5375. if (!r) { \
  5376. if (candidate_count == candidate_space) { \
  5377. candidate_space *= 2; \
  5378. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  5379. } \
  5380. candidates[candidate_count] = strdup(candidate); \
  5381. candidate_count++; \
  5382. } \
  5383. } while (0)
  5384. int _candidates_are_files = 0;
  5385. if (arg == 0 || (arg == 1 && !strcmp(args[0], "help"))) {
  5386. /* Complete command names */
  5387. for (struct command_def * c = regular_commands; regular_commands && c->name; ++c) {
  5388. add_candidate(c->name);
  5389. }
  5390. for (struct command_def * c = prefix_commands; prefix_commands && c->name; ++c) {
  5391. add_candidate(c->name);
  5392. }
  5393. goto _accept_candidate;
  5394. }
  5395. if (arg == 1 && !strcmp(args[0], "syntax")) {
  5396. /* Complete syntax options */
  5397. add_candidate("none");
  5398. for (struct syntax_definition * s = syntaxes; syntaxes && s->name; ++s) {
  5399. add_candidate(s->name);
  5400. }
  5401. goto _accept_candidate;
  5402. }
  5403. if (arg == 1 && (!strcmp(args[0], "theme") || !strcmp(args[0], "colorscheme"))) {
  5404. /* Complete color theme names */
  5405. for (struct theme_def * s = themes; themes && s->name; ++s) {
  5406. add_candidate(s->name);
  5407. }
  5408. goto _accept_candidate;
  5409. }
  5410. if (arg == 1 && (!strcmp(args[0], "setcolor"))) {
  5411. for (struct ColorName * c = color_names; c->name; ++c) {
  5412. add_candidate(c->name);
  5413. }
  5414. goto _accept_candidate;
  5415. }
  5416. if (arg == 1 && (!strcmp(args[0], "action"))) {
  5417. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5418. add_candidate(a->name);
  5419. }
  5420. goto _accept_candidate;
  5421. }
  5422. if (arg == 1 && (!strcmp(args[0], "call") || !strcmp(args[0], "trycall") || !strcmp(args[0], "showfunction"))) {
  5423. for (int i = 0; i < flex_user_functions_count; ++i) {
  5424. add_candidate(user_functions[i]->command);
  5425. }
  5426. goto _accept_candidate;
  5427. }
  5428. if (arg == 1 && (!strcmp(args[0], "mapkey"))) {
  5429. for (int i = 0; args[arg][i]; ++i) {
  5430. if (args[arg][i] == ' ') {
  5431. while (args[arg][i] == ' ') {
  5432. args[arg][i] = '\0';
  5433. i++;
  5434. }
  5435. start = &args[arg][i];
  5436. arg++;
  5437. args[arg] = start;
  5438. i = 0;
  5439. if (arg == 32) {
  5440. arg = 31;
  5441. break;
  5442. }
  5443. }
  5444. }
  5445. if (arg == 1) {
  5446. for (struct mode_names * m = mode_names; m->name; ++m) {
  5447. add_candidate(m->name);
  5448. }
  5449. } else if (arg == 2) {
  5450. for (unsigned int i = 0; i < sizeof(KeyNames)/sizeof(KeyNames[0]); ++i) {
  5451. add_candidate(KeyNames[i].name);
  5452. }
  5453. } else if (arg == 3) {
  5454. for (struct action_def * a = mappable_actions; a->name; ++a) {
  5455. add_candidate(a->name);
  5456. }
  5457. add_candidate("none");
  5458. } else if (arg == 4) {
  5459. for (char * c = "racnwmb"; *c; ++c) {
  5460. char tmp[] = {*c,'\0'};
  5461. add_candidate(tmp);
  5462. }
  5463. }
  5464. goto _accept_candidate;
  5465. }
  5466. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew") ||
  5467. !strcmp(args[0],"split") || !strcmp(args[0],"w") || !strcmp(args[0],"runscript") ||
  5468. !strcmp(args[0],"rundir") || args[0][0] == '!')) {
  5469. /* Complete file paths */
  5470. /* First, find the deepest directory match */
  5471. char * tmp = strdup(args[arg]);
  5472. char * last_slash = strrchr(tmp, '/');
  5473. DIR * dirp;
  5474. if (last_slash) {
  5475. *last_slash = '\0';
  5476. if (last_slash == tmp) {
  5477. /* Started with slash, and it was the only slash */
  5478. dirp = opendir("/");
  5479. } else {
  5480. char * home;
  5481. if (*tmp == '~' && (home = getenv("HOME"))) {
  5482. char * t = malloc(strlen(tmp) + strlen(home) + 4);
  5483. sprintf(t, "%s%s",home,tmp+1);
  5484. dirp = opendir(t);
  5485. free(t);
  5486. } else {
  5487. dirp = opendir(tmp);
  5488. }
  5489. }
  5490. } else {
  5491. /* No directory match, completing from current directory */
  5492. dirp = opendir(".");
  5493. tmp[0] = '\0';
  5494. }
  5495. if (!dirp) {
  5496. /* Directory match doesn't exist, no candidates to populate */
  5497. free(tmp);
  5498. goto done;
  5499. }
  5500. _candidates_are_files = 1;
  5501. struct dirent * ent = readdir(dirp);
  5502. while (ent != NULL) {
  5503. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  5504. struct stat statbuf;
  5505. /* Figure out if this file is a directory */
  5506. if (last_slash) {
  5507. char * x;
  5508. char * home;
  5509. if (tmp[0] == '~' && (home = getenv("HOME"))) {
  5510. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1);
  5511. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1 + strlen(home) + 1, "%s%s/%s",home,tmp+1,ent->d_name);
  5512. } else {
  5513. x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  5514. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  5515. }
  5516. stat(x, &statbuf);
  5517. free(x);
  5518. } else {
  5519. stat(ent->d_name, &statbuf);
  5520. }
  5521. /* Build the complete argument name to tab complete */
  5522. char s[1024] = {0};
  5523. if (last_slash == tmp) {
  5524. strcat(s,"/");
  5525. } else if (*tmp) {
  5526. strcat(s,tmp);
  5527. strcat(s,"/");
  5528. }
  5529. strcat(s,ent->d_name);
  5530. /*
  5531. * If it is a directory, add a / to the end so the next completion
  5532. * attempt will complete the directory's contents.
  5533. */
  5534. if (S_ISDIR(statbuf.st_mode)) {
  5535. strcat(s,"/");
  5536. }
  5537. int skip = 0;
  5538. for (const char ** c = tab_complete_ignore; *c; ++c) {
  5539. if (str_ends_with(s, *c)) {
  5540. skip = 1;
  5541. break;
  5542. }
  5543. }
  5544. if (!skip) {
  5545. add_candidate(s);
  5546. }
  5547. }
  5548. ent = readdir(dirp);
  5549. }
  5550. closedir(dirp);
  5551. free(tmp);
  5552. goto _accept_candidate;
  5553. }
  5554. _accept_candidate:
  5555. if (candidate_count == 0) {
  5556. redraw_statusbar();
  5557. goto done;
  5558. }
  5559. if (candidate_count == 1) {
  5560. /* Only one completion possibility */
  5561. redraw_statusbar();
  5562. /* Fill out the rest of the command */
  5563. char * cstart = (buffer) + (start - buf);
  5564. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  5565. *cstart = candidates[0][i];
  5566. cstart++;
  5567. }
  5568. *cstart = '\0';
  5569. } else {
  5570. /* Sort candidates */
  5571. qsort(candidates, candidate_count, sizeof(candidates[0]), compare_str);
  5572. /* Print candidates in status bar */
  5573. char * tmp = malloc(global_config.term_width+1);
  5574. memset(tmp, 0, global_config.term_width+1);
  5575. int offset = 0;
  5576. for (int i = 0; i < candidate_count; ++i) {
  5577. char * printed_candidate = candidates[i];
  5578. if (_candidates_are_files) {
  5579. for (char * c = printed_candidate; *c; ++c) {
  5580. if (c[0] == '/' && c[1] != '\0') {
  5581. printed_candidate = c+1;
  5582. }
  5583. }
  5584. }
  5585. if (offset + 1 + (signed)strlen(printed_candidate) > global_config.term_width - 5) {
  5586. strcat(tmp, "...");
  5587. break;
  5588. }
  5589. if (offset > 0) {
  5590. strcat(tmp, " ");
  5591. offset++;
  5592. }
  5593. strcat(tmp, printed_candidate);
  5594. offset += strlen(printed_candidate);
  5595. }
  5596. render_status_message("%s", tmp);
  5597. free(tmp);
  5598. /* Complete to longest common substring */
  5599. char * cstart = (buffer) + (start - buf);
  5600. for (int i = 0; i < 1023 /* max length of command */; i++) {
  5601. for (int j = 1; j < candidate_count; ++j) {
  5602. if (candidates[0][i] != candidates[j][i]) goto _reject;
  5603. }
  5604. *cstart = candidates[0][i];
  5605. cstart++;
  5606. }
  5607. /* End of longest common substring */
  5608. _reject:
  5609. *cstart = '\0';
  5610. /* Just make sure the buffer doesn't end on an incomplete multibyte sequence */
  5611. if (start > buf) { /* Start point needs to be something other than first byte */
  5612. char * tmp = cstart - 1;
  5613. if ((*tmp & 0xC0) == 0x80) {
  5614. /* Count back until we find the start byte and make sure we have the right number */
  5615. int count = 1;
  5616. int x = 0;
  5617. while (tmp >= start) {
  5618. x++;
  5619. tmp--;
  5620. if ((*tmp & 0xC0) == 0x80) {
  5621. count++;
  5622. } else if ((*tmp & 0xC0) == 0xC0) {
  5623. /* How many should we have? */
  5624. int i = 1;
  5625. int j = *tmp;
  5626. while (j & 0x20) {
  5627. i += 1;
  5628. j <<= 1;
  5629. }
  5630. if (count != i) {
  5631. *tmp = '\0';
  5632. break;
  5633. }
  5634. break;
  5635. } else {
  5636. /* This isn't right, we had a bad multibyte sequence? Or someone is typing Latin-1. */
  5637. tmp++;
  5638. *tmp = '\0';
  5639. break;
  5640. }
  5641. }
  5642. } else if ((*tmp & 0xC0) == 0xC0) {
  5643. *tmp = '\0';
  5644. }
  5645. }
  5646. }
  5647. /* Free candidates */
  5648. for (int i = 0; i < candidate_count; ++i) {
  5649. free(candidates[i]);
  5650. }
  5651. done:
  5652. free(candidates);
  5653. free(buf);
  5654. }
  5655. /**
  5656. * Macros for use in command mode.
  5657. */
  5658. #define _syn_command() do { env->syntax = global_config.command_syn; } while (0)
  5659. #define _syn_restore() do { env->syntax = global_config.command_syn_back; } while (0)
  5660. #define _restore_history(point) do { \
  5661. unsigned char * t = command_history[point]; \
  5662. global_config.command_col_no = 1; \
  5663. global_config.command_buffer->actual = 0; \
  5664. _syn_command(); \
  5665. uint32_t state = 0; \
  5666. uint32_t c = 0; \
  5667. while (*t) { \
  5668. if (!decode(&state, &c, *t)) { \
  5669. char_t _c = {codepoint_width(c), 0, c}; \
  5670. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1); \
  5671. global_config.command_col_no++; \
  5672. } else if (state == UTF8_REJECT) state = 0; \
  5673. t++; \
  5674. } \
  5675. _syn_restore(); \
  5676. } while (0)
  5677. /**
  5678. * Draw the command buffer and any prefix.
  5679. */
  5680. void render_command_input_buffer(void) {
  5681. if (!global_config.command_buffer) return;
  5682. /* Place the cursor at the bottom of the screen */
  5683. place_cursor(1, global_config.term_height);
  5684. paint_line(COLOR_BG);
  5685. set_colors(COLOR_ALT_FG, COLOR_BG);
  5686. /* If there's a mode name to render, draw it first */
  5687. int _left_gutter = 0;
  5688. if (env->mode == MODE_LINE_SELECTION) {
  5689. _left_gutter = printf("(LINE %d:%d)",
  5690. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5691. (env->start_line < env->line_no) ? env->line_no : env->start_line);
  5692. } else if (env->mode == MODE_COL_SELECTION) {
  5693. _left_gutter = printf("(COL %d:%d %d)",
  5694. (env->start_line < env->line_no) ? env->start_line : env->line_no,
  5695. (env->start_line < env->line_no) ? env->line_no : env->start_line,
  5696. (env->sel_col));
  5697. } else if (env->mode == MODE_CHAR_SELECTION) {
  5698. _left_gutter = printf("(CHAR)");
  5699. }
  5700. /* Figure out the cursor position and adjust the offset if necessary */
  5701. int x = 2 + _left_gutter - global_config.command_offset;
  5702. for (int i = 0; i < global_config.command_col_no - 1; ++i) {
  5703. char_t * c = &global_config.command_buffer->text[i];
  5704. x += c->display_width;
  5705. }
  5706. if (x > global_config.term_width - 1) {
  5707. int diff = x - (global_config.term_width - 1);
  5708. global_config.command_offset += diff;
  5709. x -= diff;
  5710. }
  5711. if (x < 2 + _left_gutter) {
  5712. int diff = (2 + _left_gutter) - x;
  5713. global_config.command_offset -= diff;
  5714. x += diff;
  5715. }
  5716. /* If the input buffer is horizontally shifted because it's too long, indicate that. */
  5717. if (global_config.command_offset) {
  5718. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  5719. printf("<");
  5720. } else {
  5721. /* Otherwise indicate buffer mode (search / ?, or command :) */
  5722. set_colors(COLOR_FG, COLOR_BG);
  5723. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5724. printf(global_config.search_direction == 0 ? "?" : "/");
  5725. } else {
  5726. printf(":");
  5727. }
  5728. }
  5729. /* Render the buffer */
  5730. render_line(global_config.command_buffer, global_config.term_width-1-_left_gutter, global_config.command_offset, -1);
  5731. /* Place and display the cursor */
  5732. place_cursor(x, global_config.term_height);
  5733. show_cursor();
  5734. }
  5735. BIM_ACTION(command_discard, 0,
  5736. "Discard the input buffer and cancel command or search."
  5737. )(void) {
  5738. free(global_config.command_buffer);
  5739. global_config.command_buffer = NULL;
  5740. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  5741. env->line_no = global_config.prev_line;
  5742. env->col_no = global_config.prev_col;
  5743. /* Unhighlight search matches */
  5744. for (int i = 0; i < env->line_count; ++i) {
  5745. for (int j = 0; j < env->lines[i]->actual; ++j) {
  5746. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  5747. }
  5748. rehighlight_search(env->lines[i]);
  5749. }
  5750. }
  5751. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5752. redraw_all();
  5753. /* TODO exit some other modes? */
  5754. }
  5755. BIM_ACTION(enter_command, 0,
  5756. "Enter command input mode."
  5757. )(void) {
  5758. global_config.overlay_mode = OVERLAY_MODE_COMMAND;
  5759. global_config.command_offset = 0;
  5760. global_config.command_col_no = 1;
  5761. if (global_config.command_buffer) {
  5762. free(global_config.command_buffer);
  5763. }
  5764. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  5765. global_config.command_buffer->available = 32;
  5766. global_config.command_syn_back = env->syntax;
  5767. global_config.command_syn = find_syntax_calculator("bimcmd");
  5768. global_config.history_point = -1;
  5769. render_command_input_buffer();
  5770. }
  5771. BIM_ACTION(command_accept, 0,
  5772. "Accept the command input and run the requested command."
  5773. )(void) {
  5774. /* Convert command buffer to UTF-8 char-array string */
  5775. size_t size = 0;
  5776. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5777. char tmp[8] = {0};
  5778. size += to_eight(global_config.command_buffer->text[i].codepoint, tmp);
  5779. }
  5780. char * tmp = malloc(size + 8); /* for overflow from to_eight */
  5781. char * t = tmp;
  5782. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  5783. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5784. }
  5785. *t = '\0';
  5786. /* Free the original editing buffer */
  5787. free(global_config.command_buffer);
  5788. global_config.command_buffer = NULL;
  5789. /* Run the converted command */
  5790. global_config.break_from_selection = 0;
  5791. insert_command_history(tmp);
  5792. process_command(tmp);
  5793. free(tmp);
  5794. if (!global_config.break_from_selection && env->mode != MODE_DIRECTORY_BROWSE) {
  5795. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) {
  5796. recalculate_selected_lines();
  5797. }
  5798. env->mode = MODE_NORMAL;
  5799. }
  5800. /* Leave command mode */
  5801. global_config.overlay_mode = OVERLAY_MODE_NONE;
  5802. }
  5803. BIM_ACTION(command_word_delete, 0,
  5804. "Delete the previous word from the input buffer."
  5805. )(void) {
  5806. _syn_command();
  5807. while (global_config.command_col_no > 1 &&
  5808. (global_config.command_buffer->text[global_config.command_col_no-2].codepoint == ' ' ||
  5809. global_config.command_buffer->text[global_config.command_col_no-2].codepoint == '/')) {
  5810. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5811. global_config.command_col_no--;
  5812. }
  5813. while (global_config.command_col_no > 1 &&
  5814. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != ' ' &&
  5815. global_config.command_buffer->text[global_config.command_col_no-2].codepoint != '/') {
  5816. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5817. global_config.command_col_no--;
  5818. }
  5819. _syn_restore();
  5820. }
  5821. BIM_ACTION(command_tab_complete_buffer, 0,
  5822. "Complete command names and arguments in the input buffer."
  5823. )(void) {
  5824. /* command_tab_complete should probably just be adjusted to deal with the buffer... */
  5825. char * tmp = calloc(1024,1);
  5826. char * t = tmp;
  5827. for (int i = 0; i < global_config.command_col_no-1; ++i) {
  5828. t += to_eight(global_config.command_buffer->text[i].codepoint, t);
  5829. }
  5830. *t = '\0';
  5831. _syn_command();
  5832. while (global_config.command_col_no > 1) {
  5833. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5834. global_config.command_col_no--;
  5835. }
  5836. _syn_restore();
  5837. command_tab_complete(tmp);
  5838. _syn_command();
  5839. uint32_t state = 0, c= 0;
  5840. t = tmp;
  5841. while (*t) {
  5842. if (!decode(&state, &c, *t)) {
  5843. char_t _c = {codepoint_width(c), 0, c};
  5844. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5845. global_config.command_col_no++;
  5846. }
  5847. t++;
  5848. }
  5849. _syn_restore();
  5850. free(tmp);
  5851. }
  5852. BIM_ACTION(command_backspace, 0,
  5853. "Erase the character before the cursor in the input buffer."
  5854. )(void) {
  5855. if (global_config.command_col_no <= 1) {
  5856. if (global_config.command_buffer->actual == 0) {
  5857. command_discard();
  5858. }
  5859. return;
  5860. }
  5861. _syn_command();
  5862. line_delete(global_config.command_buffer, global_config.command_col_no - 1, -1);
  5863. _syn_restore();
  5864. global_config.command_col_no--;
  5865. global_config.command_offset = 0;
  5866. }
  5867. BIM_ACTION(command_scroll_history, ARG_IS_CUSTOM,
  5868. "Scroll through command input history."
  5869. )(int direction) {
  5870. if (direction == -1) {
  5871. if (command_history[global_config.history_point+1]) {
  5872. _restore_history(global_config.history_point+1);
  5873. global_config.history_point++;
  5874. }
  5875. } else {
  5876. if (global_config.history_point > 0) {
  5877. global_config.history_point--;
  5878. _restore_history(global_config.history_point);
  5879. } else {
  5880. global_config.history_point = -1;
  5881. global_config.command_col_no = 1;
  5882. global_config.command_buffer->actual = 0;
  5883. }
  5884. }
  5885. }
  5886. BIM_ACTION(command_word_left, 0,
  5887. "Move to the start of the previous word in the input buffer."
  5888. )(void) {
  5889. if (global_config.command_col_no > 1) {
  5890. do {
  5891. global_config.command_col_no--;
  5892. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5893. if (global_config.command_col_no == 1) return;
  5894. do {
  5895. global_config.command_col_no--;
  5896. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no > 1);
  5897. if (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no < global_config.command_buffer->actual) global_config.command_col_no++;
  5898. }
  5899. }
  5900. BIM_ACTION(command_word_right, 0,
  5901. "Move to the start of the next word in the input buffer."
  5902. )(void) {
  5903. if (global_config.command_col_no < global_config.command_buffer->actual) {
  5904. do {
  5905. global_config.command_col_no++;
  5906. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5907. } while (!isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5908. do {
  5909. global_config.command_col_no++;
  5910. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; break; }
  5911. } while (isspace(global_config.command_buffer->text[global_config.command_col_no-1].codepoint) && global_config.command_col_no <= global_config.command_buffer->actual);
  5912. if (global_config.command_col_no > global_config.command_buffer->actual) { global_config.command_col_no = global_config.command_buffer->actual+1; }
  5913. }
  5914. }
  5915. BIM_ACTION(command_cursor_left, 0,
  5916. "Move the cursor one character left in the input buffer."
  5917. )(void) {
  5918. if (global_config.command_col_no > 1) global_config.command_col_no--;
  5919. }
  5920. BIM_ACTION(command_cursor_right, 0,
  5921. "Move the cursor one character right in the input buffer."
  5922. )(void) {
  5923. if (global_config.command_col_no < global_config.command_buffer->actual+1) global_config.command_col_no++;
  5924. }
  5925. BIM_ACTION(command_cursor_home, 0,
  5926. "Move the cursor to the start of the input buffer."
  5927. )(void) {
  5928. global_config.command_col_no = 1;
  5929. }
  5930. BIM_ACTION(command_cursor_end, 0,
  5931. "Move the cursor to the end of the input buffer."
  5932. )(void) {
  5933. global_config.command_col_no = global_config.command_buffer->actual + 1;
  5934. }
  5935. BIM_ACTION(eat_mouse, 0,
  5936. "(temporary) Read, but ignore mouse input."
  5937. )(void) {
  5938. bim_getch();
  5939. bim_getch();
  5940. bim_getch();
  5941. }
  5942. BIM_ACTION(command_insert_char, ARG_IS_INPUT,
  5943. "Insert one character into the input buffer."
  5944. )(int c) {
  5945. char_t _c = {codepoint_width(c), 0, c};
  5946. _syn_command();
  5947. global_config.command_buffer = line_insert(global_config.command_buffer, _c, global_config.command_col_no - 1, -1);
  5948. _syn_restore();
  5949. global_config.command_col_no++;
  5950. }
  5951. /**
  5952. * Determine whether a string should be searched
  5953. * case-sensitive or not based on whether it contains
  5954. * any upper-case letters.
  5955. */
  5956. int smart_case(uint32_t * str) {
  5957. if (!global_config.smart_case) return 0;
  5958. for (uint32_t * s = str; *s; ++s) {
  5959. if (tolower(*s) != (int)*s) {
  5960. return 0;
  5961. }
  5962. }
  5963. return 1;
  5964. }
  5965. /**
  5966. * Search forward from the given cursor position
  5967. * to find a basic search match.
  5968. *
  5969. * This could be more complicated...
  5970. */
  5971. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str, int * matchlen) {
  5972. int col = from_col;
  5973. int ignorecase = smart_case(str);
  5974. for (int i = from_line; i <= env->line_count; ++i) {
  5975. line_t * line = env->lines[i - 1];
  5976. int j = col - 1;
  5977. while (j < line->actual + 1) {
  5978. if (subsearch_matches(line, j, str, ignorecase, matchlen)) {
  5979. *out_line = i;
  5980. *out_col = j + 1;
  5981. return;
  5982. }
  5983. j++;
  5984. }
  5985. col = 0;
  5986. }
  5987. }
  5988. /**
  5989. * Search backwards for matching string.
  5990. */
  5991. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  5992. int col = from_col;
  5993. int ignorecase = smart_case(str);
  5994. for (int i = from_line; i >= 1; --i) {
  5995. line_t * line = env->lines[i-1];
  5996. int j = col - 1;
  5997. while (j > -1) {
  5998. if (subsearch_matches(line, j, str, ignorecase, NULL)) {
  5999. *out_line = i;
  6000. *out_col = j + 1;
  6001. return;
  6002. }
  6003. j--;
  6004. }
  6005. col = (i > 1) ? (env->lines[i-2]->actual + 1) : -1;
  6006. }
  6007. }
  6008. /**
  6009. * Re-mark search matches while editing text.
  6010. * This gets called after recalculate_syntax, so it works as we're typing or
  6011. * whenever syntax calculation would redraw other lines.
  6012. * XXX There's a bunch of code duplication between the (now three) search match functions.
  6013. * and search should be improved to support regex anyway, so this needs to be fixed.
  6014. */
  6015. void rehighlight_search(line_t * line) {
  6016. if (!global_config.search) return;
  6017. int j = 0;
  6018. int ignorecase = smart_case(global_config.search);
  6019. while (j < line->actual) {
  6020. int matchlen = 0;
  6021. if (subsearch_matches(line, j, global_config.search, ignorecase, &matchlen)) {
  6022. for (int i = j; matchlen > 0; ++i, matchlen--) {
  6023. line->text[i].flags |= FLAG_SEARCH;
  6024. }
  6025. }
  6026. j++;
  6027. }
  6028. }
  6029. /**
  6030. * Draw the matched search result.
  6031. */
  6032. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  6033. for (int i = 0; i < env->line_count; ++i) {
  6034. for (int j = 0; j < env->lines[i]->actual; ++j) {
  6035. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  6036. }
  6037. }
  6038. int line = -1, col = -1, _line = 1, _col = 1;
  6039. do {
  6040. int matchlen;
  6041. find_match(_line, _col, &line, &col, buffer, &matchlen);
  6042. if (line != -1) {
  6043. line_t * l = env->lines[line-1];
  6044. for (int i = col; matchlen > 0; ++i, --matchlen) {
  6045. l->text[i-1].flags |= FLAG_SEARCH;
  6046. }
  6047. }
  6048. _line = line;
  6049. _col = col+1;
  6050. line = -1;
  6051. col = -1;
  6052. } while (_line != -1);
  6053. redraw_text();
  6054. place_cursor_actual();
  6055. redraw_statusbar();
  6056. redraw_commandline();
  6057. if (redraw_buffer != -1) {
  6058. printf(redraw_buffer == 1 ? "/" : "?");
  6059. uint32_t * c = buffer;
  6060. while (*c) {
  6061. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  6062. to_eight(*c, tmp);
  6063. printf("%s", tmp);
  6064. c++;
  6065. }
  6066. }
  6067. }
  6068. BIM_ACTION(enter_search, ARG_IS_CUSTOM,
  6069. "Enter search mode."
  6070. )(int direction) {
  6071. global_config.overlay_mode = OVERLAY_MODE_SEARCH;
  6072. global_config.command_offset = 0;
  6073. global_config.command_col_no = 1;
  6074. global_config.prev_line = env->line_no;
  6075. global_config.prev_col = env->col_no;
  6076. global_config.prev_coffset = env->coffset;
  6077. global_config.prev_offset = env->offset;
  6078. global_config.search_direction = direction;
  6079. if (global_config.command_buffer) {
  6080. free(global_config.command_buffer);
  6081. }
  6082. global_config.command_buffer = calloc(sizeof(line_t)+sizeof(char_t)*32,1);
  6083. global_config.command_buffer->available = 32;
  6084. global_config.command_syn_back = env->syntax;
  6085. global_config.command_syn = NULL; /* Disable syntax highlighting in search; maybe use buffer's mode instead? */
  6086. render_command_input_buffer();
  6087. }
  6088. BIM_ACTION(search_accept, 0,
  6089. "Accept the search term and return to the previous mode."
  6090. )(void) {
  6091. /* Store the accepted search */
  6092. if (!global_config.command_buffer->actual) {
  6093. if (global_config.search) {
  6094. search_next();
  6095. }
  6096. goto _finish;
  6097. }
  6098. if (global_config.search) {
  6099. free(global_config.search);
  6100. }
  6101. global_config.search = malloc((global_config.command_buffer->actual + 1) * sizeof(uint32_t));
  6102. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  6103. global_config.search[i] = global_config.command_buffer->text[i].codepoint;
  6104. }
  6105. global_config.search[global_config.command_buffer->actual] = 0;
  6106. _finish:
  6107. /* Free the original editing buffer */
  6108. free(global_config.command_buffer);
  6109. global_config.command_buffer = NULL;
  6110. /* Leave command mode */
  6111. global_config.overlay_mode = OVERLAY_MODE_NONE;
  6112. }
  6113. /**
  6114. * Find the next search result, or loop back around if at the end.
  6115. */
  6116. BIM_ACTION(search_next, 0,
  6117. "Jump to the next search match."
  6118. )(void) {
  6119. if (!global_config.search) return;
  6120. if (env->coffset) env->coffset = 0;
  6121. int line = -1, col = -1;
  6122. find_match(env->line_no, env->col_no+1, &line, &col, global_config.search, NULL);
  6123. if (line == -1) {
  6124. find_match(1,1, &line, &col, global_config.search, NULL);
  6125. if (line == -1) return;
  6126. }
  6127. env->col_no = col;
  6128. env->line_no = line;
  6129. set_preferred_column();
  6130. draw_search_match(global_config.search, -1);
  6131. }
  6132. /**
  6133. * Find the previous search result, or loop to the end of the file.
  6134. */
  6135. BIM_ACTION(search_prev, 0,
  6136. "Jump to the preceding search match."
  6137. )(void) {
  6138. if (!global_config.search) return;
  6139. if (env->coffset) env->coffset = 0;
  6140. int line = -1, col = -1;
  6141. find_match_backwards(env->line_no, env->col_no-1, &line, &col, global_config.search);
  6142. if (line == -1) {
  6143. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, global_config.search);
  6144. if (line == -1) return;
  6145. }
  6146. env->col_no = col;
  6147. env->line_no = line;
  6148. set_preferred_column();
  6149. draw_search_match(global_config.search, -1);
  6150. }
  6151. /**
  6152. * Find the matching paren for this one.
  6153. *
  6154. * This approach skips having to do its own syntax parsing
  6155. * to deal with, eg., erroneous parens in comments. It does
  6156. * this by finding the matching paren with the same flag
  6157. * value, thus parens in strings will match, parens outside
  6158. * of strings will match, but parens in strings won't
  6159. * match parens outside of strings and so on.
  6160. */
  6161. void find_matching_paren(int * out_line, int * out_col, int in_col) {
  6162. if (env->col_no - in_col + 1 > env->lines[env->line_no-1]->actual) {
  6163. return; /* Invalid cursor position */
  6164. }
  6165. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  6166. int paren_match = 0;
  6167. int direction = 0;
  6168. int start = env->lines[env->line_no-1]->text[env->col_no-in_col].codepoint;
  6169. int flags = env->lines[env->line_no-1]->text[env->col_no-in_col].flags & 0x1F;
  6170. int count = 0;
  6171. /* TODO what about unicode parens? */
  6172. for (int i = 0; paren_pairs[i]; ++i) {
  6173. if (start == paren_pairs[i]) {
  6174. direction = (i % 2 == 0) ? 1 : -1;
  6175. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  6176. break;
  6177. }
  6178. }
  6179. if (!paren_match) return;
  6180. /* Scan for match */
  6181. int line = env->line_no;
  6182. int col = env->col_no - in_col + 1;
  6183. do {
  6184. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  6185. /* Only match on same syntax */
  6186. if ((env->lines[line-1]->text[col-1].flags & 0x1F) == flags) {
  6187. /* Count up on same direction */
  6188. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  6189. /* Count down on opposite direction */
  6190. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  6191. count--;
  6192. /* When count == 0 we have a match */
  6193. if (count == 0) goto _match_found;
  6194. }
  6195. }
  6196. col += direction;
  6197. }
  6198. line += direction;
  6199. /* Reached first/last line with no match */
  6200. if (line == 0 || line == env->line_count + 1) {
  6201. return;
  6202. }
  6203. /* Reset column to start/end of line, depending on direction */
  6204. if (direction > 0) {
  6205. col = 1;
  6206. } else {
  6207. col = env->lines[line-1]->actual;
  6208. }
  6209. } while (1);
  6210. _match_found:
  6211. *out_line = line;
  6212. *out_col = col;
  6213. }
  6214. /**
  6215. * Switch to the left split view
  6216. * (Primarily to handle cases where the left and right are the same buffer)
  6217. */
  6218. BIM_ACTION(use_left_buffer, 0,
  6219. "Switch to the left split view."
  6220. )(void) {
  6221. if (left_buffer == right_buffer && env->left != 0) {
  6222. view_right_offset = env->offset;
  6223. env->width = env->left;
  6224. env->left = 0;
  6225. env->offset = view_left_offset;
  6226. }
  6227. env = left_buffer;
  6228. update_title();
  6229. }
  6230. /**
  6231. * Switch to the right split view
  6232. * (Primarily to handle cases where the left and right are the same buffer)
  6233. */
  6234. BIM_ACTION(use_right_buffer, 0,
  6235. "Switch to the right split view."
  6236. )(void) {
  6237. if (left_buffer == right_buffer && env->left == 0) {
  6238. view_left_offset = env->offset;
  6239. env->left = env->width;
  6240. env->width = global_config.term_width - env->width;
  6241. env->offset = view_right_offset;
  6242. }
  6243. env = right_buffer;
  6244. update_title();
  6245. }
  6246. void handle_common_mouse(int buttons, int x, int y) {
  6247. if (buttons == 64) {
  6248. /* Scroll up */
  6249. if (global_config.shift_scrolling) {
  6250. env->loading = 1;
  6251. int shifted = 0;
  6252. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6253. if (env->offset > 0) {
  6254. env->offset--;
  6255. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - global_config.tabs_visible - global_config.cursor_padding) {
  6256. cursor_up();
  6257. }
  6258. shifted++;
  6259. }
  6260. }
  6261. env->loading = 0;
  6262. if (!shifted) return;
  6263. if (global_config.can_scroll && !left_buffer) {
  6264. shift_down(shifted);
  6265. for (int i = 0; i < shifted; ++i) {
  6266. redraw_line(env->offset+i);
  6267. }
  6268. } else {
  6269. redraw_text();
  6270. }
  6271. redraw_tabbar();
  6272. redraw_statusbar();
  6273. redraw_commandline();
  6274. place_cursor_actual();
  6275. } else {
  6276. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6277. cursor_up();
  6278. }
  6279. }
  6280. return;
  6281. } else if (buttons == 65) {
  6282. /* Scroll down */
  6283. if (global_config.shift_scrolling) {
  6284. env->loading = 1;
  6285. int shifted = 0;
  6286. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6287. if (env->offset < env->line_count-1) {
  6288. env->offset++;
  6289. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  6290. if (env->line_no <= e) {
  6291. cursor_down();
  6292. }
  6293. shifted++;
  6294. }
  6295. }
  6296. env->loading = 0;
  6297. if (!shifted) return;
  6298. if (global_config.can_scroll && !left_buffer) {
  6299. shift_up(shifted);
  6300. int l = global_config.term_height - global_config.bottom_size - global_config.tabs_visible;
  6301. for (int i = 0; i < shifted; ++i) {
  6302. if (env->offset + l - i < env->line_count + 1) {
  6303. redraw_line(env->offset + l-1-i);
  6304. } else {
  6305. draw_excess_line(l - 1 - i);
  6306. }
  6307. }
  6308. } else {
  6309. redraw_text();
  6310. }
  6311. redraw_tabbar();
  6312. redraw_statusbar();
  6313. redraw_commandline();
  6314. place_cursor_actual();
  6315. } else {
  6316. for (int i = 0; i < global_config.scroll_amount; ++i) {
  6317. cursor_down();
  6318. }
  6319. }
  6320. return;
  6321. } else if (buttons == 3) {
  6322. /* Move cursor to position */
  6323. if (x < 0) return;
  6324. if (y < 0) return;
  6325. if (y == 1 && global_config.tabs_visible) {
  6326. /* Pick from tabs */
  6327. if (env->mode != MODE_NORMAL && env->mode != MODE_INSERT) return; /* Don't let the tab be switched in other modes for now */
  6328. int _x = 0;
  6329. if (global_config.tab_offset) _x = 1;
  6330. if (global_config.tab_offset && _x >= x) {
  6331. global_config.tab_offset--;
  6332. redraw_tabbar();
  6333. return;
  6334. }
  6335. for (int i = global_config.tab_offset; i < buffers_len; i++) {
  6336. buffer_t * _env = buffers[i];
  6337. char tmp[64];
  6338. int size = 0;
  6339. int filled = draw_tab_name(_env, tmp, global_config.term_width - _x, &size);
  6340. _x += size;
  6341. if (_x >= x) {
  6342. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  6343. env = buffers[i];
  6344. redraw_all();
  6345. update_title();
  6346. return;
  6347. }
  6348. if (filled) break;
  6349. }
  6350. if (x > _x && global_config.tab_offset < buffers_len - 1) {
  6351. global_config.tab_offset++;
  6352. redraw_tabbar();
  6353. }
  6354. return;
  6355. }
  6356. if (env->mode == MODE_NORMAL || env->mode == MODE_INSERT) {
  6357. int current_mode = env->mode;
  6358. if (x < env->left && env == right_buffer) {
  6359. use_left_buffer();
  6360. } else if (x > env->width && env == left_buffer) {
  6361. use_right_buffer();
  6362. }
  6363. env->mode = current_mode;
  6364. redraw_all();
  6365. }
  6366. if (env->left) {
  6367. x -= env->left;
  6368. }
  6369. /* Figure out y coordinate */
  6370. int line_no = y + env->offset - global_config.tabs_visible;
  6371. int col_no = -1;
  6372. if (line_no > env->line_count) {
  6373. line_no = env->line_count;
  6374. }
  6375. if (line_no != env->line_no) {
  6376. env->coffset = 0;
  6377. }
  6378. /* Account for the left hand gutter */
  6379. int num_size = num_width() + gutter_width();
  6380. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  6381. /* Determine where the cursor is physically */
  6382. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  6383. char_t * c = &env->lines[line_no-1]->text[i];
  6384. _x += c->display_width;
  6385. if (_x > x-1) {
  6386. col_no = i+1;
  6387. break;
  6388. }
  6389. }
  6390. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  6391. col_no = env->lines[line_no-1]->actual;
  6392. }
  6393. env->line_no = line_no;
  6394. env->col_no = col_no;
  6395. set_history_break();
  6396. set_preferred_column();
  6397. redraw_statusbar();
  6398. place_cursor_actual();
  6399. }
  6400. return;
  6401. }
  6402. /**
  6403. * Handle mouse event
  6404. */
  6405. BIM_ACTION(handle_mouse, 0,
  6406. "Process mouse actions."
  6407. )(void) {
  6408. int buttons = bim_getch() - 32;
  6409. int x = bim_getch() - 32;
  6410. int y = bim_getch() - 32;
  6411. handle_common_mouse(buttons, x, y);
  6412. }
  6413. BIM_ACTION(handle_mouse_sgr, 0,
  6414. "Process SGR-style mouse actions."
  6415. )(void) {
  6416. int values[3] = {0};
  6417. char tmp[512] = {0};
  6418. char * c = tmp;
  6419. int buttons = 0;
  6420. do {
  6421. int _c = bim_getch();
  6422. if (_c == -1) {
  6423. break;
  6424. }
  6425. if (_c == 'm') {
  6426. buttons = 3;
  6427. break;
  6428. } else if (_c == 'M') {
  6429. buttons = 0;
  6430. break;
  6431. }
  6432. *c = _c;
  6433. ++c;
  6434. } while (1);
  6435. char * j = tmp;
  6436. char * last = tmp;
  6437. int i = 0;
  6438. while (*j) {
  6439. if (*j == ';') {
  6440. *j = '\0';
  6441. values[i] = atoi(last);
  6442. last = j+1;
  6443. i++;
  6444. if (i == 3) break;
  6445. }
  6446. j++;
  6447. }
  6448. if (last && i < 3) values[i] = atoi(last);
  6449. if (buttons != 3) {
  6450. buttons = values[0];
  6451. }
  6452. int x = values[1];
  6453. int y = values[2];
  6454. handle_common_mouse(buttons, x, y);
  6455. }
  6456. BIM_ACTION(insert_char, ARG_IS_INPUT | ACTION_IS_RW,
  6457. "Insert one character."
  6458. )(unsigned int c) {
  6459. if (!c) {
  6460. render_error("Inserted nil byte?");
  6461. return;
  6462. }
  6463. char_t _c;
  6464. _c.codepoint = c;
  6465. _c.flags = 0;
  6466. _c.display_width = codepoint_width(c);
  6467. line_t * line = env->lines[env->line_no - 1];
  6468. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  6469. if (line != nline) {
  6470. env->lines[env->line_no - 1] = nline;
  6471. }
  6472. env->col_no += 1;
  6473. set_preferred_column();
  6474. set_modified();
  6475. }
  6476. BIM_ACTION(replace_char, ARG_IS_PROMPT | ACTION_IS_RW,
  6477. "Replace a single character."
  6478. )(unsigned int c) {
  6479. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  6480. if (c >= KEY_ESCAPE) {
  6481. render_error("Invalid key for replacement");
  6482. return;
  6483. }
  6484. char_t _c;
  6485. _c.codepoint = c;
  6486. _c.flags = 0;
  6487. _c.display_width = codepoint_width(c);
  6488. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  6489. redraw_line(env->line_no-1);
  6490. set_modified();
  6491. }
  6492. BIM_ACTION(undo_history, ACTION_IS_RW,
  6493. "Undo history until the last breakpoint."
  6494. )(void) {
  6495. if (!global_config.history_enabled) return;
  6496. env->loading = 1;
  6497. history_t * e = env->history;
  6498. if (e->type == HISTORY_SENTINEL) {
  6499. env->loading = 0;
  6500. render_commandline_message("Already at oldest change");
  6501. return;
  6502. }
  6503. int count_chars = 0;
  6504. int count_lines = 0;
  6505. do {
  6506. if (e->type == HISTORY_SENTINEL) break;
  6507. switch (e->type) {
  6508. case HISTORY_INSERT:
  6509. /* Delete */
  6510. line_delete(
  6511. env->lines[e->contents.insert_delete_replace.lineno],
  6512. e->contents.insert_delete_replace.offset+1,
  6513. e->contents.insert_delete_replace.lineno
  6514. );
  6515. count_chars++;
  6516. break;
  6517. case HISTORY_DELETE:
  6518. {
  6519. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6520. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6521. env->lines[e->contents.insert_delete_replace.lineno],
  6522. _c,
  6523. e->contents.insert_delete_replace.offset-1,
  6524. e->contents.insert_delete_replace.lineno
  6525. );
  6526. }
  6527. count_chars++;
  6528. break;
  6529. case HISTORY_REPLACE:
  6530. {
  6531. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  6532. line_replace(
  6533. env->lines[e->contents.insert_delete_replace.lineno],
  6534. _o,
  6535. e->contents.insert_delete_replace.offset,
  6536. e->contents.insert_delete_replace.lineno
  6537. );
  6538. }
  6539. count_chars++;
  6540. break;
  6541. case HISTORY_REMOVE_LINE:
  6542. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6543. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6544. count_lines++;
  6545. break;
  6546. case HISTORY_ADD_LINE:
  6547. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  6548. count_lines++;
  6549. break;
  6550. case HISTORY_REPLACE_LINE:
  6551. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  6552. count_lines++;
  6553. break;
  6554. case HISTORY_SPLIT_LINE:
  6555. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  6556. count_lines++;
  6557. break;
  6558. case HISTORY_MERGE_LINES:
  6559. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  6560. count_lines++;
  6561. break;
  6562. case HISTORY_BREAK:
  6563. /* Ignore break */
  6564. break;
  6565. default:
  6566. render_error("Unknown type %d!\n", e->type);
  6567. break;
  6568. }
  6569. env->line_no = env->history->line;
  6570. env->col_no = env->history->col;
  6571. env->history = e->previous;
  6572. e = env->history;
  6573. } while (e->type != HISTORY_BREAK);
  6574. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6575. if (env->line_no < 1) env->line_no = 1;
  6576. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6577. if (env->col_no < 1) env->col_no = 1;
  6578. env->modified = (env->history != env->last_save_history);
  6579. env->loading = 0;
  6580. for (int i = 0; i < env->line_count; ++i) {
  6581. env->lines[i]->istate = 0;
  6582. recalculate_tabs(env->lines[i]);
  6583. }
  6584. for (int i = 0; i < env->line_count; ++i) {
  6585. recalculate_syntax(env->lines[i],i);
  6586. }
  6587. place_cursor_actual();
  6588. update_title();
  6589. redraw_all();
  6590. render_commandline_message("%d character%s, %d line%s changed",
  6591. count_chars, (count_chars == 1) ? "" : "s",
  6592. count_lines, (count_lines == 1) ? "" : "s");
  6593. }
  6594. BIM_ACTION(redo_history, ACTION_IS_RW,
  6595. "Redo history until the next breakpoint."
  6596. )(void) {
  6597. if (!global_config.history_enabled) return;
  6598. env->loading = 1;
  6599. history_t * e = env->history->next;
  6600. if (!e) {
  6601. env->loading = 0;
  6602. render_commandline_message("Already at newest change");
  6603. return;
  6604. }
  6605. int count_chars = 0;
  6606. int count_lines = 0;
  6607. while (e) {
  6608. if (e->type == HISTORY_BREAK) {
  6609. env->history = e;
  6610. break;
  6611. }
  6612. switch (e->type) {
  6613. case HISTORY_INSERT:
  6614. {
  6615. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6616. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  6617. env->lines[e->contents.insert_delete_replace.lineno],
  6618. _c,
  6619. e->contents.insert_delete_replace.offset,
  6620. e->contents.insert_delete_replace.lineno
  6621. );
  6622. }
  6623. count_chars++;
  6624. break;
  6625. case HISTORY_DELETE:
  6626. /* Delete */
  6627. line_delete(
  6628. env->lines[e->contents.insert_delete_replace.lineno],
  6629. e->contents.insert_delete_replace.offset,
  6630. e->contents.insert_delete_replace.lineno
  6631. );
  6632. count_chars++;
  6633. break;
  6634. case HISTORY_REPLACE:
  6635. {
  6636. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  6637. line_replace(
  6638. env->lines[e->contents.insert_delete_replace.lineno],
  6639. _o,
  6640. e->contents.insert_delete_replace.offset,
  6641. e->contents.insert_delete_replace.lineno
  6642. );
  6643. }
  6644. count_chars++;
  6645. break;
  6646. case HISTORY_ADD_LINE:
  6647. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  6648. count_lines++;
  6649. break;
  6650. case HISTORY_REMOVE_LINE:
  6651. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  6652. count_lines++;
  6653. break;
  6654. case HISTORY_REPLACE_LINE:
  6655. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  6656. count_lines++;
  6657. break;
  6658. case HISTORY_MERGE_LINES:
  6659. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  6660. count_lines++;
  6661. break;
  6662. case HISTORY_SPLIT_LINE:
  6663. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  6664. count_lines++;
  6665. break;
  6666. case HISTORY_BREAK:
  6667. /* Ignore break */
  6668. break;
  6669. default:
  6670. render_error("Unknown type %d!\n", e->type);
  6671. break;
  6672. }
  6673. env->history = e;
  6674. e = e->next;
  6675. }
  6676. env->line_no = env->history->line;
  6677. env->col_no = env->history->col;
  6678. if (env->line_no > env->line_count) env->line_no = env->line_count;
  6679. if (env->line_no < 1) env->line_no = 1;
  6680. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  6681. if (env->col_no < 1) env->col_no = 1;
  6682. env->modified = (env->history != env->last_save_history);
  6683. env->loading = 0;
  6684. for (int i = 0; i < env->line_count; ++i) {
  6685. env->lines[i]->istate = 0;
  6686. recalculate_tabs(env->lines[i]);
  6687. }
  6688. for (int i = 0; i < env->line_count; ++i) {
  6689. recalculate_syntax(env->lines[i],i);
  6690. }
  6691. place_cursor_actual();
  6692. update_title();
  6693. redraw_all();
  6694. render_commandline_message("%d character%s, %d line%s changed",
  6695. count_chars, (count_chars == 1) ? "" : "s",
  6696. count_lines, (count_lines == 1) ? "" : "s");
  6697. }
  6698. int is_whitespace(int codepoint) {
  6699. return codepoint == ' ' || codepoint == '\t';
  6700. }
  6701. int is_normal(int codepoint) {
  6702. return isalnum(codepoint) || codepoint == '_';
  6703. }
  6704. int is_special(int codepoint) {
  6705. return !is_normal(codepoint) && !is_whitespace(codepoint);
  6706. }
  6707. BIM_ACTION(word_left, 0,
  6708. "Move the cursor left to the previous word."
  6709. )(void) {
  6710. if (!env->lines[env->line_no-1]) return;
  6711. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6712. env->col_no -= 1;
  6713. }
  6714. if (env->col_no == 1) {
  6715. if (env->line_no == 1) goto _place;
  6716. env->line_no--;
  6717. env->col_no = env->lines[env->line_no-1]->actual;
  6718. goto _place;
  6719. }
  6720. int (*inverse_comparator)(int) = is_special;
  6721. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6722. inverse_comparator = is_normal;
  6723. }
  6724. do {
  6725. if (env->col_no > 1) {
  6726. env->col_no -= 1;
  6727. }
  6728. } 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));
  6729. _place:
  6730. set_preferred_column();
  6731. place_cursor_actual();
  6732. }
  6733. BIM_ACTION(big_word_left, 0,
  6734. "Move the cursor left to the previous WORD."
  6735. )(void) {
  6736. int line_no = env->line_no;
  6737. int col_no = env->col_no;
  6738. do {
  6739. col_no--;
  6740. while (col_no == 0) {
  6741. line_no--;
  6742. if (line_no == 0) {
  6743. goto_line(1);
  6744. set_preferred_column();
  6745. return;
  6746. }
  6747. col_no = env->lines[line_no-1]->actual;
  6748. }
  6749. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6750. do {
  6751. col_no--;
  6752. if (col_no == 0) {
  6753. env->col_no = 1;
  6754. env->line_no = line_no;
  6755. set_preferred_column();
  6756. redraw_statusbar();
  6757. place_cursor_actual();
  6758. return;
  6759. }
  6760. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6761. env->col_no = col_no;
  6762. env->line_no = line_no;
  6763. set_preferred_column();
  6764. cursor_right();
  6765. }
  6766. BIM_ACTION(word_right, 0,
  6767. "Move the cursor right to the start of the next word."
  6768. )(void) {
  6769. if (!env->lines[env->line_no-1]) return;
  6770. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6771. /* next line */
  6772. if (env->line_no == env->line_count) return;
  6773. env->line_no++;
  6774. env->col_no = 0;
  6775. if (env->col_no >= env->lines[env->line_no-1]->actual) {
  6776. goto _place;
  6777. }
  6778. }
  6779. if (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  6780. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no-1]->text[env->col_no - 1].codepoint)) {
  6781. env->col_no++;
  6782. }
  6783. goto _place;
  6784. }
  6785. int (*inverse_comparator)(int) = is_special;
  6786. if (is_special(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6787. inverse_comparator = is_normal;
  6788. }
  6789. while (env->col_no < env->lines[env->line_no-1]->actual && !is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint) && !inverse_comparator(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6790. env->col_no++;
  6791. }
  6792. while (env->col_no < env->lines[env->line_no-1]->actual && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 1].codepoint)) {
  6793. env->col_no++;
  6794. }
  6795. _place:
  6796. set_preferred_column();
  6797. place_cursor_actual();
  6798. }
  6799. BIM_ACTION(big_word_right, 0,
  6800. "Move the cursor right to the start of the next WORD."
  6801. )(void) {
  6802. int line_no = env->line_no;
  6803. int col_no = env->col_no;
  6804. do {
  6805. col_no++;
  6806. if (col_no > env->lines[line_no-1]->actual) {
  6807. line_no++;
  6808. if (line_no > env->line_count) {
  6809. env->line_no = env->line_count;
  6810. env->col_no = env->lines[env->line_no-1]->actual;
  6811. set_preferred_column();
  6812. redraw_statusbar();
  6813. place_cursor_actual();
  6814. return;
  6815. }
  6816. col_no = 0;
  6817. break;
  6818. }
  6819. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6820. do {
  6821. col_no++;
  6822. while (col_no > env->lines[line_no-1]->actual) {
  6823. line_no++;
  6824. if (line_no >= env->line_count) {
  6825. env->col_no = env->lines[env->line_count-1]->actual;
  6826. env->line_no = env->line_count;
  6827. set_preferred_column();
  6828. redraw_statusbar();
  6829. place_cursor_actual();
  6830. return;
  6831. }
  6832. col_no = 1;
  6833. }
  6834. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  6835. env->col_no = col_no;
  6836. env->line_no = line_no;
  6837. set_preferred_column();
  6838. redraw_statusbar();
  6839. place_cursor_actual();
  6840. return;
  6841. }
  6842. BIM_ACTION(delete_at_cursor, ACTION_IS_RW,
  6843. "Delete the character at the cursor, or merge with previous line."
  6844. )(void) {
  6845. if (env->col_no > 1) {
  6846. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6847. env->col_no -= 1;
  6848. if (env->coffset > 0) env->coffset--;
  6849. redraw_line(env->line_no-1);
  6850. set_modified();
  6851. redraw_statusbar();
  6852. place_cursor_actual();
  6853. } else if (env->line_no > 1) {
  6854. int tmp = env->lines[env->line_no - 2]->actual;
  6855. merge_lines(env->lines, env->line_no - 1);
  6856. env->line_no -= 1;
  6857. env->col_no = tmp+1;
  6858. set_preferred_column();
  6859. redraw_text();
  6860. set_modified();
  6861. redraw_statusbar();
  6862. place_cursor_actual();
  6863. }
  6864. }
  6865. BIM_ACTION(delete_word, ACTION_IS_RW,
  6866. "Delete the previous word."
  6867. )(void) {
  6868. if (!env->lines[env->line_no-1]) return;
  6869. if (env->col_no > 1) {
  6870. /* Start by deleting whitespace */
  6871. while (env->col_no > 1 && is_whitespace(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6872. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6873. env->col_no -= 1;
  6874. if (env->coffset > 0) env->coffset--;
  6875. }
  6876. int (*inverse_comparator)(int) = is_special;
  6877. if (env->col_no > 1 && is_special(env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint)) {
  6878. inverse_comparator = is_normal;
  6879. }
  6880. do {
  6881. if (env->col_no > 1) {
  6882. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  6883. env->col_no -= 1;
  6884. if (env->coffset > 0) env->coffset--;
  6885. }
  6886. } 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));
  6887. set_preferred_column();
  6888. redraw_text();
  6889. set_modified();
  6890. redraw_statusbar();
  6891. place_cursor_actual();
  6892. }
  6893. }
  6894. BIM_ACTION(insert_line_feed, ACTION_IS_RW,
  6895. "Insert a line break, splitting the current line into two."
  6896. )(void) {
  6897. if (env->indent) {
  6898. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  6899. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  6900. (env->col_no > 3) &&
  6901. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  6902. delete_at_cursor();
  6903. }
  6904. }
  6905. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  6906. env->lines = add_line(env->lines, env->line_no);
  6907. } else {
  6908. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  6909. }
  6910. env->coffset = 0;
  6911. env->col_no = 1;
  6912. env->line_no += 1;
  6913. set_preferred_column();
  6914. add_indent(env->line_no-1,env->line_no-2,0);
  6915. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  6916. env->offset += 1;
  6917. }
  6918. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  6919. set_modified();
  6920. }
  6921. BIM_ACTION(yank_lines, 0,
  6922. "Copy lines into the paste buffer."
  6923. )(void) {
  6924. int start = env->start_line;
  6925. int end = env->line_no;
  6926. if (global_config.yanks) {
  6927. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6928. free(global_config.yanks[i]);
  6929. }
  6930. free(global_config.yanks);
  6931. }
  6932. int lines_to_yank;
  6933. int start_point;
  6934. if (start <= end) {
  6935. lines_to_yank = end - start + 1;
  6936. start_point = start - 1;
  6937. } else {
  6938. lines_to_yank = start - end + 1;
  6939. start_point = end - 1;
  6940. }
  6941. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6942. global_config.yank_count = lines_to_yank;
  6943. global_config.yank_is_full_lines = 1;
  6944. for (int i = 0; i < lines_to_yank; ++i) {
  6945. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6946. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6947. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6948. global_config.yanks[i]->istate = 0;
  6949. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6950. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6951. global_config.yanks[i]->text[j].flags = 0;
  6952. }
  6953. }
  6954. }
  6955. /**
  6956. * Helper to yank part of a line into a new yank line.
  6957. */
  6958. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  6959. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  6960. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  6961. global_config.yanks[yank_no]->actual = count;
  6962. global_config.yanks[yank_no]->istate = 0;
  6963. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  6964. for (int i = 0; i < count; ++i) {
  6965. global_config.yanks[yank_no]->text[i].flags = 0;
  6966. }
  6967. }
  6968. /**
  6969. * Yank text...
  6970. */
  6971. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  6972. if (global_config.yanks) {
  6973. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  6974. free(global_config.yanks[i]);
  6975. }
  6976. free(global_config.yanks);
  6977. }
  6978. int lines_to_yank = end_line - start_line + 1;
  6979. int start_point = start_line - 1;
  6980. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  6981. global_config.yank_count = lines_to_yank;
  6982. global_config.yank_is_full_lines = 0;
  6983. if (lines_to_yank == 1) {
  6984. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  6985. } else {
  6986. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  6987. /* Yank middle lines */
  6988. for (int i = 1; i < lines_to_yank - 1; ++i) {
  6989. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  6990. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  6991. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  6992. global_config.yanks[i]->istate = 0;
  6993. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  6994. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  6995. global_config.yanks[i]->text[j].flags = 0;
  6996. }
  6997. }
  6998. /* Yank end line */
  6999. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  7000. }
  7001. }
  7002. BIM_ACTION(delete_at_column, ARG_IS_CUSTOM | ACTION_IS_RW,
  7003. "Delete from the current column backwards (`<backspace>`) or forwards (`<del>`)."
  7004. )(int direction) {
  7005. if (direction == -1 && env->sel_col <= 0) return;
  7006. int prev_width = 0;
  7007. for (int i = env->line_no; i <= env->start_line; i++) {
  7008. line_t * line = env->lines[i - 1];
  7009. int _x = 0;
  7010. int col = 1;
  7011. int j = 0;
  7012. for (; j < line->actual; ++j) {
  7013. char_t * c = &line->text[j];
  7014. _x += c->display_width;
  7015. col = j+1;
  7016. if (_x > env->sel_col) break;
  7017. prev_width = c->display_width;
  7018. }
  7019. if ((direction == -1) && (_x == env->sel_col && j == line->actual)) {
  7020. line_delete(line, line->actual, i - 1);
  7021. set_modified();
  7022. } else if (_x > env->sel_col) {
  7023. line_delete(line, col - (direction == -1 ? 1 : 0), i - 1);
  7024. set_modified();
  7025. }
  7026. }
  7027. if (direction == -1) {
  7028. env->sel_col -= prev_width;
  7029. env->col_no--;
  7030. }
  7031. redraw_text();
  7032. }
  7033. uint32_t * get_word_under_cursor(void) {
  7034. /* Figure out size */
  7035. int c_before = 0;
  7036. int c_after = 0;
  7037. int i = env->col_no;
  7038. while (i > 0) {
  7039. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7040. c_before++;
  7041. i--;
  7042. }
  7043. i = env->col_no+1;
  7044. while (i < env->lines[env->line_no-1]->actual+1) {
  7045. if (!simple_keyword_qualifier(env->lines[env->line_no-1]->text[i-1].codepoint)) break;
  7046. c_after++;
  7047. i++;
  7048. }
  7049. if (!c_before && !c_after) return NULL;
  7050. /* Populate with characters */
  7051. uint32_t * out = malloc(sizeof(uint32_t) * (c_before+c_after+1));
  7052. int j = 0;
  7053. while (c_before) {
  7054. out[j] = env->lines[env->line_no-1]->text[env->col_no-c_before].codepoint;
  7055. c_before--;
  7056. j++;
  7057. }
  7058. int x = 0;
  7059. while (c_after) {
  7060. out[j] = env->lines[env->line_no-1]->text[env->col_no+x].codepoint;
  7061. j++;
  7062. x++;
  7063. c_after--;
  7064. }
  7065. out[j] = 0;
  7066. return out;
  7067. }
  7068. BIM_ACTION(search_under_cursor, 0,
  7069. "Search for the word currently under the cursor."
  7070. )(void) {
  7071. if (global_config.search) free(global_config.search);
  7072. global_config.search = get_word_under_cursor();
  7073. /* Find it */
  7074. search_next();
  7075. }
  7076. BIM_ACTION(find_character_forward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7077. "Find a character forward on the current line and place the cursor on (`f`) or before (`t`) it."
  7078. )(int type, int c) {
  7079. for (int i = env->col_no+1; i <= env->lines[env->line_no-1]->actual; ++i) {
  7080. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7081. env->col_no = i - !!(type == 't');
  7082. place_cursor_actual();
  7083. set_preferred_column();
  7084. return;
  7085. }
  7086. }
  7087. }
  7088. BIM_ACTION(find_character_backward, ARG_IS_PROMPT | ARG_IS_INPUT,
  7089. "Find a character backward on the current line and place the cursor on (`F`) or after (`T`) it."
  7090. )(int type, int c) {
  7091. for (int i = env->col_no-1; i >= 1; --i) {
  7092. if (env->lines[env->line_no-1]->text[i-1].codepoint == c) {
  7093. env->col_no = i + !!(type == 'T');
  7094. place_cursor_actual();
  7095. set_preferred_column();
  7096. return;
  7097. }
  7098. }
  7099. }
  7100. /**
  7101. * Clear the navigation number buffer
  7102. */
  7103. void reset_nav_buffer(int c) {
  7104. if (c == KEY_TIMEOUT) return;
  7105. if (nav_buffer && (c < '0' || c > '9')) {
  7106. nav_buffer = 0;
  7107. redraw_commandline();
  7108. }
  7109. }
  7110. /**
  7111. * Determine if a column + line number are within range of the
  7112. * current character selection specified by start_line, etc.
  7113. *
  7114. * Used to determine how syntax flags should be set when redrawing
  7115. * selected text in CHAR SELECTION mode.
  7116. */
  7117. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  7118. if (start_line == end_line) {
  7119. if ( end_col < start_col) {
  7120. int tmp = end_col;
  7121. end_col = start_col;
  7122. start_col = tmp;
  7123. }
  7124. return (col >= start_col && col <= end_col);
  7125. }
  7126. if (start_line > end_line) {
  7127. int tmp = end_line;
  7128. end_line = start_line;
  7129. start_line = tmp;
  7130. tmp = end_col;
  7131. end_col = start_col;
  7132. start_col = tmp;
  7133. }
  7134. if (line < start_line || line > end_line) return 0;
  7135. if (line == start_line) {
  7136. return col >= start_col;
  7137. }
  7138. if (line == end_line) {
  7139. return col <= end_col;
  7140. }
  7141. return 1;
  7142. }
  7143. /**
  7144. * Macro for redrawing selected lines with appropriate highlighting.
  7145. */
  7146. #define _redraw_line(line, force_start_line) \
  7147. do { \
  7148. if (!(force_start_line) && (line) == env->start_line) break; \
  7149. if ((line) > env->line_count + 1) { \
  7150. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7151. draw_excess_line((line) - env->offset - 1); \
  7152. } \
  7153. break; \
  7154. } \
  7155. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7156. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7157. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7158. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7159. } else { \
  7160. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7161. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7162. } \
  7163. } \
  7164. redraw_line((line)-1); \
  7165. } while (0)
  7166. #define _redraw_line_char(line, force_start_line) \
  7167. do { \
  7168. if (!(force_start_line) && (line) == env->start_line) break; \
  7169. if ((line) > env->line_count + 1) { \
  7170. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7171. draw_excess_line((line) - env->offset - 1); \
  7172. } \
  7173. break; \
  7174. } \
  7175. if ((env->line_no < env->start_line && ((line) < env->line_no || (line) > env->start_line)) || \
  7176. (env->line_no > env->start_line && ((line) > env->line_no || (line) < env->start_line)) || \
  7177. (env->line_no == env->start_line && (line) != env->start_line)) { \
  7178. /* Line is completely outside selection */ \
  7179. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7180. } else { \
  7181. if ((line) == env->start_line || (line) == env->line_no) { \
  7182. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  7183. } \
  7184. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  7185. if (point_in_range(env->start_line, env->line_no,env->start_col, env->col_no, (line), j+1)) { \
  7186. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  7187. } \
  7188. } \
  7189. } \
  7190. redraw_line((line)-1); \
  7191. } while (0)
  7192. #define _redraw_line_col(line, force_start_line) \
  7193. do {\
  7194. if (!(force_start_line) && (line) == env->start_line) break; \
  7195. if ((line) > env->line_count + 1) { \
  7196. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  7197. draw_excess_line((line) - env->offset - 1); \
  7198. } \
  7199. break; \
  7200. } \
  7201. redraw_line((line)-1); \
  7202. } while (0)
  7203. BIM_ACTION(adjust_indent, ARG_IS_CUSTOM | ACTION_IS_RW,
  7204. "Adjust the indentation on the selected lines (`<tab>` for deeper, `<shift-tab>` for shallower)."
  7205. )(int direction) {
  7206. int lines_to_cover = 0;
  7207. int start_point = 0;
  7208. if (env->start_line <= env->line_no) {
  7209. start_point = env->start_line - 1;
  7210. lines_to_cover = env->line_no - env->start_line + 1;
  7211. } else {
  7212. start_point = env->line_no - 1;
  7213. lines_to_cover = env->start_line - env->line_no + 1;
  7214. }
  7215. for (int i = 0; i < lines_to_cover; ++i) {
  7216. if (env->lines[start_point + i]->actual < 1) continue;
  7217. if (direction == -1) {
  7218. if (env->tabs) {
  7219. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  7220. line_delete(env->lines[start_point + i],1,start_point+i);
  7221. _redraw_line(start_point+i+1,1);
  7222. }
  7223. } else {
  7224. for (int j = 0; j < env->tabstop; ++j) {
  7225. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  7226. line_delete(env->lines[start_point + i],1,start_point+i);
  7227. }
  7228. }
  7229. _redraw_line(start_point+i+1,1);
  7230. }
  7231. } else if (direction == 1) {
  7232. if (env->tabs) {
  7233. char_t c;
  7234. c.codepoint = '\t';
  7235. c.display_width = env->tabstop;
  7236. c.flags = FLAG_SELECT;
  7237. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7238. } else {
  7239. for (int j = 0; j < env->tabstop; ++j) {
  7240. char_t c;
  7241. c.codepoint = ' ';
  7242. c.display_width = 1;
  7243. c.flags = FLAG_SELECT;
  7244. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  7245. }
  7246. }
  7247. _redraw_line(start_point+i+1,1);
  7248. }
  7249. }
  7250. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7251. env->col_no = env->lines[env->line_no-1]->actual;
  7252. }
  7253. set_preferred_column();
  7254. set_modified();
  7255. }
  7256. void recalculate_selected_lines(void) {
  7257. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7258. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7259. if (start < 1) start = 1;
  7260. if (start > env->line_count) start = env->line_count;
  7261. if (end < 1) end = 1;
  7262. if (end > env->line_count) end = env->line_count;
  7263. for (int i = (start > 1) ? (start-1) : (start); i <= end; ++i) {
  7264. recalculate_syntax(env->lines[i-1],i-1);
  7265. }
  7266. redraw_all();
  7267. }
  7268. BIM_ACTION(enter_line_selection, 0,
  7269. "Enter line selection mode."
  7270. )(void) {
  7271. /* Set mode */
  7272. env->mode = MODE_LINE_SELECTION;
  7273. /* Store start position */
  7274. env->start_line = env->line_no;
  7275. env->prev_line = env->start_line;
  7276. env->start_col = env->col_no;
  7277. /* Redraw commandline to get -- LINE SELECTION -- text */
  7278. redraw_commandline();
  7279. unhighlight_matching_paren();
  7280. /* Set this line as selected for syntax highlighting */
  7281. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  7282. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  7283. }
  7284. /* And redraw it */
  7285. redraw_line(env->line_no-1);
  7286. }
  7287. BIM_ACTION(switch_selection_mode, ARG_IS_CUSTOM,
  7288. "Swap between LINE and CHAR selection modes."
  7289. )(int mode) {
  7290. env->mode = mode;
  7291. if (mode == MODE_LINE_SELECTION) {
  7292. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7293. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7294. for (int i = start; i <= end; ++i) {
  7295. _redraw_line(i, 1);
  7296. }
  7297. } else if (mode == MODE_CHAR_SELECTION) {
  7298. int start = env->line_no < env->start_line ? env->line_no : env->start_line;
  7299. int end = env->line_no > env->start_line ? env->line_no : env->start_line;
  7300. for (int i = start; i <= end; ++i) {
  7301. _redraw_line_char(i, 1);
  7302. }
  7303. }
  7304. }
  7305. BIM_ACTION(delete_and_yank_lines, 0,
  7306. "Delete and yank the selected lines."
  7307. )(void) {
  7308. yank_lines();
  7309. if (env->start_line <= env->line_no) {
  7310. int lines_to_delete = env->line_no - env->start_line + 1;
  7311. for (int i = 0; i < lines_to_delete; ++i) {
  7312. env->lines = remove_line(env->lines, env->start_line-1);
  7313. }
  7314. env->line_no = env->start_line;
  7315. } else {
  7316. int lines_to_delete = env->start_line - env->line_no + 1;
  7317. for (int i = 0; i < lines_to_delete; ++i) {
  7318. env->lines = remove_line(env->lines, env->line_no-1);
  7319. }
  7320. }
  7321. if (env->line_no > env->line_count) {
  7322. env->line_no = env->line_count;
  7323. }
  7324. if (env->col_no > env->lines[env->line_no-1]->actual) {
  7325. env->col_no = env->lines[env->line_no-1]->actual;
  7326. }
  7327. set_preferred_column();
  7328. set_modified();
  7329. }
  7330. BIM_ACTION(enter_insert, ACTION_IS_RW,
  7331. "Enter insert mode."
  7332. )(void) {
  7333. env->mode = MODE_INSERT;
  7334. set_history_break();
  7335. }
  7336. BIM_ACTION(delete_lines_and_enter_insert, ACTION_IS_RW,
  7337. "Delete and yank the selected lines and then enter insert mode."
  7338. )(void) {
  7339. delete_and_yank_lines();
  7340. env->lines = add_line(env->lines, env->line_no-1);
  7341. redraw_text();
  7342. env->mode = MODE_INSERT;
  7343. }
  7344. BIM_ACTION(replace_chars_in_line, ARG_IS_PROMPT | ACTION_IS_RW,
  7345. "Replace characters in the selected lines."
  7346. )(int c) {
  7347. if (c >= KEY_ESCAPE) {
  7348. render_error("Invalid key for replacement");
  7349. return;
  7350. }
  7351. char_t _c = {codepoint_width(c), 0, c};
  7352. int start_point = env->start_line < env->line_no ? env->start_line : env->line_no;
  7353. int end_point = env->start_line < env->line_no ? env->line_no : env->start_line;
  7354. for (int line = start_point; line <= end_point; ++line) {
  7355. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7356. line_replace(env->lines[line-1], _c, i, line-1);
  7357. }
  7358. }
  7359. }
  7360. BIM_ACTION(leave_selection, 0,
  7361. "Leave selection modes and return to normal mode."
  7362. )(void) {
  7363. set_history_break();
  7364. env->mode = MODE_NORMAL;
  7365. recalculate_selected_lines();
  7366. }
  7367. BIM_ACTION(insert_char_at_column, ARG_IS_INPUT | ACTION_IS_RW,
  7368. "Insert a character on all lines at the current column."
  7369. )(int c) {
  7370. char_t _c;
  7371. _c.codepoint = c;
  7372. _c.flags = 0;
  7373. _c.display_width = codepoint_width(c);
  7374. int inserted_width = 0;
  7375. /* For each line */
  7376. for (int i = env->line_no; i <= env->start_line; i++) {
  7377. line_t * line = env->lines[i - 1];
  7378. int _x = 0;
  7379. int col = 1;
  7380. int j = 0;
  7381. for (; j < line->actual; ++j) {
  7382. char_t * c = &line->text[j];
  7383. _x += c->display_width;
  7384. col = j+1;
  7385. if (_x > env->sel_col) break;
  7386. }
  7387. if ((_x == env->sel_col && j == line->actual)) {
  7388. _x = env->sel_col + 1;
  7389. col = line->actual + 1;
  7390. }
  7391. if (_x > env->sel_col) {
  7392. line_t * nline = line_insert(line, _c, col - 1, i - 1);
  7393. if (line != nline) {
  7394. env->lines[i - 1] = nline;
  7395. line = nline;
  7396. }
  7397. set_modified();
  7398. }
  7399. recalculate_tabs(line);
  7400. inserted_width = line->text[col-1].display_width;
  7401. }
  7402. env->sel_col += inserted_width;
  7403. env->col_no++;
  7404. }
  7405. BIM_ACTION(enter_col_insert, ACTION_IS_RW,
  7406. "Enter column insert mode."
  7407. )(void) {
  7408. if (env->start_line < env->line_no) {
  7409. /* swap */
  7410. int tmp = env->line_no;
  7411. env->line_no = env->start_line;
  7412. env->start_line = tmp;
  7413. }
  7414. env->mode = MODE_COL_INSERT;
  7415. }
  7416. BIM_ACTION(enter_col_insert_after, ACTION_IS_RW,
  7417. "Enter column insert mode after the selected column."
  7418. )(void) {
  7419. env->sel_col += 1;
  7420. enter_col_insert();
  7421. }
  7422. BIM_ACTION(delete_column, ACTION_IS_RW,
  7423. "(temporary) Delete the selected column."
  7424. )(void) {
  7425. /* TODO maybe a flag to do this so we can just call delete_at_column with arg = 1? */
  7426. if (env->start_line < env->line_no) {
  7427. int tmp = env->line_no;
  7428. env->line_no = env->start_line;
  7429. env->start_line = tmp;
  7430. }
  7431. delete_at_column(1);
  7432. }
  7433. BIM_ACTION(enter_col_selection, 0,
  7434. "Enter column selection mode."
  7435. )(void) {
  7436. /* Set mode */
  7437. env->mode = MODE_COL_SELECTION;
  7438. /* Store cursor */
  7439. env->start_line = env->line_no;
  7440. env->sel_col = env->preferred_column;
  7441. env->prev_line = env->start_line;
  7442. /* Redraw commandline */
  7443. redraw_commandline();
  7444. /* Nothing else to do here; rely on cursor */
  7445. }
  7446. BIM_ACTION(yank_characters, 0,
  7447. "Yank the selected characters to the paste buffer."
  7448. )(void) {
  7449. int end_line = env->line_no;
  7450. int end_col = env->col_no;
  7451. if (env->start_line == end_line) {
  7452. if (env->start_col > end_col) {
  7453. int tmp = env->start_col;
  7454. env->start_col = end_col;
  7455. end_col = tmp;
  7456. }
  7457. } else if (env->start_line > end_line) {
  7458. int tmp = env->start_line;
  7459. env->start_line = end_line;
  7460. end_line = tmp;
  7461. tmp = env->start_col;
  7462. env->start_col = end_col;
  7463. end_col = tmp;
  7464. }
  7465. yank_text(env->start_line, env->start_col, end_line, end_col);
  7466. }
  7467. BIM_ACTION(delete_and_yank_chars, ACTION_IS_RW,
  7468. "Delete and yank the selected characters."
  7469. )(void) {
  7470. int end_line = env->line_no;
  7471. int end_col = env->col_no;
  7472. if (env->start_line == end_line) {
  7473. if (env->start_col > end_col) {
  7474. int tmp = env->start_col;
  7475. env->start_col = end_col;
  7476. end_col = tmp;
  7477. }
  7478. yank_text(env->start_line, env->start_col, end_line, end_col);
  7479. for (int i = env->start_col; i <= end_col; ++i) {
  7480. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7481. }
  7482. env->col_no = env->start_col;
  7483. } else {
  7484. if (env->start_line > end_line) {
  7485. int tmp = env->start_line;
  7486. env->start_line = end_line;
  7487. end_line = tmp;
  7488. tmp = env->start_col;
  7489. env->start_col = end_col;
  7490. end_col = tmp;
  7491. }
  7492. /* Copy lines */
  7493. yank_text(env->start_line, env->start_col, end_line, end_col);
  7494. /* Delete lines */
  7495. for (int i = env->start_line+1; i < end_line; ++i) {
  7496. env->lines = remove_line(env->lines, env->start_line);
  7497. } /* end_line is no longer valid; should be start_line+1*/
  7498. /* Delete from env->start_col forward */
  7499. int tmp = env->lines[env->start_line-1]->actual;
  7500. for (int i = env->start_col; i <= tmp; ++i) {
  7501. line_delete(env->lines[env->start_line-1], env->start_col, env->start_line - 1);
  7502. }
  7503. for (int i = 1; i <= end_col; ++i) {
  7504. line_delete(env->lines[env->start_line], 1, env->start_line);
  7505. }
  7506. /* Merge start and end lines */
  7507. merge_lines(env->lines, env->start_line);
  7508. env->line_no = env->start_line;
  7509. env->col_no = env->start_col;
  7510. }
  7511. if (env->line_no > env->line_count) {
  7512. env->line_no = env->line_count;
  7513. }
  7514. set_preferred_column();
  7515. set_modified();
  7516. }
  7517. BIM_ACTION(delete_chars_and_enter_insert, ACTION_IS_RW,
  7518. "Delete and yank the selected characters and then enter insert mode."
  7519. )(void) {
  7520. delete_and_yank_chars();
  7521. redraw_text();
  7522. enter_insert();
  7523. }
  7524. BIM_ACTION(replace_chars, ARG_IS_PROMPT | ACTION_IS_RW,
  7525. "Replace the selected characters."
  7526. )(int c) {
  7527. if (c >= KEY_ESCAPE) {
  7528. render_error("Invalid key for replacement");
  7529. return;
  7530. }
  7531. char_t _c = {codepoint_width(c), 0, c};
  7532. /* This should probably be a function line "do_over_range" or something */
  7533. if (env->start_line == env->line_no) {
  7534. int s = (env->start_col < env->col_no) ? env->start_col : env->col_no;
  7535. int e = (env->start_col < env->col_no) ? env->col_no : env->start_col;
  7536. for (int i = s; i <= e; ++i) {
  7537. line_replace(env->lines[env->start_line-1], _c, i-1, env->start_line-1);
  7538. }
  7539. redraw_text();
  7540. } else {
  7541. if (env->start_line < env->line_no) {
  7542. for (int s = env->start_col-1; s < env->lines[env->start_line-1]->actual; ++s) {
  7543. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7544. }
  7545. for (int line = env->start_line + 1; line < env->line_no; ++line) {
  7546. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7547. line_replace(env->lines[line-1], _c, i, line-1);
  7548. }
  7549. }
  7550. for (int s = 0; s < env->col_no; ++s) {
  7551. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7552. }
  7553. } else {
  7554. for (int s = env->col_no-1; s < env->lines[env->line_no-1]->actual; ++s) {
  7555. line_replace(env->lines[env->line_no-1], _c, s, env->line_no-1);
  7556. }
  7557. for (int line = env->line_no + 1; line < env->start_line; ++line) {
  7558. for (int i = 0; i < env->lines[line-1]->actual; ++i) {
  7559. line_replace(env->lines[line-1], _c, i, line-1);
  7560. }
  7561. }
  7562. for (int s = 0; s < env->start_col; ++s) {
  7563. line_replace(env->lines[env->start_line-1], _c, s, env->start_line-1);
  7564. }
  7565. }
  7566. }
  7567. }
  7568. BIM_ACTION(enter_char_selection, 0,
  7569. "Enter character selection mode."
  7570. )(void) {
  7571. /* Set mode */
  7572. env->mode = MODE_CHAR_SELECTION;
  7573. /* Set cursor positions */
  7574. env->start_line = env->line_no;
  7575. env->start_col = env->col_no;
  7576. env->prev_line = env->start_line;
  7577. /* Redraw commandline for -- CHAR SELECTION -- */
  7578. redraw_commandline();
  7579. unhighlight_matching_paren();
  7580. /* Select single character */
  7581. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  7582. redraw_line(env->line_no-1);
  7583. }
  7584. BIM_ACTION(insert_at_end_of_selection, ACTION_IS_RW,
  7585. "Move the cursor to the end of the selection and enter insert mode."
  7586. )(void) {
  7587. recalculate_selected_lines();
  7588. if (env->line_no == env->start_line) {
  7589. env->col_no = env->col_no > env->start_col ? env->col_no + 1 : env->start_col + 1;
  7590. } else if (env->line_no < env->start_line) {
  7591. env->col_no = env->start_col + 1;
  7592. env->line_no = env->start_line;
  7593. } else {
  7594. env->col_no += 1;
  7595. }
  7596. env->mode = MODE_INSERT;
  7597. }
  7598. void free_completion_match(struct completion_match * match) {
  7599. if (match->string) free(match->string);
  7600. if (match->file) free(match->file);
  7601. if (match->search) free(match->search);
  7602. }
  7603. /**
  7604. * Read ctags file to find matches for a symbol
  7605. */
  7606. int read_tags(uint32_t * comp, struct completion_match **matches, int * matches_count, int complete_match) {
  7607. int _matches_len = 4;
  7608. int *matches_len = &_matches_len;
  7609. *matches_count = 0;
  7610. *matches = malloc(sizeof(struct completion_match) * (*matches_len));
  7611. FILE * tags = fopen("tags","r");
  7612. if (tags) {
  7613. char tmp[4096]; /* max line */
  7614. while (!feof(tags) && fgets(tmp, 4096, tags)) {
  7615. if (tmp[0] == '!') continue;
  7616. int i = 0;
  7617. while (comp[i] && comp[i] == (unsigned int)tmp[i]) i++;
  7618. if (comp[i] == '\0') {
  7619. if (complete_match && tmp[i] != '\t') continue;
  7620. int j = i;
  7621. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7622. tmp[j] = '\0'; j++;
  7623. char * file = &tmp[j];
  7624. while (tmp[j] != '\t' && tmp[j] != '\n' && tmp[j] != '\0') j++;
  7625. tmp[j] = '\0'; j++;
  7626. char * search = &tmp[j];
  7627. while (!(tmp[j] == '/' && tmp[j+1] == ';' && tmp[j+2] == '"' && tmp[j+3] == '\t') /* /normal searches/ */
  7628. && !(tmp[j] == ';' && tmp[j+1] == '"' && tmp[j+2] == '\t') /* Old ctags line number searches */
  7629. && (tmp[j] != '\n' && tmp[j] != '\0')) j++;
  7630. tmp[j] = '\0'; j++;
  7631. add_match(tmp,file,search);
  7632. }
  7633. }
  7634. fclose(tags);
  7635. }
  7636. /* TODO: Get these from syntax files with a dynamic callback */
  7637. if (env->syntax && env->syntax->completion_matcher) {
  7638. env->syntax->completion_matcher(comp,matches,matches_count,complete_match,matches_len);
  7639. }
  7640. return 0;
  7641. }
  7642. /**
  7643. * Draw an autocomplete popover with matches.
  7644. */
  7645. void draw_completion_matches(uint32_t * tmp, struct completion_match *matches, int matches_count, int index) {
  7646. int original_length = 0;
  7647. while (tmp[original_length]) original_length++;
  7648. int max_width = 0;
  7649. for (int i = 0; i < matches_count; ++i) {
  7650. /* TODO unicode width */
  7651. unsigned int my_width = strlen(matches[i].string) + (matches[i].file ? strlen(matches[i].file) + 1 : 0);
  7652. if (my_width > (unsigned int)max_width) {
  7653. max_width = my_width;
  7654. }
  7655. }
  7656. /* Figure out how much space we have to display the window */
  7657. int cursor_y = env->line_no - env->offset + global_config.tabs_visible;
  7658. int max_y = global_config.term_height - global_config.bottom_size - cursor_y;
  7659. /* Find a good place to put the box horizontally */
  7660. int num_size = num_width() + gutter_width();
  7661. int x = num_size + 1 - env->coffset;
  7662. /* Determine where the cursor is physically */
  7663. for (int i = 0; i < env->col_no - 1 - original_length; ++i) {
  7664. char_t * c = &env->lines[env->line_no-1]->text[i];
  7665. x += c->display_width;
  7666. }
  7667. int box_width = max_width;
  7668. int box_x = x;
  7669. int box_y = cursor_y + 1;
  7670. if (max_width > env->width - num_width() - gutter_width()) {
  7671. box_width = env->width - num_width() - gutter_width();
  7672. box_x = num_width() + gutter_width() + 1;
  7673. } else if (env->width - x < max_width) {
  7674. box_width = max_width;
  7675. box_x = env->width - max_width;
  7676. }
  7677. int max_count = (max_y < matches_count) ? max_y - 1 : matches_count;
  7678. for (int x = index; x < max_count+index; ++x) {
  7679. int i = x % matches_count;
  7680. place_cursor(box_x + env->left, box_y+x-index);
  7681. set_colors(COLOR_KEYWORD, COLOR_STATUS_BG);
  7682. /* TODO wide characters */
  7683. int match_width = strlen(matches[i].string);
  7684. int file_width = matches[i].file ? strlen(matches[i].file) : 0;
  7685. for (int j = 0; j < box_width; ++j) {
  7686. if (j == original_length) set_colors(i == index ? COLOR_NUMERAL : COLOR_STATUS_FG, COLOR_STATUS_BG);
  7687. if (j == match_width) set_colors(COLOR_TYPE, COLOR_STATUS_BG);
  7688. if (j < match_width) printf("%c", matches[i].string[j]);
  7689. else if (j > match_width && j - match_width - 1 < file_width) printf("%c", matches[i].file[j-match_width-1]);
  7690. else printf(" ");
  7691. }
  7692. }
  7693. if (max_count == 0) {
  7694. place_cursor(box_x + env->left, box_y);
  7695. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7696. printf(" (no matches) ");
  7697. } else if (max_count != matches_count) {
  7698. place_cursor(box_x + env->left, box_y+max_count);
  7699. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  7700. printf(" (%d more) ", matches_count-max_count);
  7701. }
  7702. }
  7703. /**
  7704. * Autocomplete words (function/variable names, etc.) in input mode.
  7705. */
  7706. int omni_complete(int quit_quietly_on_none) {
  7707. int c;
  7708. int (*qualifier)(int c) = simple_keyword_qualifier;
  7709. if (env->syntax && env->syntax->completion_qualifier) {
  7710. qualifier = env->syntax->completion_qualifier;
  7711. }
  7712. /* Pull the word from before the cursor */
  7713. int c_before = 0;
  7714. int i = env->col_no-1;
  7715. while (i > 0) {
  7716. int c = env->lines[env->line_no-1]->text[i-1].codepoint;
  7717. if (!qualifier(c)) break;
  7718. c_before++;
  7719. i--;
  7720. }
  7721. if (!c_before && quit_quietly_on_none) return 0;
  7722. /* Populate with characters */
  7723. uint32_t * tmp = malloc(sizeof(uint32_t) * (c_before+1));
  7724. int j = 0;
  7725. while (c_before) {
  7726. tmp[j] = env->lines[env->line_no-1]->text[env->col_no-c_before-1].codepoint;
  7727. c_before--;
  7728. j++;
  7729. }
  7730. tmp[j] = 0;
  7731. /*
  7732. * TODO matches should probably be a struct with more data than just
  7733. * the matching string; maybe offset where the needle was found,
  7734. * class information, source file information - anything we can extract
  7735. * from ctags, but also other information for other sources of completion.
  7736. */
  7737. struct completion_match *matches;
  7738. int matches_count;
  7739. /* TODO just reading ctags is rather mediocre; can we do something cool here? */
  7740. if (read_tags(tmp, &matches, &matches_count, 0)) goto _completion_done;
  7741. /* Draw box with matches at cursor-width(tmp) */
  7742. if (quit_quietly_on_none && matches_count == 0) return 0;
  7743. draw_completion_matches(tmp, matches, matches_count, 0);
  7744. int retval = 0;
  7745. int index = 0;
  7746. _completion_done:
  7747. place_cursor_actual();
  7748. while (1) {
  7749. c = bim_getch();
  7750. if (c == -1) continue;
  7751. if (matches_count < 1) {
  7752. redraw_all();
  7753. break;
  7754. }
  7755. if (c == 15) {
  7756. index = (index + 1) % matches_count;
  7757. draw_completion_matches(tmp, matches, matches_count, index);
  7758. place_cursor_actual();
  7759. continue;
  7760. } else if (c == '\t') {
  7761. for (unsigned int i = j; i < strlen(matches[index].string); ++i) {
  7762. insert_char(matches[index].string[i]);
  7763. }
  7764. set_preferred_column();
  7765. redraw_text();
  7766. place_cursor_actual();
  7767. goto _finish_completion;
  7768. } else if (isgraph(c) && c != '}') {
  7769. /* insert and continue matching */
  7770. insert_char(c);
  7771. set_preferred_column();
  7772. redraw_text();
  7773. place_cursor_actual();
  7774. retval = 1;
  7775. goto _finish_completion;
  7776. } else if (c == DELETE_KEY || c == BACKSPACE_KEY) {
  7777. delete_at_cursor();
  7778. set_preferred_column();
  7779. redraw_text();
  7780. place_cursor_actual();
  7781. retval = 1;
  7782. goto _finish_completion;
  7783. }
  7784. /* TODO: Keyboard navigation of the matches list would be nice */
  7785. redraw_all();
  7786. break;
  7787. }
  7788. bim_unget(c);
  7789. _finish_completion:
  7790. for (int i = 0; i < matches_count; ++i) {
  7791. free_completion_match(&matches[i]);
  7792. }
  7793. free(matches);
  7794. free(tmp);
  7795. return retval;
  7796. }
  7797. /**
  7798. * Set the search string from a UTF-8 sequence.
  7799. * Since the search string is normally a series of codepoints, this saves
  7800. * some effort when trying to search for things we pulled from the outside world.
  7801. * (eg., ctags search terms)
  7802. */
  7803. void set_search_from_bytes(char * bytes) {
  7804. if (global_config.search) free(global_config.search);
  7805. global_config.search = malloc(sizeof(uint32_t) * (strlen(bytes) + 1));
  7806. uint32_t * s = global_config.search;
  7807. char * tmp = bytes;
  7808. uint32_t c, istate = 0;
  7809. while (*tmp) {
  7810. if (!decode(&istate, &c, *tmp)) {
  7811. *s = c;
  7812. s++;
  7813. *s = 0;
  7814. } else if (istate == UTF8_REJECT) {
  7815. istate = 0;
  7816. }
  7817. tmp++;
  7818. }
  7819. }
  7820. BIM_ACTION(goto_definition, 0,
  7821. "Jump to the definition of the word under under cursor."
  7822. )(void) {
  7823. uint32_t * word = get_word_under_cursor();
  7824. if (!word) {
  7825. render_error("No match");
  7826. return;
  7827. }
  7828. struct completion_match *matches;
  7829. int matches_count;
  7830. if (read_tags(word, &matches, &matches_count, 1)) {
  7831. render_error("No tags file");
  7832. goto _done;
  7833. }
  7834. if (!matches_count) {
  7835. render_error("No match");
  7836. goto _done;
  7837. }
  7838. #define _perform_correct_search(i) do { \
  7839. if (matches[i].search[0] == '/') { \
  7840. set_search_from_bytes(&matches[i].search[1]); \
  7841. search_next(); \
  7842. } else { \
  7843. goto_line(atoi(matches[i].search)); \
  7844. } \
  7845. } while (0)
  7846. if (env->file_name && !strcmp(matches[0].file, env->file_name)) {
  7847. _perform_correct_search(0);
  7848. } else {
  7849. /* Check if there were other matches that are in this file */
  7850. for (int i =1; env->file_name && i < matches_count; ++i) {
  7851. if (!strcmp(matches[i].file, env->file_name)) {
  7852. _perform_correct_search(i);
  7853. goto _done;
  7854. }
  7855. }
  7856. /* Check buffers */
  7857. for (int i = 0; i < buffers_len; ++i) {
  7858. if (buffers[i]->file_name && !strcmp(matches[0].file,buffers[i]->file_name)) {
  7859. if (left_buffer && buffers[i] != left_buffer && buffers[i] != right_buffer) unsplit();
  7860. env = buffers[i];
  7861. redraw_tabbar();
  7862. _perform_correct_search(i);
  7863. goto _done;
  7864. }
  7865. }
  7866. /* Okay, let's try opening */
  7867. buffer_t * old_buf = env;
  7868. open_file(matches[0].file);
  7869. if (env != old_buf) {
  7870. _perform_correct_search(0);
  7871. } else {
  7872. render_error("Could not locate file containing definition");
  7873. }
  7874. }
  7875. _done:
  7876. for (int i = 0; i < matches_count; ++i) {
  7877. free_completion_match(&matches[i]);
  7878. }
  7879. free(matches);
  7880. free(word);
  7881. }
  7882. /**
  7883. * Read one codepoint, with verbatim support.
  7884. */
  7885. int read_one_character(char * message) {
  7886. /* Read one character and replace */
  7887. if (!global_config.overlay_mode) {
  7888. render_commandline_message(message);
  7889. place_cursor_actual();
  7890. }
  7891. int c;
  7892. while ((c = bim_getkey(200))) {
  7893. if (c == KEY_TIMEOUT) continue;
  7894. if (c == KEY_CTRL_V) {
  7895. if (!global_config.overlay_mode) {
  7896. render_commandline_message(message);
  7897. printf(" ^V");
  7898. place_cursor_actual();
  7899. }
  7900. while ((c = bim_getch()) == -1);
  7901. break;
  7902. }
  7903. break;
  7904. }
  7905. redraw_commandline();
  7906. return c;
  7907. }
  7908. int read_one_byte(char * message) {
  7909. if (!global_config.overlay_mode) {
  7910. render_commandline_message(message);
  7911. place_cursor_actual();
  7912. }
  7913. int c;
  7914. while ((c = bim_getch())) {
  7915. if (c == -1) continue;
  7916. break;
  7917. }
  7918. redraw_commandline();
  7919. return c;
  7920. }
  7921. BIM_ACTION(cursor_left_with_wrap, 0,
  7922. "Move the cursor one position left, wrapping to the previous line."
  7923. )(void) {
  7924. if (env->line_no > 1 && env->col_no == 1) {
  7925. env->line_no--;
  7926. env->col_no = env->lines[env->line_no-1]->actual;
  7927. set_preferred_column();
  7928. place_cursor_actual();
  7929. } else {
  7930. cursor_left();
  7931. }
  7932. }
  7933. BIM_ACTION(prepend_and_insert, ACTION_IS_RW,
  7934. "Insert a new line before the current line and enter insert mode."
  7935. )(void) {
  7936. set_history_break();
  7937. env->lines = add_line(env->lines, env->line_no-1);
  7938. env->col_no = 1;
  7939. add_indent(env->line_no-1,env->line_no,0);
  7940. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7941. redraw_text();
  7942. set_preferred_column();
  7943. set_modified();
  7944. place_cursor_actual();
  7945. env->mode = MODE_INSERT;
  7946. }
  7947. BIM_ACTION(append_and_insert, ACTION_IS_RW,
  7948. "Insert a new line after the current line and enter insert mode."
  7949. )(void) {
  7950. set_history_break();
  7951. env->lines = add_line(env->lines, env->line_no);
  7952. env->col_no = 1;
  7953. env->line_no += 1;
  7954. add_indent(env->line_no-1,env->line_no-2,0);
  7955. set_preferred_column();
  7956. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  7957. env->offset += 1;
  7958. }
  7959. if (env->highlighting_paren && env->highlighting_paren > env->line_no) env->highlighting_paren++;
  7960. redraw_text();
  7961. set_modified();
  7962. place_cursor_actual();
  7963. env->mode = MODE_INSERT;
  7964. }
  7965. BIM_ACTION(insert_after_cursor, ACTION_IS_RW,
  7966. "Place the cursor after the selected character and enter insert mode."
  7967. )(void) {
  7968. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  7969. env->col_no += 1;
  7970. }
  7971. enter_insert();
  7972. }
  7973. BIM_ACTION(delete_forward, ACTION_IS_RW,
  7974. "Delete the character under the cursor."
  7975. )(void) {
  7976. if (env->col_no <= env->lines[env->line_no-1]->actual) {
  7977. line_delete(env->lines[env->line_no-1], env->col_no, env->line_no-1);
  7978. redraw_text();
  7979. } else if (env->col_no == env->lines[env->line_no-1]->actual + 1 && env->line_count > env->line_no) {
  7980. merge_lines(env->lines, env->line_no);
  7981. redraw_text();
  7982. }
  7983. set_modified();
  7984. redraw_statusbar();
  7985. place_cursor_actual();
  7986. }
  7987. BIM_ACTION(delete_forward_and_insert, ACTION_IS_RW,
  7988. "Delete the character under the cursor and enter insert mode."
  7989. )(void) {
  7990. set_history_break();
  7991. delete_forward();
  7992. env->mode = MODE_INSERT;
  7993. }
  7994. BIM_ACTION(paste, ARG_IS_CUSTOM | ACTION_IS_RW,
  7995. "Paste yanked text before (`P`) or after (`p`) the cursor."
  7996. )(int direction) {
  7997. if (global_config.yanks) {
  7998. if (!global_config.yank_is_full_lines) {
  7999. /* Handle P for paste before, p for past after */
  8000. int target_column = (direction == -1 ? (env->col_no) : (env->col_no+1));
  8001. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  8002. target_column = env->lines[env->line_no-1]->actual + 1;
  8003. }
  8004. if (global_config.yank_count > 1) {
  8005. /* Spit the current line at the current position */
  8006. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  8007. }
  8008. /* Insert first line at current position */
  8009. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  8010. 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);
  8011. }
  8012. if (global_config.yank_count > 1) {
  8013. /* Insert full lines */
  8014. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8015. env->lines = add_line(env->lines, env->line_no);
  8016. }
  8017. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  8018. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  8019. }
  8020. /* Insert characters from last line into (what was) the next line */
  8021. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  8022. 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);
  8023. }
  8024. }
  8025. } else {
  8026. /* Insert full lines */
  8027. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8028. env->lines = add_line(env->lines, env->line_no - (direction == -1 ? 1 : 0));
  8029. }
  8030. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  8031. replace_line(env->lines, env->line_no - (direction == -1 ? 1 : 0) + i, global_config.yanks[i]);
  8032. }
  8033. }
  8034. /* Recalculate whole document syntax */
  8035. for (int i = 0; i < env->line_count; ++i) {
  8036. env->lines[i]->istate = 0;
  8037. }
  8038. for (int i = 0; i < env->line_count; ++i) {
  8039. recalculate_syntax(env->lines[i],i);
  8040. }
  8041. if (direction == 1) {
  8042. if (global_config.yank_is_full_lines) {
  8043. env->line_no += 1;
  8044. } else {
  8045. if (global_config.yank_count == 1) {
  8046. env->col_no = env->col_no + global_config.yanks[0]->actual;
  8047. } else {
  8048. env->line_no = env->line_no + global_config.yank_count - 1;
  8049. env->col_no = global_config.yanks[global_config.yank_count-1]->actual;
  8050. }
  8051. }
  8052. }
  8053. if (global_config.yank_is_full_lines) {
  8054. env->col_no = 1;
  8055. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8056. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8057. env->col_no = i + 1;
  8058. break;
  8059. }
  8060. }
  8061. }
  8062. set_history_break();
  8063. set_modified();
  8064. redraw_all();
  8065. }
  8066. }
  8067. BIM_ACTION(insert_at_end, ACTION_IS_RW,
  8068. "Move the cursor to the end of the current line and enter insert mode."
  8069. )(void) {
  8070. env->col_no = env->lines[env->line_no-1]->actual+1;
  8071. env->mode = MODE_INSERT;
  8072. set_history_break();
  8073. }
  8074. BIM_ACTION(enter_replace, ACTION_IS_RW,
  8075. "Enter replace mode."
  8076. )(void) {
  8077. env->mode = MODE_REPLACE;
  8078. set_history_break();
  8079. }
  8080. BIM_ACTION(toggle_numbers, 0,
  8081. "Toggle the display of line numbers."
  8082. )(void) {
  8083. env->numbers = !env->numbers;
  8084. redraw_all();
  8085. place_cursor_actual();
  8086. }
  8087. BIM_ACTION(toggle_gutter, 0,
  8088. "Toggle the display of the revision status gutter."
  8089. )(void) {
  8090. env->gutter = !env->gutter;
  8091. redraw_all();
  8092. place_cursor_actual();
  8093. }
  8094. BIM_ACTION(toggle_indent, 0,
  8095. "Toggle smart indentation."
  8096. )(void) {
  8097. env->indent = !env->indent;
  8098. redraw_statusbar();
  8099. place_cursor_actual();
  8100. }
  8101. BIM_ACTION(toggle_smartcomplete, 0,
  8102. "Toggle smart completion."
  8103. )(void) {
  8104. global_config.smart_complete = !global_config.smart_complete;
  8105. redraw_statusbar();
  8106. place_cursor_actual();
  8107. }
  8108. BIM_ACTION(expand_split_right, 0,
  8109. "Move the view split divider to the right."
  8110. )(void) {
  8111. global_config.split_percent += 1;
  8112. update_split_size();
  8113. redraw_all();
  8114. }
  8115. BIM_ACTION(expand_split_left, 0,
  8116. "Move the view split divider to the left."
  8117. )(void) {
  8118. global_config.split_percent -= 1;
  8119. update_split_size();
  8120. redraw_all();
  8121. }
  8122. BIM_ACTION(go_page_up, 0,
  8123. "Jump up a screenful."
  8124. )(void) {
  8125. goto_line(env->line_no - (global_config.term_height - 6));
  8126. }
  8127. BIM_ACTION(go_page_down, 0,
  8128. "Jump down a screenful."
  8129. )(void) {
  8130. goto_line(env->line_no + (global_config.term_height - 6));
  8131. }
  8132. BIM_ACTION(jump_to_matching_bracket, 0,
  8133. "Find and jump to the matching bracket for the character under the cursor."
  8134. )(void) {
  8135. recalculate_selected_lines();
  8136. int paren_line = -1, paren_col = -1;
  8137. find_matching_paren(&paren_line, &paren_col, 1);
  8138. if (paren_line != -1) {
  8139. env->line_no = paren_line;
  8140. env->col_no = paren_col;
  8141. set_preferred_column();
  8142. place_cursor_actual();
  8143. redraw_statusbar();
  8144. }
  8145. }
  8146. BIM_ACTION(jump_to_previous_blank, 0,
  8147. "Jump to the preceding blank line before the cursor."
  8148. )(void) {
  8149. env->col_no = 1;
  8150. if (env->line_no == 1) return;
  8151. do {
  8152. env->line_no--;
  8153. if (env->lines[env->line_no-1]->actual == 0) break;
  8154. } while (env->line_no > 1);
  8155. set_preferred_column();
  8156. redraw_statusbar();
  8157. }
  8158. BIM_ACTION(jump_to_next_blank, 0,
  8159. "Jump to the next blank line after the cursor."
  8160. )(void) {
  8161. env->col_no = 1;
  8162. if (env->line_no == env->line_count) return;
  8163. do {
  8164. env->line_no++;
  8165. if (env->lines[env->line_no-1]->actual == 0) break;
  8166. } while (env->line_no < env->line_count);
  8167. set_preferred_column();
  8168. redraw_statusbar();
  8169. }
  8170. BIM_ACTION(first_non_whitespace, 0,
  8171. "Jump to the first non-whitespace character in the current line."
  8172. )(void) {
  8173. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8174. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) {
  8175. env->col_no = i + 1;
  8176. break;
  8177. }
  8178. }
  8179. set_preferred_column();
  8180. redraw_statusbar();
  8181. }
  8182. BIM_ACTION(next_line_non_whitespace, 0,
  8183. "Jump to the first non-whitespace character in the next next line."
  8184. )(void) {
  8185. if (env->line_no < env->line_count) {
  8186. env->line_no++;
  8187. env->col_no = 1;
  8188. } else {
  8189. return;
  8190. }
  8191. first_non_whitespace();
  8192. }
  8193. BIM_ACTION(smart_backspace, ACTION_IS_RW,
  8194. "Delete the preceding character, with special handling for indentation."
  8195. )(void) {
  8196. if (!env->tabs && env->col_no > 1) {
  8197. int i;
  8198. for (i = 0; i < env->col_no-1; ++i) {
  8199. if (!is_whitespace(env->lines[env->line_no-1]->text[i].codepoint)) break;
  8200. }
  8201. if (i == env->col_no-1) {
  8202. /* Backspace until aligned */
  8203. delete_at_cursor();
  8204. while (env->col_no > 1 && (env->col_no-1) % env->tabstop) {
  8205. delete_at_cursor();
  8206. }
  8207. return;
  8208. }
  8209. }
  8210. delete_at_cursor();
  8211. }
  8212. BIM_ACTION(perform_omni_completion, ACTION_IS_RW,
  8213. "(temporary) Perform smart symbol competion from ctags."
  8214. )(void) {
  8215. /* This should probably be a submode */
  8216. while (omni_complete(0) == 1);
  8217. }
  8218. BIM_ACTION(smart_tab, ACTION_IS_RW,
  8219. "Insert a tab or spaces depending on indent mode. (Use ^V <tab> to guarantee a literal tab)"
  8220. )(void) {
  8221. if (env->tabs) {
  8222. insert_char('\t');
  8223. } else {
  8224. for (int i = 0; i < env->tabstop; ++i) {
  8225. insert_char(' ');
  8226. }
  8227. }
  8228. }
  8229. BIM_ACTION(smart_comment_end, ARG_IS_INPUT | ACTION_IS_RW,
  8230. "Insert a `/` ending a C-style comment."
  8231. )(int c) {
  8232. /* smart *end* of comment anyway */
  8233. if (env->indent) {
  8234. if ((env->lines[env->line_no-1]->text[env->col_no-2].flags & 0x1F) == FLAG_COMMENT &&
  8235. (env->lines[env->line_no-1]->text[env->col_no-2].codepoint == ' ') &&
  8236. (env->col_no > 3) &&
  8237. (env->lines[env->line_no-1]->text[env->col_no-3].codepoint == '*')) {
  8238. env->col_no--;
  8239. replace_char('/');
  8240. env->col_no++;
  8241. place_cursor_actual();
  8242. return;
  8243. }
  8244. }
  8245. insert_char(c);
  8246. }
  8247. BIM_ACTION(smart_brace_end, ARG_IS_INPUT | ACTION_IS_RW,
  8248. "Insert a closing brace and smartly position it if it is the first character on a line."
  8249. )(int c) {
  8250. if (env->indent) {
  8251. int was_whitespace = 1;
  8252. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  8253. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  8254. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  8255. was_whitespace = 0;
  8256. break;
  8257. }
  8258. }
  8259. insert_char(c);
  8260. if (was_whitespace) {
  8261. int line = -1, col = -1;
  8262. env->col_no--;
  8263. find_matching_paren(&line,&col, 1);
  8264. if (line != -1) {
  8265. line = find_brace_line_start(line, col);
  8266. while (env->lines[env->line_no-1]->actual) {
  8267. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  8268. }
  8269. add_indent(env->line_no-1,line-1,1);
  8270. env->col_no = env->lines[env->line_no-1]->actual + 1;
  8271. insert_char(c);
  8272. }
  8273. }
  8274. set_preferred_column();
  8275. return;
  8276. }
  8277. insert_char(c);
  8278. }
  8279. BIM_ACTION(enter_line_selection_and_cursor_up, 0,
  8280. "Enter line selection and move the cursor up one line."
  8281. )(void) {
  8282. enter_line_selection();
  8283. cursor_up();
  8284. }
  8285. BIM_ACTION(enter_line_selection_and_cursor_down, 0,
  8286. "Enter line selection and move the cursor down one line."
  8287. )(void) {
  8288. enter_line_selection();
  8289. cursor_down();
  8290. }
  8291. BIM_ACTION(shift_horizontally, ARG_IS_CUSTOM,
  8292. "Shift the current line or screen view horiztonally, depending on settings."
  8293. )(int amount) {
  8294. env->coffset += amount;
  8295. if (env->coffset < 0) env->coffset = 0;
  8296. redraw_text();
  8297. }
  8298. struct action_map _NORMAL_MAP[] = {
  8299. {KEY_BACKSPACE, cursor_left_with_wrap, opt_rep, 0},
  8300. {'V', enter_line_selection, 0, 0},
  8301. {'v', enter_char_selection, 0, 0},
  8302. {KEY_CTRL_V, enter_col_selection, 0, 0},
  8303. {'O', prepend_and_insert, opt_rw, 0},
  8304. {'o', append_and_insert, opt_rw, 0},
  8305. {'a', insert_after_cursor, opt_rw, 0},
  8306. {'s', delete_forward_and_insert, opt_rw, 0},
  8307. {'x', delete_forward, opt_rep | opt_rw, 0},
  8308. {'P', paste, opt_arg | opt_rw, -1},
  8309. {'p', paste, opt_arg | opt_rw, 1},
  8310. {'r', replace_char, opt_char | opt_rw, 0},
  8311. {'A', insert_at_end, opt_rw, 0},
  8312. {'u', undo_history, opt_rw, 0},
  8313. {KEY_CTRL_R, redo_history, opt_rw, 0},
  8314. {KEY_CTRL_L, redraw_all, 0, 0},
  8315. {KEY_CTRL_G, goto_definition, 0, 0},
  8316. {'i', enter_insert, opt_rw, 0},
  8317. {'R', enter_replace, opt_rw, 0},
  8318. {KEY_SHIFT_UP, enter_line_selection_and_cursor_up, 0, 0},
  8319. {KEY_SHIFT_DOWN, enter_line_selection_and_cursor_down, 0, 0},
  8320. {KEY_ALT_UP, previous_tab, 0, 0},
  8321. {KEY_ALT_DOWN, next_tab, 0, 0},
  8322. {-1, NULL, 0, 0},
  8323. };
  8324. struct action_map _INSERT_MAP[] = {
  8325. {KEY_ESCAPE, leave_insert, 0, 0},
  8326. {KEY_DELETE, delete_forward, 0, 0},
  8327. {KEY_CTRL_C, leave_insert, 0, 0},
  8328. {KEY_BACKSPACE, smart_backspace, 0, 0},
  8329. {KEY_ENTER, insert_line_feed, 0, 0},
  8330. {KEY_CTRL_O, perform_omni_completion, 0, 0},
  8331. {KEY_CTRL_V, insert_char, opt_byte, 0},
  8332. {KEY_CTRL_W, delete_word, 0, 0},
  8333. {'\t', smart_tab, 0, 0},
  8334. {'/', smart_comment_end, opt_arg, '/'},
  8335. {'}', smart_brace_end, opt_arg, '}'},
  8336. {-1, NULL, 0, 0},
  8337. };
  8338. struct action_map _REPLACE_MAP[] = {
  8339. {KEY_ESCAPE, leave_insert, 0, 0},
  8340. {KEY_DELETE, delete_forward, 0, 0},
  8341. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8342. {KEY_ENTER, insert_line_feed, 0, 0},
  8343. {-1, NULL, 0, 0},
  8344. };
  8345. struct action_map _LINE_SELECTION_MAP[] = {
  8346. {KEY_ESCAPE, leave_selection, 0, 0},
  8347. {KEY_CTRL_C, leave_selection, 0, 0},
  8348. {'V', leave_selection, 0, 0},
  8349. {'v', switch_selection_mode, opt_arg, MODE_CHAR_SELECTION},
  8350. {'y', yank_lines, opt_norm, 0},
  8351. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8352. {'\t', adjust_indent, opt_arg | opt_rw, 1},
  8353. {KEY_SHIFT_TAB, adjust_indent, opt_arg | opt_rw, -1},
  8354. {'D', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8355. {'d', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8356. {'x', delete_and_yank_lines, opt_rw | opt_norm, 0},
  8357. {'s', delete_lines_and_enter_insert, opt_rw, 0},
  8358. {'r', replace_chars_in_line, opt_char | opt_rw, 0},
  8359. {KEY_SHIFT_UP, cursor_up, 0, 0},
  8360. {KEY_SHIFT_DOWN, cursor_down, 0, 0},
  8361. {-1, NULL, 0, 0},
  8362. };
  8363. struct action_map _CHAR_SELECTION_MAP[] = {
  8364. {KEY_ESCAPE, leave_selection, 0, 0},
  8365. {KEY_CTRL_C, leave_selection, 0, 0},
  8366. {'v', leave_selection, 0, 0},
  8367. {'V', switch_selection_mode, opt_arg, MODE_LINE_SELECTION},
  8368. {'y', yank_characters, opt_norm, 0},
  8369. {KEY_BACKSPACE, cursor_left_with_wrap, 0, 0},
  8370. {'D', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8371. {'d', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8372. {'x', delete_and_yank_chars, opt_rw | opt_norm, 0},
  8373. {'s', delete_chars_and_enter_insert, opt_rw, 0},
  8374. {'r', replace_chars, opt_char | opt_rw, 0},
  8375. {'A', insert_at_end_of_selection, opt_rw, 0},
  8376. {-1, NULL, 0, 0},
  8377. };
  8378. struct action_map _COL_SELECTION_MAP[] = {
  8379. {KEY_ESCAPE, leave_selection, 0, 0},
  8380. {KEY_CTRL_C, leave_selection, 0, 0},
  8381. {KEY_CTRL_V, leave_selection, 0, 0},
  8382. {'I', enter_col_insert, opt_rw, 0},
  8383. {'a', enter_col_insert_after, opt_rw, 0},
  8384. {'d', delete_column, opt_norm | opt_rw, 0},
  8385. {-1, NULL, 0, 0},
  8386. };
  8387. struct action_map _COL_INSERT_MAP[] = {
  8388. {KEY_ESCAPE, leave_selection, 0, 0},
  8389. {KEY_CTRL_C, leave_selection, 0, 0},
  8390. {KEY_BACKSPACE, delete_at_column, opt_arg, -1},
  8391. {KEY_DELETE, delete_at_column, opt_arg, 1},
  8392. {KEY_ENTER, NULL, 0, 0},
  8393. {KEY_CTRL_W, NULL, 0, 0},
  8394. {KEY_CTRL_V, insert_char_at_column, opt_char, 0},
  8395. {-1, NULL, 0, 0},
  8396. };
  8397. struct action_map _NAVIGATION_MAP[] = {
  8398. /* Common navigation */
  8399. {KEY_CTRL_B, go_page_up, opt_rep, 0},
  8400. {KEY_CTRL_F, go_page_down, opt_rep, 0},
  8401. {':', enter_command, 0, 0},
  8402. {'/', enter_search, opt_arg, 1},
  8403. {'?', enter_search, opt_arg, 0},
  8404. {'n', search_next, opt_rep, 0},
  8405. {'N', search_prev, opt_rep, 0},
  8406. {'j', cursor_down, opt_rep, 0},
  8407. {'k', cursor_up, opt_rep, 0},
  8408. {'h', cursor_left, opt_rep, 0},
  8409. {'l', cursor_right, opt_rep, 0},
  8410. {'b', word_left, opt_rep, 0},
  8411. {'w', word_right, opt_rep, 0},
  8412. {'B', big_word_left, opt_rep, 0},
  8413. {'W', big_word_right, opt_rep, 0},
  8414. {'<', shift_horizontally, opt_arg, -1},
  8415. {'>', shift_horizontally, opt_arg, 1},
  8416. {'f', find_character_forward, opt_rep | opt_arg | opt_char, 'f'},
  8417. {'F', find_character_backward, opt_rep | opt_arg | opt_char, 'F'},
  8418. {'t', find_character_forward, opt_rep | opt_arg | opt_char, 't'},
  8419. {'T', find_character_backward, opt_rep | opt_arg | opt_char, 'T'},
  8420. {'G', goto_line, opt_nav, 0},
  8421. {'*', search_under_cursor, 0, 0},
  8422. {' ', go_page_down, opt_rep, 0},
  8423. {'%', jump_to_matching_bracket, 0, 0},
  8424. {'{', jump_to_previous_blank, opt_rep, 0},
  8425. {'}', jump_to_next_blank, opt_rep, 0},
  8426. {'$', cursor_end, 0, 0},
  8427. {'|', cursor_home, 0, 0},
  8428. {KEY_ENTER, next_line_non_whitespace, opt_rep, 0},
  8429. {'^', first_non_whitespace, 0, 0},
  8430. {'0', cursor_home, 0, 0},
  8431. {-1, NULL, 0, 0},
  8432. };
  8433. struct action_map _ESCAPE_MAP[] = {
  8434. {KEY_F1, toggle_numbers, 0, 0},
  8435. {KEY_F2, toggle_indent, 0, 0},
  8436. {KEY_F3, toggle_gutter, 0, 0},
  8437. {KEY_F4, toggle_smartcomplete, 0, 0},
  8438. {KEY_MOUSE, handle_mouse, 0, 0},
  8439. {KEY_MOUSE_SGR, handle_mouse_sgr, 0, 0},
  8440. {KEY_UP, cursor_up, opt_rep, 0},
  8441. {KEY_DOWN, cursor_down, opt_rep, 0},
  8442. {KEY_RIGHT, cursor_right, opt_rep, 0},
  8443. {KEY_CTRL_RIGHT, big_word_right, opt_rep, 0},
  8444. {KEY_SHIFT_RIGHT, word_right, opt_rep, 0},
  8445. {KEY_ALT_RIGHT, expand_split_right, opt_rep, 0},
  8446. {KEY_ALT_SHIFT_RIGHT, use_right_buffer, opt_rep, 0},
  8447. {KEY_LEFT, cursor_left, opt_rep, 0},
  8448. {KEY_CTRL_LEFT, big_word_left, opt_rep, 0},
  8449. {KEY_SHIFT_LEFT, word_left, opt_rep, 0},
  8450. {KEY_ALT_LEFT, expand_split_left, opt_rep, 0},
  8451. {KEY_ALT_SHIFT_LEFT, use_left_buffer, opt_rep, 0},
  8452. {KEY_HOME, cursor_home, 0, 0},
  8453. {KEY_END, cursor_end, 0, 0},
  8454. {KEY_PAGE_UP, go_page_up, opt_rep, 0},
  8455. {KEY_PAGE_DOWN, go_page_down, opt_rep, 0},
  8456. {KEY_CTRL_Z, suspend, 0, 0},
  8457. {-1, NULL, 0, 0}
  8458. };
  8459. struct action_map _COMMAND_MAP[] = {
  8460. {KEY_ENTER, command_accept, 0, 0},
  8461. {'\t', command_tab_complete_buffer, 0, 0},
  8462. {KEY_UP, command_scroll_history, opt_arg, -1}, /* back */
  8463. {KEY_DOWN, command_scroll_history, opt_arg, 1}, /* forward */
  8464. {-1, NULL, 0, 0}
  8465. };
  8466. struct action_map _SEARCH_MAP[] = {
  8467. {KEY_ENTER, search_accept, 0, 0},
  8468. {KEY_UP, NULL, 0, 0},
  8469. {KEY_DOWN, NULL, 0, 0},
  8470. {-1, NULL, 0, 0}
  8471. };
  8472. struct action_map _INPUT_BUFFER_MAP[] = {
  8473. /* These are generic and shared with search */
  8474. {KEY_ESCAPE, command_discard, 0, 0},
  8475. {KEY_CTRL_C, command_discard, 0, 0},
  8476. {KEY_BACKSPACE, command_backspace, 0, 0},
  8477. {KEY_CTRL_W, command_word_delete, 0, 0},
  8478. {KEY_MOUSE, eat_mouse, 0, 0},
  8479. {KEY_LEFT, command_cursor_left, 0, 0},
  8480. {KEY_CTRL_LEFT, command_word_left, 0, 0},
  8481. {KEY_RIGHT, command_cursor_right, 0, 0},
  8482. {KEY_CTRL_RIGHT,command_word_right, 0, 0},
  8483. {KEY_HOME, command_cursor_home, 0, 0},
  8484. {KEY_END, command_cursor_end, 0, 0},
  8485. {-1, NULL, 0, 0}
  8486. };
  8487. /* DIRECTORY_BROWSE_MAP is only to override KEY_ENTER and should not be remapped,
  8488. * so unlike the others it is not going to be redefined as a pointer. */
  8489. struct action_map DIRECTORY_BROWSE_MAP[] = {
  8490. {KEY_ENTER, open_file_from_line, 0, 0},
  8491. {-1, NULL, 0, 0}
  8492. };
  8493. struct action_map * NORMAL_MAP = NULL;
  8494. struct action_map * INSERT_MAP = NULL;
  8495. struct action_map * REPLACE_MAP = NULL;
  8496. struct action_map * LINE_SELECTION_MAP = NULL;
  8497. struct action_map * CHAR_SELECTION_MAP = NULL;
  8498. struct action_map * COL_SELECTION_MAP = NULL;
  8499. struct action_map * COL_INSERT_MAP = NULL;
  8500. struct action_map * NAVIGATION_MAP = NULL;
  8501. struct action_map * ESCAPE_MAP = NULL;
  8502. struct action_map * COMMAND_MAP = NULL;
  8503. struct action_map * SEARCH_MAP = NULL;
  8504. struct action_map * INPUT_BUFFER_MAP = NULL;
  8505. struct mode_names mode_names[] = {
  8506. {"Normal","norm",&NORMAL_MAP},
  8507. {"Insert","insert",&INSERT_MAP},
  8508. {"Replace","replace",&REPLACE_MAP},
  8509. {"Line Selection","line",&LINE_SELECTION_MAP},
  8510. {"Char Selection","char",&CHAR_SELECTION_MAP},
  8511. {"Col Selection","col",&COL_SELECTION_MAP},
  8512. {"Col Insert","colinsert",&COL_INSERT_MAP},
  8513. {"Navigation (Select)","nav",&NAVIGATION_MAP},
  8514. {"Escape (Select, Insert)","esc",&ESCAPE_MAP},
  8515. {"Command","command",&COMMAND_MAP},
  8516. {"Search","search",&SEARCH_MAP},
  8517. {"Input (Command, Search)","input",&INPUT_BUFFER_MAP},
  8518. {NULL,NULL,NULL},
  8519. };
  8520. int handle_action(struct action_map * basemap, int key) {
  8521. for (struct action_map * map = basemap; map->key != -1; map++) {
  8522. if (map->key == key) {
  8523. if (!map->method) return 1;
  8524. if ((map->options & opt_rw) && (env->readonly)) {
  8525. render_error("Buffer is read-only");
  8526. return 2;
  8527. }
  8528. /* Determine how to format this request */
  8529. int reps = (map->options & opt_rep) ? ((nav_buffer) ? atoi(nav_buf) : 1) : 1;
  8530. int c = 0;
  8531. if (map->options & opt_char) {
  8532. c = read_one_character(name_from_key(key));
  8533. }
  8534. if (map->options & opt_byte) {
  8535. c = read_one_byte(name_from_key(key));
  8536. }
  8537. for (int i = 0; i < reps; ++i) {
  8538. if (((map->options & opt_char) || (map->options & opt_byte)) && (map->options & opt_arg)) {
  8539. map->method(map->arg, c);
  8540. } else if ((map->options & opt_char) || (map->options & opt_byte)) {
  8541. map->method(c);
  8542. } else if (map->options & opt_arg) {
  8543. map->method(map->arg);
  8544. } else if (map->options & opt_nav) {
  8545. if (nav_buffer) {
  8546. map->method(atoi(nav_buf));
  8547. reset_nav_buffer(0);
  8548. } else {
  8549. map->method(-1);
  8550. }
  8551. } else {
  8552. map->method();
  8553. }
  8554. }
  8555. if (map->options & opt_norm) {
  8556. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) leave_insert();
  8557. else if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION || env->mode == MODE_COL_SELECTION) leave_selection();
  8558. else {
  8559. env->mode = MODE_NORMAL;
  8560. redraw_all();
  8561. }
  8562. }
  8563. return 1;
  8564. }
  8565. }
  8566. return 0;
  8567. }
  8568. int handle_nav_buffer(int key) {
  8569. if ((key >= '1' && key <= '9') || (key == '0' && nav_buffer)) {
  8570. if (nav_buffer < NAV_BUFFER_MAX) {
  8571. /* Up to NAV_BUFFER_MAX=10 characters; that should be enough for most tasks */
  8572. nav_buf[nav_buffer] = key;
  8573. nav_buf[nav_buffer+1] = 0;
  8574. nav_buffer++;
  8575. /* Print the number buffer */
  8576. redraw_commandline();
  8577. }
  8578. return 0;
  8579. }
  8580. return 1;
  8581. }
  8582. /**
  8583. * NORMAL mode
  8584. *
  8585. * Default editor mode - just cursor navigation and keybinds
  8586. * to enter the other modes.
  8587. */
  8588. void normal_mode(void) {
  8589. int last_mode = MODE_NORMAL;
  8590. int refresh = 0;
  8591. while (1) {
  8592. if (global_config.overlay_mode) {
  8593. if (global_config.overlay_mode == OVERLAY_MODE_COMMAND) {
  8594. if (refresh) {
  8595. render_command_input_buffer();
  8596. refresh = 0;
  8597. }
  8598. int key = bim_getkey(200);
  8599. if (key != KEY_TIMEOUT) {
  8600. refresh = 1;
  8601. if (!handle_action(COMMAND_MAP, key))
  8602. if (!handle_action(INPUT_BUFFER_MAP, key))
  8603. if (key < KEY_ESCAPE) command_insert_char(key);
  8604. }
  8605. continue;
  8606. } else if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8607. if (refresh) {
  8608. render_command_input_buffer();
  8609. refresh = 0;
  8610. }
  8611. int key = bim_getkey(200);
  8612. if (key != KEY_TIMEOUT) {
  8613. refresh = 1;
  8614. if (!handle_action(SEARCH_MAP, key)) {
  8615. if (!handle_action(INPUT_BUFFER_MAP, key)) {
  8616. if (key < KEY_ESCAPE) command_insert_char(key);
  8617. }
  8618. }
  8619. if (global_config.overlay_mode == OVERLAY_MODE_SEARCH) {
  8620. /* Find the next search match */
  8621. uint32_t * buffer = malloc(sizeof(uint32_t) * (global_config.command_buffer->actual+1));
  8622. for (int i = 0; i < global_config.command_buffer->actual; ++i) {
  8623. buffer[i] = global_config.command_buffer->text[i].codepoint;
  8624. }
  8625. buffer[global_config.command_buffer->actual] = 0;
  8626. int line = -1, col = -1;
  8627. if (global_config.search_direction == 1) {
  8628. find_match(global_config.prev_line, global_config.prev_col, &line, &col, buffer, NULL);
  8629. if (line == -1) {
  8630. find_match(1, global_config.prev_col, &line, &col, buffer, NULL);
  8631. }
  8632. } else {
  8633. find_match_backwards(global_config.prev_line, global_config.prev_col, &line, &col, buffer);
  8634. if (line == -1) {
  8635. find_match_backwards(env->line_count, global_config.prev_col, &line, &col, buffer);
  8636. }
  8637. }
  8638. if (line != -1) {
  8639. env->col_no = col;
  8640. env->line_no = line;
  8641. set_preferred_column();
  8642. } else {
  8643. env->coffset = global_config.prev_coffset;
  8644. env->offset = global_config.prev_offset;
  8645. env->col_no = global_config.prev_col;
  8646. set_preferred_column();
  8647. env->line_no = global_config.prev_line;
  8648. }
  8649. draw_search_match(buffer, 0);
  8650. free(buffer);
  8651. }
  8652. }
  8653. continue;
  8654. }
  8655. }
  8656. if (env->mode != last_mode) {
  8657. redraw_statusbar();
  8658. redraw_commandline();
  8659. last_mode = env->mode;
  8660. }
  8661. if (env->mode == MODE_NORMAL) {
  8662. place_cursor_actual();
  8663. int key = bim_getkey(200);
  8664. if (handle_nav_buffer(key)) {
  8665. if (!handle_action(NORMAL_MAP, key))
  8666. if (!handle_action(NAVIGATION_MAP, key))
  8667. handle_action(ESCAPE_MAP, key);
  8668. }
  8669. reset_nav_buffer(key);
  8670. } else if (env->mode == MODE_INSERT) {
  8671. place_cursor_actual();
  8672. int key = bim_getkey(refresh ? 10 : 200);
  8673. if (key == KEY_TIMEOUT) {
  8674. if (refresh > 1) {
  8675. redraw_text();
  8676. } else if (refresh) {
  8677. redraw_line(env->line_no-1);
  8678. }
  8679. refresh = 0;
  8680. } else if (handle_action(INSERT_MAP, key)) {
  8681. refresh = 2;
  8682. } else if (handle_action(ESCAPE_MAP, key)) {
  8683. /* Do nothing */
  8684. } else if (key < KEY_ESCAPE) {
  8685. insert_char(key);
  8686. if (global_config.smart_complete) {
  8687. redraw_line(env->line_no-1);
  8688. while (omni_complete(1) == 1);
  8689. }
  8690. refresh |= 1;
  8691. }
  8692. } else if (env->mode == MODE_REPLACE) {
  8693. place_cursor_actual();
  8694. int key = bim_getkey(200);
  8695. if (key != KEY_TIMEOUT) {
  8696. if (handle_action(REPLACE_MAP, key)) {
  8697. redraw_text();
  8698. } else if (!handle_action(ESCAPE_MAP, key)) {
  8699. /* Perform replacement */
  8700. if (key < KEY_ESCAPE) {
  8701. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  8702. replace_char(key);
  8703. env->col_no += 1;
  8704. } else {
  8705. insert_char(key);
  8706. redraw_line(env->line_no-1);
  8707. }
  8708. set_preferred_column();
  8709. }
  8710. }
  8711. }
  8712. } else if (env->mode == MODE_LINE_SELECTION) {
  8713. place_cursor_actual();
  8714. int key = bim_getkey(200);
  8715. if (key == KEY_TIMEOUT) continue;
  8716. if (handle_nav_buffer(key)) {
  8717. if (!handle_action(LINE_SELECTION_MAP, key))
  8718. if (!handle_action(NAVIGATION_MAP, key))
  8719. handle_action(ESCAPE_MAP, key);
  8720. }
  8721. reset_nav_buffer(key);
  8722. if (env->mode == MODE_LINE_SELECTION) {
  8723. /* Mark current line */
  8724. _redraw_line(env->line_no,0);
  8725. _redraw_line(env->start_line,1);
  8726. /* Properly mark everything in the span we just moved through */
  8727. if (env->prev_line < env->line_no) {
  8728. for (int i = env->prev_line; i < env->line_no; ++i) {
  8729. _redraw_line(i,0);
  8730. }
  8731. env->prev_line = env->line_no;
  8732. } else if (env->prev_line > env->line_no) {
  8733. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8734. _redraw_line(i,0);
  8735. }
  8736. env->prev_line = env->line_no;
  8737. }
  8738. redraw_commandline();
  8739. }
  8740. } else if (env->mode == MODE_CHAR_SELECTION) {
  8741. place_cursor_actual();
  8742. int key = bim_getkey(200);
  8743. if (key == KEY_TIMEOUT) continue;
  8744. if (handle_nav_buffer(key)) {
  8745. if (!handle_action(CHAR_SELECTION_MAP, key))
  8746. if (!handle_action(NAVIGATION_MAP, key))
  8747. handle_action(ESCAPE_MAP, key);
  8748. }
  8749. reset_nav_buffer(key);
  8750. if (env->mode == MODE_CHAR_SELECTION) {
  8751. /* Mark current line */
  8752. _redraw_line_char(env->line_no,1);
  8753. /* Properly mark everything in the span we just moved through */
  8754. if (env->prev_line < env->line_no) {
  8755. for (int i = env->prev_line; i < env->line_no; ++i) {
  8756. _redraw_line_char(i,1);
  8757. }
  8758. env->prev_line = env->line_no;
  8759. } else if (env->prev_line > env->line_no) {
  8760. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8761. _redraw_line_char(i,1);
  8762. }
  8763. env->prev_line = env->line_no;
  8764. }
  8765. }
  8766. } else if (env->mode == MODE_COL_SELECTION) {
  8767. place_cursor_actual();
  8768. int key = bim_getkey(200);
  8769. if (key == KEY_TIMEOUT) continue;
  8770. if (handle_nav_buffer(key)) {
  8771. if (!handle_action(COL_SELECTION_MAP, key))
  8772. if (!handle_action(NAVIGATION_MAP, key))
  8773. handle_action(ESCAPE_MAP, key);
  8774. }
  8775. reset_nav_buffer(key);
  8776. if (env->mode == MODE_COL_SELECTION) {
  8777. _redraw_line_col(env->line_no, 0);
  8778. /* Properly mark everything in the span we just moved through */
  8779. if (env->prev_line < env->line_no) {
  8780. for (int i = env->prev_line; i < env->line_no; ++i) {
  8781. _redraw_line_col(i,0);
  8782. }
  8783. env->prev_line = env->line_no;
  8784. } else if (env->prev_line > env->line_no) {
  8785. for (int i = env->line_no + 1; i <= env->prev_line; ++i) {
  8786. _redraw_line_col(i,0);
  8787. }
  8788. env->prev_line = env->line_no;
  8789. }
  8790. redraw_commandline();
  8791. }
  8792. } else if (env->mode == MODE_COL_INSERT) {
  8793. int key = bim_getkey(refresh ? 10 : 200);
  8794. if (key == KEY_TIMEOUT) {
  8795. if (refresh) {
  8796. redraw_commandline();
  8797. redraw_text();
  8798. }
  8799. refresh = 0;
  8800. } else if (handle_action(COL_INSERT_MAP, key)) {
  8801. /* pass */
  8802. } else if (key < KEY_ESCAPE) {
  8803. insert_char_at_column(key);
  8804. refresh = 1;
  8805. }
  8806. } if (env->mode == MODE_DIRECTORY_BROWSE) {
  8807. place_cursor_actual();
  8808. int key = bim_getkey(200);
  8809. if (handle_nav_buffer(key)) {
  8810. if (!handle_action(DIRECTORY_BROWSE_MAP, key))
  8811. if (!handle_action(NAVIGATION_MAP, key))
  8812. handle_action(ESCAPE_MAP, key);
  8813. }
  8814. reset_nav_buffer(key);
  8815. }
  8816. }
  8817. }
  8818. /**
  8819. * Show help text for -?
  8820. */
  8821. static void show_usage(char * argv[]) {
  8822. #define _s "\033[3m"
  8823. #define _e "\033[0m\n"
  8824. printf(
  8825. "bim - Text editor\n"
  8826. "\n"
  8827. "usage: %s [options] [file]\n"
  8828. " %s [options] -- -\n"
  8829. "\n"
  8830. " -R " _s "open initial buffer read-only" _e
  8831. " -O " _s "set various options:" _e
  8832. " noscroll " _s "disable terminal scrolling" _e
  8833. " noaltscreen " _s "disable alternate screen buffer" _e
  8834. " nomouse " _s "disable mouse support" _e
  8835. " nounicode " _s "disable unicode display" _e
  8836. " nobright " _s "disable bright next" _e
  8837. " nohideshow " _s "disable togglging cursor visibility" _e
  8838. " nosyntax " _s "disable syntax highlighting on load" _e
  8839. " notitle " _s "disable title-setting escapes" _e
  8840. " history " _s "enable experimental undo/redo" _e
  8841. " -c,-C " _s "print file to stdout with syntax highlighting" _e
  8842. " " _s "-C includes line numbers, -c does not" _e
  8843. " -u " _s "override bimrc file" _e
  8844. " -? " _s "show this help text" _e
  8845. "\n"
  8846. "Long options:\n"
  8847. " --help " _s "show this help text" _e
  8848. " --version " _s "show version information and available plugins" _e
  8849. " --dump-mappings " _s "dump markdown description of key mappings" _e
  8850. " --dump-commands " _s "dump markdown description of all commands" _e
  8851. " --dump-config " _s "dump key mappings as a bimscript" _e
  8852. " --html FILE " _s "convert FILE to syntax-highlighted HTML" _e
  8853. "\n", argv[0], argv[0]);
  8854. #undef _e
  8855. #undef _s
  8856. }
  8857. void free_function(struct bim_function * func) {
  8858. do {
  8859. struct bim_function * next = func->next;
  8860. free(func->command);
  8861. free(func);
  8862. func = next;
  8863. } while (func);
  8864. }
  8865. int run_function(char * name) {
  8866. for (int i = 0; i < flex_user_functions_count; ++i) {
  8867. if (user_functions[i] && !strcmp(user_functions[i]->command, name)) {
  8868. /* Execute function */
  8869. struct bim_function * this = user_functions[i]->next;
  8870. while (this) {
  8871. char * tmp = strdup(this->command);
  8872. int result = process_command(tmp);
  8873. free(tmp);
  8874. if (result != 0) {
  8875. return result;
  8876. }
  8877. this = this->next;
  8878. }
  8879. return 0;
  8880. }
  8881. }
  8882. return -1;
  8883. }
  8884. int has_function(char * name) {
  8885. for (int i = 0; i < flex_user_functions_count; ++i) {
  8886. if (user_functions[i] && !strcmp(user_functions[i]->command, name)) {
  8887. return 1;
  8888. }
  8889. }
  8890. return 0;
  8891. }
  8892. BIM_COMMAND(call,"call","Call a function") {
  8893. if (argc < 2) {
  8894. render_error("Expected function name");
  8895. return 1;
  8896. }
  8897. int result = run_function(argv[1]);
  8898. if (result == -1) {
  8899. render_error("Undefined function: %s", argv[1]);
  8900. return 1;
  8901. }
  8902. return result;
  8903. }
  8904. BIM_COMMAND(try_call,"trycall","Call a function but return quietly if it fails") {
  8905. if (argc < 2) return 0;
  8906. run_function(argv[1]);
  8907. return 0;
  8908. }
  8909. BIM_COMMAND(list_functions,"listfunctions","List functions") {
  8910. render_commandline_message("");
  8911. for (int i = 0; i < flex_user_functions_count; ++i) {
  8912. render_commandline_message("%s\n", user_functions[i]->command);
  8913. }
  8914. pause_for_key();
  8915. return 0;
  8916. }
  8917. BIM_COMMAND(show_function,"showfunction","Show the commands in a function") {
  8918. if (argc < 2) return 1;
  8919. struct bim_function * this = NULL;
  8920. for (int i = 0; i < flex_user_functions_count; ++i) {
  8921. if (user_functions[i] && !strcmp(user_functions[i]->command, argv[1])) {
  8922. this = user_functions[i];
  8923. break;
  8924. }
  8925. }
  8926. if (!this) {
  8927. render_error("Not a function: %s", argv[1]);
  8928. return 1;
  8929. }
  8930. /* We really should rewrite this so syntax highlighting takes a highlighter */
  8931. struct syntax_definition * old_syntax = env->syntax;
  8932. env->syntax = find_syntax_calculator("bimcmd");
  8933. int i = 0;
  8934. while (this) {
  8935. /* Turn command into line */
  8936. line_t * tmp = calloc(sizeof(line_t) + sizeof(char_t) * strlen(this->command),1);
  8937. tmp->available = strlen(this->command);
  8938. unsigned char * t = (unsigned char *)this->command;
  8939. uint32_t state = 0;
  8940. uint32_t c = 0;
  8941. int col = 1;
  8942. while (*t) {
  8943. if (!decode(&state, &c, *t)) {
  8944. char_t _c = {codepoint_width(c), 0, c};
  8945. tmp = line_insert(tmp, _c, col - 1, -1);
  8946. col++;
  8947. }
  8948. t++;
  8949. }
  8950. render_commandline_message("");
  8951. render_line(tmp, global_config.term_width - 1, 0, -1);
  8952. printf("\n");
  8953. this = this->next;
  8954. i++;
  8955. if (this && i == global_config.term_height - 3) {
  8956. printf("(function continues)");
  8957. while (bim_getkey(200) == KEY_TIMEOUT);
  8958. }
  8959. }
  8960. /* Restore previous syntax */
  8961. env->syntax = old_syntax;
  8962. pause_for_key();
  8963. return 0;
  8964. }
  8965. BIM_COMMAND(runscript,"runscript","Run a script file") {
  8966. if (argc < 2) {
  8967. render_error("Expected a script to run");
  8968. return 1;
  8969. }
  8970. /* Run commands */
  8971. FILE * f;
  8972. char * home;
  8973. if (argv[1][0] == '~' && (home = getenv("HOME"))) {
  8974. char * tmp = malloc(strlen(argv[1]) + strlen(home) + 4);
  8975. sprintf(tmp,"%s%s", home, argv[1]+1);
  8976. f = fopen(tmp,"r");
  8977. free(tmp);
  8978. } else {
  8979. f = fopen(argv[1],"r");
  8980. }
  8981. if (!f) {
  8982. render_error("Failed to open script");
  8983. return 1;
  8984. }
  8985. int retval = 0;
  8986. char linebuf[4096];
  8987. int line = 1;
  8988. int was_collecting_function = 0;
  8989. char * function_name = NULL;
  8990. struct bim_function * new_function = NULL;
  8991. struct bim_function * last_function = NULL;
  8992. while (!feof(f)) {
  8993. memset(linebuf, 0, 4096);
  8994. fgets(linebuf, 4095, f);
  8995. /* Remove linefeed */
  8996. char * s = strstr(linebuf, "\n");
  8997. if (s) *s = '\0';
  8998. /* See if this is a special syntax element */
  8999. if (!strncmp(linebuf, "function ", 9)) {
  9000. /* Confirm we have a function name */
  9001. if (was_collecting_function) {
  9002. free_function(new_function);
  9003. render_error("Syntax error on line %d: attempt nest function while already defining function '%s'", line, function_name);
  9004. retval = 1;
  9005. break;
  9006. }
  9007. if (!strlen(linebuf+9)) {
  9008. render_error("Syntax error on line %d: function needs a name", line);
  9009. retval = 1;
  9010. break;
  9011. }
  9012. function_name = strdup(linebuf+9);
  9013. was_collecting_function = 1;
  9014. new_function = malloc(sizeof(struct bim_function));
  9015. new_function->command = strdup(function_name);
  9016. new_function->next = NULL;
  9017. last_function = new_function;
  9018. /* Set up function */
  9019. } else if (!strcmp(linebuf,"end")) {
  9020. if (!was_collecting_function) {
  9021. render_error("Syntax error on line %d: unexpected 'end'", line);
  9022. retval = 1;
  9023. break;
  9024. }
  9025. was_collecting_function = 0;
  9026. /* See if a function with this name is already defined */
  9027. int this = -1;
  9028. for (int i = 0; i < flex_user_functions_count; ++i) {
  9029. if (user_functions[i] && !strcmp(user_functions[i]->command, function_name)) {
  9030. this = i;
  9031. break;
  9032. }
  9033. }
  9034. if (this > -1) {
  9035. free_function(user_functions[this]);
  9036. user_functions[this] = new_function;
  9037. } else {
  9038. add_user_function(new_function);
  9039. if (strstr(function_name,"theme:") == function_name) {
  9040. add_colorscheme((struct theme_def){strdup(function_name+6), load_colorscheme_script});
  9041. }
  9042. }
  9043. free(function_name);
  9044. new_function = NULL;
  9045. last_function = NULL;
  9046. function_name = NULL;
  9047. } else if (was_collecting_function) {
  9048. /* Collect function */
  9049. last_function->next = malloc(sizeof(struct bim_function));
  9050. last_function = last_function->next;
  9051. char * s = linebuf;
  9052. while (*s == ' ') s++;
  9053. last_function->command = strdup(s);
  9054. last_function->next = NULL;
  9055. } else {
  9056. int result = process_command(linebuf);
  9057. if (result != 0) {
  9058. retval = result;
  9059. break;
  9060. }
  9061. }
  9062. line++;
  9063. }
  9064. if (was_collecting_function) {
  9065. free_function(new_function);
  9066. render_error("Syntax error on line %d: unexpected end of file while defining function '%s'", line, function_name);
  9067. retval = 1;
  9068. }
  9069. if (function_name) free(function_name);
  9070. fclose(f);
  9071. return retval;
  9072. }
  9073. BIM_COMMAND(rundir,"rundir","Run scripts from a directory, in unspecified order") {
  9074. if (argc < 2) return 1;
  9075. char * file = argv[1];
  9076. DIR * dirp = NULL;
  9077. if (file[0] == '~') {
  9078. char * home = getenv("HOME");
  9079. if (home) {
  9080. char * _file = malloc(strlen(file) + strlen(home) + 4); /* Paranoia */
  9081. sprintf(_file, "%s%s", home, file+1);
  9082. dirp = opendir(_file);
  9083. free(_file);
  9084. }
  9085. } else {
  9086. dirp = opendir(file);
  9087. }
  9088. if (!dirp) {
  9089. render_error("Directory is not accessible: %s", argv[1]);
  9090. return 1;
  9091. }
  9092. struct dirent * ent = readdir(dirp);
  9093. while (ent) {
  9094. if (str_ends_with(ent->d_name,".bimscript")) {
  9095. char * tmp = malloc(strlen(file) + 1 + strlen(ent->d_name) + 1);