bim.c 163 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. *
  3. * Copyright (C) 2012-2019 K. Lange
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. * bim - Text editor
  18. *
  19. * Bim is inspired by vim, and its name is short for "Bad IMitation".
  20. *
  21. * Bim supports syntax highlighting, extensive editing, line selection
  22. * and copy-paste, undo/redo stack, forward and backward search, and can
  23. * be built for ToaruOS, Sortix, Linux, macOS, and BSDs.
  24. */
  25. #define _XOPEN_SOURCE
  26. #define _DEFAULT_SOURCE
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <stdint.h>
  31. #include <stdarg.h>
  32. #include <unistd.h>
  33. #include <termios.h>
  34. #include <signal.h>
  35. #include <locale.h>
  36. #include <wchar.h>
  37. #include <ctype.h>
  38. #include <dirent.h>
  39. #include <poll.h>
  40. #include <sys/types.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/stat.h>
  43. #define BIM_VERSION "1.1.7"
  44. #define BIM_COPYRIGHT "Copyright 2012-2019 K. Lange <\033[3mklange@toaruos.org\033[23m>"
  45. #define BLOCK_SIZE 4096
  46. #define ENTER_KEY '\r'
  47. #define LINE_FEED '\n'
  48. #define BACKSPACE_KEY 0x08
  49. #define DELETE_KEY 0x7F
  50. /**
  51. * Theming data
  52. *
  53. * This is all overridden by a load_colorscheme_ method.
  54. * The default is to load_colorscheme_ansi, but config
  55. * files can be used to set a different default theme.
  56. */
  57. const char * COLOR_FG = "@17";
  58. const char * COLOR_BG = "@0";
  59. const char * COLOR_ALT_FG = "@17";
  60. const char * COLOR_ALT_BG = "@0";
  61. const char * COLOR_NUMBER_FG = "@17";
  62. const char * COLOR_NUMBER_BG = "@0";
  63. const char * COLOR_STATUS_FG = "@17";
  64. const char * COLOR_STATUS_BG = "@0";
  65. const char * COLOR_TABBAR_BG = "@0";
  66. const char * COLOR_TAB_BG = "@0";
  67. const char * COLOR_ERROR_FG = "@17";
  68. const char * COLOR_ERROR_BG = "@0";
  69. const char * COLOR_SEARCH_FG = "@17";
  70. const char * COLOR_SEARCH_BG = "@0";
  71. const char * COLOR_KEYWORD = "@17";
  72. const char * COLOR_STRING = "@17";
  73. const char * COLOR_COMMENT = "@17";
  74. const char * COLOR_TYPE = "@17";
  75. const char * COLOR_PRAGMA = "@17";
  76. const char * COLOR_NUMERAL = "@17";
  77. const char * COLOR_SELECTFG = "@0";
  78. const char * COLOR_SELECTBG = "@17";
  79. const char * COLOR_RED = "@1";
  80. const char * COLOR_GREEN = "@2";
  81. const char * current_theme = "none";
  82. /**
  83. * Syntax highlighting flags.
  84. */
  85. #define FLAG_NONE 0
  86. #define FLAG_KEYWORD 1
  87. #define FLAG_STRING 2
  88. #define FLAG_COMMENT 3
  89. #define FLAG_TYPE 4
  90. #define FLAG_PRAGMA 5
  91. #define FLAG_NUMERAL 6
  92. #define FLAG_STRING2 7
  93. #define FLAG_DIFFPLUS 8
  94. #define FLAG_DIFFMINUS 9
  95. #define FLAG_SELECT (1 << 4)
  96. #define FLAG_SEARCH (1 << 5)
  97. #define FLAG_CONTINUES (1 << 6)
  98. /**
  99. * Convert syntax hilighting flag to color code
  100. */
  101. const char * flag_to_color(int _flag) {
  102. int flag = _flag & 0xF;
  103. switch (flag) {
  104. case FLAG_KEYWORD:
  105. return COLOR_KEYWORD;
  106. case FLAG_STRING:
  107. case FLAG_STRING2: /* allows python to differentiate " and ' */
  108. return COLOR_STRING;
  109. case FLAG_COMMENT:
  110. return COLOR_COMMENT;
  111. case FLAG_TYPE:
  112. return COLOR_TYPE;
  113. case FLAG_NUMERAL:
  114. return COLOR_NUMERAL;
  115. case FLAG_PRAGMA:
  116. return COLOR_PRAGMA;
  117. case FLAG_DIFFPLUS:
  118. return COLOR_GREEN;
  119. case FLAG_DIFFMINUS:
  120. return COLOR_RED;
  121. case FLAG_SELECT:
  122. return COLOR_FG;
  123. default:
  124. return COLOR_FG;
  125. }
  126. }
  127. /**
  128. * Line buffer definitions
  129. *
  130. * Lines are essentially resizable vectors of char_t structs,
  131. * which represent single codepoints in the file.
  132. */
  133. typedef struct {
  134. uint32_t display_width:4;
  135. uint32_t flags:7;
  136. uint32_t codepoint:21;
  137. } __attribute__((packed)) char_t;
  138. /**
  139. * Lines have available and actual lengths, describing
  140. * how much space was allocated vs. how much is being
  141. * used at the moment.
  142. */
  143. typedef struct {
  144. int available;
  145. int actual;
  146. int istate;
  147. int is_current;
  148. char_t text[];
  149. } line_t;
  150. /**
  151. * Global configuration state
  152. */
  153. struct {
  154. /* Terminal size */
  155. int term_width, term_height;
  156. int bottom_size;
  157. /* Command-line parameters */
  158. int hilight_on_open;
  159. int initial_file_is_read_only;
  160. line_t ** yanks;
  161. size_t yank_count;
  162. int yank_is_full_lines;
  163. int tty_in;
  164. const char * bimrc_path;
  165. int can_scroll;
  166. int can_hideshow;
  167. int can_altscreen;
  168. int can_mouse;
  169. int can_unicode;
  170. int can_bright;
  171. int can_title;
  172. int can_bce;
  173. int history_enabled;
  174. int cursor_padding;
  175. int highlight_parens;
  176. int smart_case;
  177. int can_24bit;
  178. int can_256color;
  179. int can_italic;
  180. int go_to_line;
  181. int hilight_current_line;
  182. } global_config = {
  183. 0, /* term_width */
  184. 0, /* term_height */
  185. 2, /* bottom_size */
  186. 1, /* hilight_on_open */
  187. 0, /* initial_file_is_read_only */
  188. NULL, /* yanks */
  189. 0, /* yank_count */
  190. 0,
  191. STDIN_FILENO, /* tty_in */
  192. "~/.bimrc", /* bimrc_path */
  193. 1, /* can scroll */
  194. 1, /* can hide/show cursor */
  195. 1, /* can use alternate screen */
  196. 1, /* can mouse */
  197. 1, /* can unicode */
  198. 1, /* can use bright colors */
  199. 1, /* can set title */
  200. 1, /* can bce */
  201. 1, /* history enabled */
  202. 4, /* cursor padding */
  203. 1, /* highlight parens/braces when cursor moves */
  204. 1, /* smart case */
  205. 1, /* can use 24-bit color */
  206. 1, /* can use 265 colors */
  207. 1, /* can use italics (without inverting) */
  208. 1, /* should go to line when opening file */
  209. 1, /* hilight the current line */
  210. };
  211. void redraw_line(int j, int x);
  212. /**
  213. * Special implementation of getch with a timeout
  214. */
  215. int _bim_unget = -1;
  216. void bim_unget(int c) {
  217. _bim_unget = c;
  218. }
  219. #define bim_getch() bim_getch_timeout(200)
  220. int bim_getch_timeout(int timeout) {
  221. if (_bim_unget != -1) {
  222. int out = _bim_unget;
  223. _bim_unget = -1;
  224. return out;
  225. }
  226. struct pollfd fds[1];
  227. fds[0].fd = global_config.tty_in;
  228. fds[0].events = POLLIN;
  229. int ret = poll(fds,1,timeout);
  230. if (ret > 0 && fds[0].revents & POLLIN) {
  231. unsigned char buf[1];
  232. read(global_config.tty_in, buf, 1);
  233. return buf[0];
  234. } else {
  235. return -1;
  236. }
  237. }
  238. #define HISTORY_SENTINEL 0
  239. #define HISTORY_INSERT 1
  240. #define HISTORY_DELETE 2
  241. #define HISTORY_REPLACE 3
  242. #define HISTORY_REMOVE_LINE 4
  243. #define HISTORY_ADD_LINE 5
  244. #define HISTORY_REPLACE_LINE 6
  245. #define HISTORY_MERGE_LINES 7
  246. #define HISTORY_SPLIT_LINE 8
  247. #define HISTORY_BREAK 10
  248. typedef struct history {
  249. struct history * previous;
  250. struct history * next;
  251. int type;
  252. union {
  253. struct {
  254. int lineno;
  255. int offset;
  256. int codepoint;
  257. int old_codepoint;
  258. } insert_delete_replace;
  259. struct {
  260. int lineno;
  261. line_t * contents;
  262. line_t * old_contents;
  263. } remove_replace_line;
  264. struct {
  265. int lineno;
  266. int split;
  267. } add_merge_split_lines;
  268. } contents;
  269. } history_t;
  270. /**
  271. * Buffer data
  272. *
  273. * A buffer describes a file, and stores
  274. * its name as well as the editor state
  275. * (cursor offsets, etc.) and the actual
  276. * line buffers.
  277. */
  278. typedef struct _env {
  279. unsigned short loading:1;
  280. unsigned short tabs:1;
  281. unsigned short modified:1;
  282. unsigned short readonly:1;
  283. unsigned short indent:1;
  284. unsigned short highlighting_paren:1;
  285. short mode;
  286. short tabstop;
  287. char * file_name;
  288. int offset;
  289. int coffset;
  290. int line_no;
  291. int line_count;
  292. int line_avail;
  293. int col_no;
  294. int preferred_column;
  295. uint32_t * search;
  296. struct syntax_definition * syntax;
  297. line_t ** lines;
  298. history_t * history;
  299. history_t * last_save_history;
  300. } buffer_t;
  301. /**
  302. * Pointer to current active buffer
  303. */
  304. buffer_t * env;
  305. /**
  306. * Editor modes (like in vim)
  307. */
  308. #define MODE_NORMAL 0
  309. #define MODE_INSERT 1
  310. #define MODE_LINE_SELECTION 2
  311. #define MODE_REPLACE 3
  312. #define MODE_CHAR_SELECTION 4
  313. /**
  314. * Available buffers
  315. */
  316. int buffers_len;
  317. int buffers_avail;
  318. buffer_t ** buffers;
  319. /**
  320. * Create a new buffer
  321. */
  322. buffer_t * buffer_new(void) {
  323. if (buffers_len == buffers_avail) {
  324. /* If we are out of buffer space, expand the buffers vector */
  325. buffers_avail *= 2;
  326. buffers = realloc(buffers, sizeof(buffer_t *) * buffers_avail);
  327. }
  328. /* Allocate a new buffer */
  329. buffers[buffers_len] = malloc(sizeof(buffer_t));
  330. memset(buffers[buffers_len], 0x00, sizeof(buffer_t));
  331. buffers_len++;
  332. return buffers[buffers_len-1];
  333. }
  334. /**
  335. * Close a buffer
  336. */
  337. buffer_t * buffer_close(buffer_t * buf) {
  338. int i;
  339. /* Locate the buffer in the buffer pointer vector */
  340. for (i = 0; i < buffers_len; i++) {
  341. if (buf == buffers[i])
  342. break;
  343. }
  344. /* Invalid buffer? */
  345. if (i == buffers_len) {
  346. return env; /* wtf */
  347. }
  348. /* Remove the buffer from the vector, moving others up */
  349. if (i != buffers_len - 1) {
  350. memmove(&buffers[i], &buffers[i+1], sizeof(*buffers) * (buffers_len - i));
  351. }
  352. /* There is one less buffer */
  353. buffers_len--;
  354. if (!buffers_len) {
  355. /* There are no more buffers. */
  356. return NULL;
  357. }
  358. /* If this was the last buffer, return the previous last buffer */
  359. if (i == buffers_len) {
  360. return buffers[buffers_len-1];
  361. }
  362. /* Otherwise return the new last buffer */
  363. return buffers[i];
  364. }
  365. /**
  366. * Themes
  367. */
  368. /* 16-color theme, default */
  369. void load_colorscheme_ansi(void) {
  370. COLOR_FG = global_config.can_bright ? "@17" : "@7";
  371. COLOR_BG = global_config.can_bright ? "@9" : "@0";
  372. COLOR_ALT_FG = global_config.can_bright ? "@10" : "@5";
  373. COLOR_ALT_BG = "@9";
  374. COLOR_NUMBER_FG = "@3";
  375. COLOR_NUMBER_BG = "@9";
  376. COLOR_STATUS_FG = global_config.can_bright ? "@17" : "@7";
  377. COLOR_STATUS_BG = "@4";
  378. COLOR_TABBAR_BG = "@4";
  379. COLOR_TAB_BG = "@4";
  380. COLOR_KEYWORD = global_config.can_bright ? "@14" : "@4";
  381. COLOR_STRING = "@2";
  382. COLOR_COMMENT = global_config.can_bright ? "@10" : "@5";
  383. COLOR_TYPE = "@3";
  384. COLOR_PRAGMA = "@1";
  385. COLOR_NUMERAL = "@1";
  386. COLOR_ERROR_FG = global_config.can_bright ? "@17" : "@7";
  387. COLOR_ERROR_BG = "@1";
  388. COLOR_SEARCH_FG = "@0";
  389. COLOR_SEARCH_BG = global_config.can_bright ? "@13" : "@3";
  390. COLOR_SELECTBG = global_config.can_bright ? "@17" : "@7";
  391. COLOR_SELECTFG = "@0";
  392. COLOR_RED = "@1";
  393. COLOR_GREEN = "@2";
  394. current_theme = "ansi";
  395. }
  396. /* Based on the wombat256 theme for vim */
  397. void load_colorscheme_wombat(void) {
  398. if (!global_config.can_256color) return;
  399. COLOR_FG = "5;230";
  400. COLOR_BG = "5;235";
  401. COLOR_ALT_FG = "5;244";
  402. COLOR_ALT_BG = "5;236";
  403. COLOR_NUMBER_BG = "5;232";
  404. COLOR_NUMBER_FG = "5;101";
  405. COLOR_STATUS_FG = "5;230";
  406. COLOR_STATUS_BG = "5;238";
  407. COLOR_TABBAR_BG = "5;230";
  408. COLOR_TAB_BG = "5;248";
  409. COLOR_KEYWORD = "5;117";
  410. COLOR_STRING = "5;113";
  411. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  412. COLOR_TYPE = "5;186";
  413. COLOR_PRAGMA = "5;173";
  414. COLOR_NUMERAL = COLOR_PRAGMA;
  415. COLOR_ERROR_FG = "5;15";
  416. COLOR_ERROR_BG = "5;196";
  417. COLOR_SEARCH_FG = "5;234";
  418. COLOR_SEARCH_BG = "5;226";
  419. COLOR_SELECTFG = "5;235";
  420. COLOR_SELECTBG = "5;230";
  421. COLOR_RED = "@1";
  422. COLOR_GREEN = "@2";
  423. current_theme = "wombat";
  424. }
  425. /* "City Lights" based on citylights.xyz */
  426. void load_colorscheme_citylights(void) {
  427. if (!global_config.can_24bit) return;
  428. COLOR_FG = "2;151;178;198";
  429. COLOR_BG = "2;29;37;44";
  430. COLOR_ALT_FG = "2;45;55;65";
  431. COLOR_ALT_BG = "2;33;42;50";
  432. COLOR_NUMBER_FG = "2;71;89;103";
  433. COLOR_NUMBER_BG = "2;37;47;56";
  434. COLOR_STATUS_FG = "2;116;144;166";
  435. COLOR_STATUS_BG = "2;53;67;78";
  436. COLOR_TABBAR_BG = "2;37;47;56";
  437. COLOR_TAB_BG = "2;29;37;44";
  438. COLOR_KEYWORD = "2;94;196;255";
  439. COLOR_STRING = "2;83;154;252";
  440. COLOR_COMMENT = "2;107;133;153;3";
  441. COLOR_TYPE = "2;139;212;156";
  442. COLOR_PRAGMA = "2;0;139;148";
  443. COLOR_NUMERAL = "2;207;118;132";
  444. COLOR_ERROR_FG = "5;15";
  445. COLOR_ERROR_BG = "5;196";
  446. COLOR_SEARCH_FG = "5;234";
  447. COLOR_SEARCH_BG = "5;226";
  448. COLOR_SELECTFG = "2;29;37;44";
  449. COLOR_SELECTBG = "2;151;178;198";
  450. COLOR_RED = "2;222;53;53";
  451. COLOR_GREEN = "2;55;167;0";
  452. current_theme = "citylights";
  453. }
  454. /* Solarized Dark, popular theme */
  455. void load_colorscheme_solarized_dark(void) {
  456. if (!global_config.can_24bit) return;
  457. COLOR_FG = "2;147;161;161";
  458. COLOR_BG = "2;0;43;54";
  459. COLOR_ALT_FG = "2;147;161;161";
  460. COLOR_ALT_BG = "2;7;54;66";
  461. COLOR_NUMBER_FG = "2;131;148;149";
  462. COLOR_NUMBER_BG = "2;7;54;66";
  463. COLOR_STATUS_FG = "2;131;148;150";
  464. COLOR_STATUS_BG = "2;7;54;66";
  465. COLOR_TABBAR_BG = "2;7;54;66";
  466. COLOR_TAB_BG = "2;131;148;150";
  467. COLOR_KEYWORD = "2;133;153;0";
  468. COLOR_STRING = "2;42;161;152";
  469. COLOR_COMMENT = "2;101;123;131";
  470. COLOR_TYPE = "2;181;137;0";
  471. COLOR_PRAGMA = "2;203;75;22";
  472. COLOR_NUMERAL = "2;220;50;47";
  473. COLOR_ERROR_FG = "5;15";
  474. COLOR_ERROR_BG = "5;196";
  475. COLOR_SEARCH_FG = "5;234";
  476. COLOR_SEARCH_BG = "5;226";
  477. COLOR_SELECTFG = "2;0;43;54";
  478. COLOR_SELECTBG = "2;147;161;161";
  479. COLOR_RED = "2;222;53;53";
  480. COLOR_GREEN = "2;55;167;0";
  481. current_theme = "solarized-dark";
  482. }
  483. void load_colorscheme_sunsmoke256(void) {
  484. if (!global_config.can_256color) return;
  485. COLOR_FG = "5;188";
  486. COLOR_BG = "5;234";
  487. COLOR_ALT_FG = "5;244";
  488. COLOR_ALT_BG = "5;236";
  489. COLOR_NUMBER_FG = "5;101";
  490. COLOR_NUMBER_BG = "5;232";
  491. COLOR_STATUS_FG = "5;188";
  492. COLOR_STATUS_BG = "5;59";
  493. COLOR_TABBAR_BG = "5;59";
  494. COLOR_TAB_BG = "5;59";
  495. COLOR_KEYWORD = "5;74";
  496. COLOR_STRING = "5;71";
  497. COLOR_COMMENT = global_config.can_italic ? "5;102;3" : "5;102";
  498. COLOR_TYPE = "5;221";
  499. COLOR_PRAGMA = "5;160";
  500. COLOR_NUMERAL = "5;161";
  501. COLOR_ERROR_FG = "5;15";
  502. COLOR_ERROR_BG = "5;196";
  503. COLOR_SEARCH_FG = "5;234";
  504. COLOR_SEARCH_BG = "5;226";
  505. COLOR_SELECTFG = "5;17";
  506. COLOR_SELECTBG = "5;109";
  507. COLOR_RED = "@1";
  508. COLOR_GREEN = "@2";
  509. current_theme = "sunsmoke256";
  510. }
  511. /* Custom theme */
  512. void load_colorscheme_sunsmoke(void) {
  513. if (!global_config.can_24bit) {
  514. load_colorscheme_sunsmoke256();
  515. return;
  516. }
  517. COLOR_FG = "2;230;230;230";
  518. COLOR_BG = "2;31;31;31";
  519. COLOR_ALT_FG = "2;122;122;122";
  520. COLOR_ALT_BG = "2;46;43;46";
  521. COLOR_NUMBER_FG = "2;150;139;57";
  522. COLOR_NUMBER_BG = "2;0;0;0";
  523. COLOR_STATUS_FG = "2;230;230;230";
  524. COLOR_STATUS_BG = "2;71;64;58";
  525. COLOR_TABBAR_BG = "2;71;64;58";
  526. COLOR_TAB_BG = "2;71;64;58";
  527. COLOR_KEYWORD = "2;51;162;230";
  528. COLOR_STRING = "2;72;176;72";
  529. COLOR_COMMENT = "2;158;153;129;3";
  530. COLOR_TYPE = "2;230;206;110";
  531. COLOR_PRAGMA = "2;194;70;54";
  532. COLOR_NUMERAL = "2;230;43;127";
  533. COLOR_ERROR_FG = "5;15";
  534. COLOR_ERROR_BG = "5;196";
  535. COLOR_SEARCH_FG = "5;234";
  536. COLOR_SEARCH_BG = "5;226";
  537. COLOR_SELECTFG = "2;0;43;54";
  538. COLOR_SELECTBG = "2;147;161;161";
  539. COLOR_RED = "2;222;53;53";
  540. COLOR_GREEN = "2;55;167;0";
  541. current_theme = "sunsmoke";
  542. }
  543. struct theme_def {
  544. const char * name;
  545. void (*load)(void);
  546. } themes[] = {
  547. {"wombat", load_colorscheme_wombat},
  548. {"citylights", load_colorscheme_citylights},
  549. {"solarized-dark", load_colorscheme_solarized_dark},
  550. {"ansi", load_colorscheme_ansi},
  551. {"sunsmoke", load_colorscheme_sunsmoke},
  552. {"sunsmoke256", load_colorscheme_sunsmoke256},
  553. {NULL, NULL}
  554. };
  555. /**
  556. * Syntax definition for C
  557. */
  558. int syn_c_iskeywordchar(int c) {
  559. if (isalnum(c)) return 1;
  560. if (c == '_') return 1;
  561. return 0;
  562. }
  563. static char * syn_c_keywords[] = {
  564. "while","if","for","continue","return","break","switch","case","sizeof",
  565. "struct","union","typedef","do","default","else","goto",
  566. "alignas","alignof","offsetof","asm","__asm__",
  567. /* C++ stuff */
  568. "public","private","class","using","namespace","virtual","override","protected",
  569. NULL
  570. };
  571. static char * syn_c_types[] = {
  572. "static","int","char","short","float","double","void","unsigned","volatile","const",
  573. "register","long","inline","restrict","enum","auto","extern","bool","complex",
  574. "uint8_t","uint16_t","uint32_t","uint64_t",
  575. "int8_t","int16_t","int32_t","int64_t","FILE",
  576. "ssize_t","size_t","uintptr_t","intptr_t","__volatile__",
  577. NULL
  578. };
  579. static char * syn_c_special[] = {
  580. "NULL",
  581. "stdin","stdout","stderr",
  582. "STDIN_FILENO","STDOUT_FILENO","STDERR_FILENO",
  583. NULL
  584. };
  585. static int syn_c_extended(line_t * line, int i, int c, int last, int * out_left) {
  586. if (i == 0 && c == '#') {
  587. *out_left = line->actual+1;
  588. if (line->text[line->actual-1].codepoint == '\\') {
  589. return FLAG_PRAGMA | FLAG_CONTINUES;
  590. }
  591. return FLAG_PRAGMA;
  592. }
  593. if ((!last || !syn_c_iskeywordchar(last)) && syn_c_iskeywordchar(c)) {
  594. int j = i;
  595. for (int s = 0; syn_c_special[s]; ++s) {
  596. int d = 0;
  597. while (j + d < line->actual - 1 && line->text[j+d].codepoint == syn_c_special[s][d]) d++;
  598. if (syn_c_special[s][d] == '\0' && (j+d > line->actual || !syn_c_iskeywordchar(line->text[j+d].codepoint))) {
  599. *out_left = d-1;
  600. return FLAG_NUMERAL;
  601. }
  602. }
  603. }
  604. if ((!last || !syn_c_iskeywordchar(last)) && isdigit(c)) {
  605. if (c == '0' && i < line->actual - 1 && line->text[i+1].codepoint == 'x') {
  606. int j = 2;
  607. for (; i + j < line->actual && isxdigit(line->text[i+j].codepoint); ++j);
  608. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  609. return FLAG_NONE;
  610. }
  611. *out_left = j - 1;
  612. return FLAG_NUMERAL;
  613. } else {
  614. int j = 1;
  615. while (i + j < line->actual && isdigit(line->text[i+j].codepoint)) {
  616. j++;
  617. }
  618. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  619. return FLAG_NONE;
  620. }
  621. *out_left = j - 1;
  622. return FLAG_NUMERAL;
  623. }
  624. }
  625. if (c == '/') {
  626. if (i < line->actual - 1 && line->text[i+1].codepoint == '/') {
  627. *out_left = (line->actual + 1) - i;
  628. return FLAG_COMMENT;
  629. }
  630. if (i < line->actual - 1 && line->text[i+1].codepoint == '*') {
  631. int last = 0;
  632. for (int j = i + 2; j < line->actual; ++j) {
  633. int c = line->text[j].codepoint;
  634. if (c == '/' && last == '*') {
  635. *out_left = j - i;
  636. return FLAG_COMMENT;
  637. }
  638. last = c;
  639. }
  640. /* TODO multiline - update next */
  641. *out_left = (line->actual + 1) - i;
  642. return FLAG_COMMENT | FLAG_CONTINUES;
  643. }
  644. }
  645. if (c == '\'') {
  646. if (i < line->actual - 3 && line->text[i+1].codepoint == '\\' &&
  647. line->text[i+3].codepoint == '\'') {
  648. *out_left = 3;
  649. return FLAG_NUMERAL;
  650. }
  651. if (i < line->actual - 2 && line->text[i+2].codepoint == '\'') {
  652. *out_left = 2;
  653. return FLAG_NUMERAL;
  654. }
  655. }
  656. if (c == '"') {
  657. int last = 0;
  658. for (int j = i+1; j < line->actual; ++j) {
  659. int c = line->text[j].codepoint;
  660. if (last != '\\' && c == '"') {
  661. *out_left = j - i;
  662. return FLAG_STRING;
  663. }
  664. if (last == '\\' && c == '\\') {
  665. last = 0;
  666. }
  667. last = c;
  668. }
  669. *out_left = (line->actual + 1) - i; /* unterminated string */
  670. return FLAG_STRING;
  671. }
  672. return 0;
  673. }
  674. char * syn_c_ext[] = {".c",".h",".cpp",".hpp",".c++",".h++",NULL};
  675. static int syn_c_finish(line_t * line, int * left, int state) {
  676. if (state == (FLAG_COMMENT | FLAG_CONTINUES)) {
  677. int last = 0;
  678. for (int i = 0; i < line->actual; ++i) {
  679. if (line->text[i].codepoint == '/' && last == '*') {
  680. *left = i+2;
  681. return FLAG_COMMENT;
  682. }
  683. last = line->text[i].codepoint;
  684. }
  685. return FLAG_COMMENT | FLAG_CONTINUES;
  686. }
  687. if (state == (FLAG_PRAGMA | FLAG_CONTINUES)) {
  688. *left = line->actual + 1;
  689. if (line->text[line->actual-1].codepoint == '\\') {
  690. return FLAG_PRAGMA | FLAG_CONTINUES;
  691. }
  692. return FLAG_PRAGMA;
  693. }
  694. return 0;
  695. }
  696. /**
  697. * Syntax definition for Python
  698. */
  699. static char * syn_py_keywords[] = {
  700. "class","def","return","del","if","else","elif",
  701. "for","while","continue","break","assert",
  702. "as","and","or","except","finally","from",
  703. "global","import","in","is","lambda","with",
  704. "nonlocal","not","pass","raise","try","yield",
  705. NULL
  706. };
  707. static char * syn_py_types[] = {
  708. "True","False","None",
  709. "object","set","dict","int","str","bytes",
  710. NULL
  711. };
  712. static int syn_py_extended(line_t * line, int i, int c, int last, int * out_left) {
  713. if (i == 0 && c == 'i') {
  714. /* Check for import */
  715. char * import = "import ";
  716. for (int j = 0; j < line->actual + 1; ++j) {
  717. if (import[j] == '\0') {
  718. *out_left = j - 2;
  719. return FLAG_PRAGMA;
  720. }
  721. if (line->text[j].codepoint != import[j]) break;
  722. }
  723. }
  724. if (c == '#') {
  725. *out_left = (line->actual + 1) - i;
  726. return FLAG_COMMENT;
  727. }
  728. if (c == '@') {
  729. for (int j = i+1; j < line->actual + 1; ++j) {
  730. if (!syn_c_iskeywordchar(line->text[j].codepoint)) {
  731. *out_left = j - i - 1;
  732. return FLAG_PRAGMA;
  733. }
  734. *out_left = (line->actual + 1) - i;
  735. return FLAG_PRAGMA;
  736. }
  737. }
  738. if ((!last || !syn_c_iskeywordchar(last)) && isdigit(c)) {
  739. if (c == '0' && i < line->actual - 1 && line->text[i+1].codepoint == 'x') {
  740. int j = 2;
  741. for (; i + j < line->actual && isxdigit(line->text[i+j].codepoint); ++j);
  742. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  743. return FLAG_NONE;
  744. }
  745. *out_left = j - 1;
  746. return FLAG_NUMERAL;
  747. } else {
  748. int j = 1;
  749. while (i + j < line->actual && isdigit(line->text[i+j].codepoint)) {
  750. j++;
  751. }
  752. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  753. return FLAG_NONE;
  754. }
  755. *out_left = j - 1;
  756. return FLAG_NUMERAL;
  757. }
  758. }
  759. if (line->text[i].codepoint == '\'') {
  760. if (i + 2 < line->actual && line->text[i+1].codepoint == '\'' && line->text[i+2].codepoint == '\'') {
  761. /* Begin multiline */
  762. for (int j = i + 3; j < line->actual - 2; ++j) {
  763. if (line->text[j].codepoint == '\'' &&
  764. line->text[j+1].codepoint == '\'' &&
  765. line->text[j+2].codepoint == '\'') {
  766. *out_left = (j+2) - i;
  767. return FLAG_STRING;
  768. }
  769. }
  770. return FLAG_STRING | FLAG_CONTINUES;
  771. }
  772. int last = 0;
  773. for (int j = i+1; j < line->actual; ++j) {
  774. int c = line->text[j].codepoint;
  775. if (last != '\\' && c == '\'') {
  776. *out_left = j - i;
  777. return FLAG_STRING;
  778. }
  779. if (last == '\\' && c == '\\') {
  780. last = 0;
  781. }
  782. last = c;
  783. }
  784. *out_left = (line->actual + 1) - i; /* unterminated string */
  785. return FLAG_STRING;
  786. }
  787. if (line->text[i].codepoint == '"') {
  788. if (i + 2 < line->actual && line->text[i+1].codepoint == '"' && line->text[i+2].codepoint == '"') {
  789. /* Begin multiline */
  790. for (int j = i + 3; j < line->actual - 2; ++j) {
  791. if (line->text[j].codepoint == '"' &&
  792. line->text[j+1].codepoint == '"' &&
  793. line->text[j+2].codepoint == '"') {
  794. *out_left = (j+2) - i;
  795. return FLAG_STRING;
  796. }
  797. }
  798. return FLAG_STRING2 | FLAG_CONTINUES;
  799. }
  800. int last = 0;
  801. for (int j = i+1; j < line->actual; ++j) {
  802. int c = line->text[j].codepoint;
  803. if (last != '\\' && c == '"') {
  804. *out_left = j - i;
  805. return FLAG_STRING;
  806. }
  807. if (last == '\\' && c == '\\') {
  808. last = 0;
  809. }
  810. last = c;
  811. }
  812. *out_left = (line->actual + 1) - i; /* unterminated string */
  813. return FLAG_STRING;
  814. }
  815. return 0;
  816. }
  817. static int syn_py_finish(line_t * line, int * left, int state) {
  818. /* TODO support multiline quotes */
  819. if (state == (FLAG_STRING | FLAG_CONTINUES)) {
  820. for (int j = 0; j < line->actual - 2; ++j) {
  821. if (line->text[j].codepoint == '\'' &&
  822. line->text[j+1].codepoint == '\'' &&
  823. line->text[j+2].codepoint == '\'') {
  824. *left = (j+3);
  825. return FLAG_STRING;
  826. }
  827. }
  828. return FLAG_STRING | FLAG_CONTINUES;
  829. }
  830. if (state == (FLAG_STRING2 | FLAG_CONTINUES)) {
  831. for (int j = 0; j < line->actual - 2; ++j) {
  832. if (line->text[j].codepoint == '"' &&
  833. line->text[j+1].codepoint == '"' &&
  834. line->text[j+2].codepoint == '"') {
  835. *left = (j+3);
  836. return FLAG_STRING2;
  837. }
  838. }
  839. return FLAG_STRING2 | FLAG_CONTINUES;
  840. }
  841. return 0;
  842. }
  843. char * syn_py_ext[] = {".py",NULL};
  844. /**
  845. * Syntax definition for ToaruOS shell
  846. */
  847. static char * syn_sh_keywords[] = {
  848. "cd","exit","export","help","history","if",
  849. "empty?","equals?","return","export-cmd","read",
  850. "source","exec","not","while","then","else",
  851. /* Command commands */
  852. "echo","cd","ln","tar","rm","cp","chmod",
  853. NULL,
  854. };
  855. static int variable_char(uint8_t c) {
  856. if (c >= 'A' && c <= 'Z') return 1;
  857. if (c >= 'a' && c <= 'z') return 1;
  858. if (c >= '0' && c <= '9') return 1;
  859. if (c == '_') return 1;
  860. return 0;
  861. }
  862. int variable_char_first(uint8_t c) {
  863. if (c == '?') return 1;
  864. if (c == '$') return 1;
  865. if (c == '#') return 1;
  866. return 0;
  867. }
  868. static int syn_sh_extended(line_t * line, int i, int c, int last, int * out_left) {
  869. (void)last;
  870. if (c == '#' && last != '\\') {
  871. *out_left = (line->actual + 1) - i;
  872. return FLAG_COMMENT;
  873. }
  874. if (line->text[i].codepoint == '\'' && last != '\\') {
  875. int last = 0;
  876. for (int j = i+1; j < line->actual + 1; ++j) {
  877. int c = line->text[j].codepoint;
  878. if (last != '\\' && c == '\'') {
  879. *out_left = j - i;
  880. return FLAG_STRING;
  881. }
  882. if (last == '\\' && c == '\\') {
  883. last = 0;
  884. }
  885. last = c;
  886. }
  887. *out_left = (line->actual + 1) - i; /* unterminated string */
  888. return FLAG_STRING;
  889. }
  890. if (line->text[i].codepoint == '$' && last != '\\') {
  891. if (i < line->actual - 1 && line->text[i+1].codepoint == '{') {
  892. int j = i + 2;
  893. for (; j < line->actual+1; ++j) {
  894. if (line->text[j].codepoint == '}') break;
  895. }
  896. *out_left = (j - i);
  897. return FLAG_NUMERAL;
  898. }
  899. int j = i + 1;
  900. int col = 0;
  901. for (; j < line->actual + 1; ++j, ++col) {
  902. if (col == 0) {
  903. if (variable_char_first(line->text[j].codepoint) || isdigit(line->text[j].codepoint)) {
  904. j++;
  905. break;
  906. }
  907. if (!variable_char(line->text[j].codepoint)) break;
  908. } else {
  909. if (!variable_char(line->text[j].codepoint)) break;
  910. }
  911. }
  912. *out_left = (j - i) - 1;
  913. return FLAG_NUMERAL;
  914. }
  915. if (line->text[i].codepoint == '"' && last != '\\') {
  916. int last = 0;
  917. for (int j = i+1; j < line->actual + 1; ++j) {
  918. int c = line->text[j].codepoint;
  919. if (last != '\\' && c == '"') {
  920. *out_left = j - i;
  921. return FLAG_STRING;
  922. }
  923. if (last == '\\' && c == '\\') {
  924. last = 0;
  925. }
  926. last = c;
  927. }
  928. *out_left = (line->actual + 1) - i; /* unterminated string */
  929. return FLAG_STRING;
  930. }
  931. return 0;
  932. }
  933. static int syn_sh_iskeywordchar(int c) {
  934. if (isalnum(c)) return 1;
  935. if (c == '-') return 1;
  936. if (c == '_') return 1;
  937. if (c == '?') return 1;
  938. return 0;
  939. }
  940. static char * syn_sh_ext[] = {".sh",".eshrc",".esh",NULL};
  941. static char * syn_make_ext[] = {"Makefile","makefile","GNUmakefile",".mak",NULL};
  942. static char * syn_make_commands[] = {
  943. "define","endef","undefine","ifdef","ifndef","ifeq","ifneq","else","endif",
  944. "include","sinclude","override","export","unexport","private","vpath",
  945. "-include",
  946. NULL
  947. };
  948. static char * syn_make_functions[] = {
  949. "subst","patsubst","findstring","filter","filter-out",
  950. "sort","word","words","wordlist","firstword","lastword",
  951. "dir","notdir","suffix","basename","addsuffix","addprefix",
  952. "join","wildcard","realpath","abspath","error","warning",
  953. "shell","origin","flavor","foreach","if","or","and",
  954. "call","eval","file","value",
  955. NULL
  956. };
  957. static int syn_make_extended(line_t * line, int i, int c, int last, int * out_left) {
  958. (void)last;
  959. if (c == '#') {
  960. *out_left = (line->actual + 1) - i;
  961. return FLAG_COMMENT;
  962. }
  963. if (c == '\t') {
  964. *out_left = (line->actual + 1) - i;
  965. return FLAG_NUMERAL;
  966. }
  967. if (i == 0) {
  968. int j = 0;
  969. for (; j < line->actual; ++j) {
  970. /* Handle leading spaces */
  971. if (line->text[j].codepoint != ' ') break;
  972. }
  973. for (int s = 0; syn_make_commands[s]; ++s) {
  974. int d = 0;
  975. while (j + d < line->actual && line->text[j+d].codepoint == syn_make_commands[s][d]) d++;
  976. if (syn_make_commands[s][d] == '\0') {
  977. *out_left = j+d;
  978. return FLAG_PRAGMA;
  979. }
  980. }
  981. }
  982. if (last == '(' && i > 1) {
  983. if (line->text[i-2].codepoint == '$') {
  984. int j = i;
  985. for (int s = 0; syn_make_functions[s]; ++s) {
  986. int d = 0;
  987. while (j + d < line->actual && line->text[j+d].codepoint == syn_make_functions[s][d]) d++;
  988. if (syn_make_functions[s][d] == '\0' && (j + d == line->actual
  989. || line->text[j+d].codepoint == ')' || line->text[j+d].codepoint == ' ')) {
  990. *out_left = d;
  991. return FLAG_KEYWORD;
  992. }
  993. }
  994. }
  995. }
  996. if (i == 0) {
  997. int j = 0;
  998. for (; j < line->actual; ++j) {
  999. if (line->text[j].codepoint == '=') {
  1000. *out_left = j;
  1001. return FLAG_TYPE;
  1002. }
  1003. if (line->text[j].codepoint == ':') {
  1004. *out_left = j;
  1005. return FLAG_TYPE;
  1006. }
  1007. }
  1008. }
  1009. return FLAG_NONE;
  1010. }
  1011. static char * syn_bimrc_keywords[] = {
  1012. "theme",
  1013. "padding",
  1014. NULL,
  1015. };
  1016. static int syn_bimrc_extended(line_t * line, int i, int c, int last, int * out_left) {
  1017. (void)last;
  1018. if (i == 0 && c == '#') {
  1019. *out_left = line->actual+1;
  1020. return FLAG_COMMENT;
  1021. }
  1022. return FLAG_NONE;
  1023. }
  1024. static char * syn_bimrc_ext[] = {".bimrc",NULL};
  1025. static int syn_gitcommit_extended(line_t * line, int i, int c, int last, int * out_left) {
  1026. (void)last;
  1027. if (c == '#') {
  1028. *out_left = (line->actual + 1) - i;
  1029. return FLAG_COMMENT;
  1030. }
  1031. return FLAG_NONE;
  1032. }
  1033. static char * syn_gitcommit_ext[] = {"COMMIT_EDITMSG",NULL};
  1034. static char * syn_gitrebase_commands[] = {
  1035. "p ","r ","e ","s ","f ","x "," d",
  1036. "pick ","reword ","edit ","squash ","fixup ",
  1037. "exec ","drop ",
  1038. NULL
  1039. };
  1040. static int syn_gitrebase_extended(line_t * line, int i, int c, int last, int * out_left) {
  1041. (void)last;
  1042. if (c == '#') {
  1043. *out_left = (line->actual + 1) - i;
  1044. return FLAG_COMMENT;
  1045. }
  1046. if (i == 0) {
  1047. int j = i;
  1048. for (int s = 0; syn_gitrebase_commands[s]; ++s) {
  1049. int d = 0;
  1050. while (j + d < line->actual && line->text[j+d].codepoint == syn_gitrebase_commands[s][d]) d++;
  1051. if (syn_gitrebase_commands[s][d] == '\0') {
  1052. *out_left = j+d-1;
  1053. return FLAG_KEYWORD;
  1054. }
  1055. }
  1056. }
  1057. if (i > 0 && (line->text[i-1].flags & FLAG_KEYWORD)) {
  1058. int j = i;
  1059. while (isxdigit(line->text[j].codepoint)) {
  1060. j++;
  1061. }
  1062. *out_left = j-i-1;
  1063. return FLAG_NUMERAL;
  1064. }
  1065. return FLAG_NONE;
  1066. }
  1067. static char * syn_gitrebase_ext[] = {"git-rebase-todo",NULL};
  1068. static int syn_diff_extended(line_t * line, int i, int c, int last, int * out_left) {
  1069. (void)last;
  1070. if (i == 0) {
  1071. if (c == '+') {
  1072. *out_left = (line->actual + 1);
  1073. return FLAG_DIFFPLUS;
  1074. } else if (c == '-') {
  1075. *out_left = (line->actual + 1);
  1076. return FLAG_DIFFMINUS;
  1077. } else if (c == '@') {
  1078. *out_left = (line->actual + 1);
  1079. return FLAG_TYPE;
  1080. } else if (c != ' ') {
  1081. *out_left = (line->actual + 1);
  1082. return FLAG_KEYWORD;
  1083. }
  1084. }
  1085. return FLAG_NONE;
  1086. }
  1087. static char * syn_diff_ext[] = {".diff",".patch",NULL};
  1088. static char * syn_rust_keywords[] = {
  1089. "as","break","const","continue","crate","else","enum","extern",
  1090. "false","fn","for","if","impl","in","let","loop","match","mod",
  1091. "move","mut","pub","ref","return","Self","self","static","struct",
  1092. "super","trait","true","type","unsafe","use","where","while",
  1093. NULL,
  1094. };
  1095. static char * syn_rust_types[] = {
  1096. "bool","char","str",
  1097. "i8","i16","i32","i64",
  1098. "u8","u16","u32","u64",
  1099. "isize","usize",
  1100. "f32","f64",
  1101. NULL,
  1102. };
  1103. static int syn_rust_extended(line_t * line, int i, int c, int last, int * out_left) {
  1104. if ((!last || !syn_c_iskeywordchar(last)) && isdigit(c)) {
  1105. if (c == '0' && i < line->actual - 1 && line->text[i+1].codepoint == 'x') {
  1106. int j = 2;
  1107. for (; i + j < line->actual && isxdigit(line->text[i+j].codepoint); ++j);
  1108. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  1109. return FLAG_NONE;
  1110. }
  1111. *out_left = j - 1;
  1112. return FLAG_NUMERAL;
  1113. } else {
  1114. int j = 1;
  1115. while (i + j < line->actual && isdigit(line->text[i+j].codepoint)) {
  1116. j++;
  1117. }
  1118. if (i + j < line->actual && syn_c_iskeywordchar(line->text[i+j].codepoint)) {
  1119. return FLAG_NONE;
  1120. }
  1121. *out_left = j - 1;
  1122. return FLAG_NUMERAL;
  1123. }
  1124. }
  1125. if (c == '/') {
  1126. if (i < line->actual - 1 && line->text[i+1].codepoint == '/') {
  1127. *out_left = (line->actual + 1) - i;
  1128. return FLAG_COMMENT;
  1129. }
  1130. /* TODO: We can't support Rust's nested comments with this... */
  1131. if (i < line->actual - 1 && line->text[i+1].codepoint == '*') {
  1132. int last = 0;
  1133. for (int j = i + 2; j < line->actual; ++j) {
  1134. int c = line->text[j].codepoint;
  1135. if (c == '/' && last == '*') {
  1136. *out_left = j - i;
  1137. return FLAG_COMMENT;
  1138. }
  1139. last = c;
  1140. }
  1141. *out_left = (line->actual + 1) - i;
  1142. return FLAG_COMMENT | FLAG_CONTINUES;
  1143. }
  1144. }
  1145. if (c == '\'') {
  1146. if (i < line->actual - 3 && line->text[i+1].codepoint == '\\' &&
  1147. line->text[i+3].codepoint == '\'') {
  1148. *out_left = 3;
  1149. return FLAG_NUMERAL;
  1150. }
  1151. if (i < line->actual - 2 && line->text[i+2].codepoint == '\'') {
  1152. *out_left = 2;
  1153. return FLAG_NUMERAL;
  1154. }
  1155. }
  1156. if (c == '"') {
  1157. int last = 0;
  1158. for (int j = i+1; j < line->actual; ++j) {
  1159. int c = line->text[j].codepoint;
  1160. if (last != '\\' && c == '"') {
  1161. *out_left = j - i;
  1162. return FLAG_STRING;
  1163. }
  1164. if (last == '\\' && c == '\\') {
  1165. last = 0;
  1166. }
  1167. last = c;
  1168. }
  1169. *out_left = (line->actual + 1) - i; /* unterminated string */
  1170. return FLAG_STRING;
  1171. }
  1172. return 0;
  1173. }
  1174. static int syn_rust_finish(line_t * line, int * left, int state) {
  1175. if (state == (FLAG_COMMENT | FLAG_CONTINUES)) {
  1176. int last = 0;
  1177. for (int i = 0; i < line->actual; ++i) {
  1178. if (line->text[i].codepoint == '/' && last == '*') {
  1179. *left = i+2;
  1180. return FLAG_COMMENT;
  1181. }
  1182. last = line->text[i].codepoint;
  1183. }
  1184. return FLAG_COMMENT | FLAG_CONTINUES;
  1185. }
  1186. return 0;
  1187. }
  1188. static char * syn_rust_ext[] = {".rs",NULL};
  1189. static int syn_conf_extended(line_t * line, int i, int c, int last, int * out_left) {
  1190. (void)last;
  1191. if (i == 0) {
  1192. if (c == ';') {
  1193. *out_left = (line->actual + 1) - i;
  1194. return FLAG_COMMENT;
  1195. }
  1196. if (c == '[') {
  1197. *out_left = (line->actual + 1) - i;
  1198. return FLAG_KEYWORD;
  1199. }
  1200. int j = 0;
  1201. for (; j < line->actual; ++j) {
  1202. if (line->text[j].codepoint == '=') {
  1203. *out_left = j;
  1204. return FLAG_TYPE;
  1205. }
  1206. }
  1207. }
  1208. return FLAG_NONE;
  1209. }
  1210. static char * syn_conf_ext[] = {".conf",NULL};
  1211. /**
  1212. * Syntax hilighting definition database
  1213. */
  1214. struct syntax_definition {
  1215. char * name;
  1216. char ** ext;
  1217. char ** keywords;
  1218. char ** types;
  1219. int (*extended)(line_t *, int, int, int, int *);
  1220. int (*iskwchar)(int);
  1221. int (*finishml)(line_t *, int *, int);
  1222. } syntaxes[] = {
  1223. {"c",syn_c_ext,syn_c_keywords,syn_c_types,syn_c_extended,syn_c_iskeywordchar,syn_c_finish},
  1224. {"python",syn_py_ext,syn_py_keywords,syn_py_types,syn_py_extended,syn_c_iskeywordchar,syn_py_finish},
  1225. {"esh",syn_sh_ext,syn_sh_keywords,NULL,syn_sh_extended,syn_sh_iskeywordchar,NULL},
  1226. {"make",syn_make_ext,NULL,NULL,syn_make_extended,NULL,NULL},
  1227. {"bimrc",syn_bimrc_ext,syn_bimrc_keywords,NULL,syn_bimrc_extended,syn_c_iskeywordchar,NULL},
  1228. {"gitcommit",syn_gitcommit_ext,NULL,NULL,syn_gitcommit_extended,NULL,NULL},
  1229. {"gitrebase",syn_gitrebase_ext,NULL,NULL,syn_gitrebase_extended,NULL,NULL},
  1230. {"diff",syn_diff_ext,NULL,NULL,syn_diff_extended,NULL,NULL},
  1231. {"rust",syn_rust_ext,syn_rust_keywords,syn_rust_types,syn_rust_extended,syn_c_iskeywordchar,syn_rust_finish},
  1232. {"conf",syn_conf_ext,NULL,NULL,syn_conf_extended,NULL,NULL},
  1233. {NULL}
  1234. };
  1235. /**
  1236. * Checks whether the character pointed to by `c` is the start of a match for
  1237. * keyword or type name `str`.
  1238. */
  1239. int check_line(line_t * line, int c, char * str, int last) {
  1240. if (env->syntax->iskwchar(last)) return 0;
  1241. for (int i = c; i < line->actual; ++i, ++str) {
  1242. if (*str == '\0' && !env->syntax->iskwchar(line->text[i].codepoint)) return 1;
  1243. if (line->text[i].codepoint == *str) continue;
  1244. return 0;
  1245. }
  1246. if (*str == '\0') return 1;
  1247. return 0;
  1248. }
  1249. /**
  1250. * Calculate syntax hilighting for the given line.
  1251. */
  1252. void recalculate_syntax(line_t * line, int offset) {
  1253. if (!env->syntax) {
  1254. for (int i = 0; i < line->actual; ++i) {
  1255. line->text[i].flags = 0;
  1256. }
  1257. return;
  1258. }
  1259. /* Start from the line's stored in initial state */
  1260. int state = line->istate;
  1261. int left = 0;
  1262. int last = 0;
  1263. if (state) {
  1264. /*
  1265. * If we are already highlighting coming in, then we need to check
  1266. * for a finishing sequence for the curent state.
  1267. */
  1268. state = env->syntax->finishml(line,&left,state);
  1269. if (state & FLAG_CONTINUES) {
  1270. /* The finish check said that this multiline state continues. */
  1271. for (int i = 0; i < line->actual; i++) {
  1272. /* Set the entire line to draw with this state */
  1273. line->text[i].flags = state;
  1274. }
  1275. /* Recalculate later lines if needed */
  1276. goto _multiline;
  1277. }
  1278. }
  1279. for (int i = 0; i < line->actual; last = line->text[i++].codepoint) {
  1280. if (!left) state = 0;
  1281. if (state) {
  1282. /* Currently hilighting, have `left` characters remaining with this state */
  1283. left--;
  1284. line->text[i].flags = state;
  1285. if (!left) {
  1286. /* Done hilighting this state, go back to parsing on next character */
  1287. state = 0;
  1288. }
  1289. /* If we are hilighting something, don't parse */
  1290. continue;
  1291. }
  1292. int c = line->text[i].codepoint;
  1293. line->text[i].flags = FLAG_NONE;
  1294. /* Language-specific syntax hilighting */
  1295. if (env->syntax->extended) {
  1296. int s = env->syntax->extended(line,i,c,last,&left);
  1297. if (s) {
  1298. state = s;
  1299. if (state & FLAG_CONTINUES) {
  1300. /* A multiline state was returned. Fill the rest of the line */
  1301. for (; i < line->actual; i++) {
  1302. line->text[i].flags = state;
  1303. }
  1304. /* And recalculate later lines if needed */
  1305. goto _multiline;
  1306. }
  1307. goto _continue;
  1308. }
  1309. }
  1310. /* Keywords */
  1311. if (env->syntax->keywords) {
  1312. for (char ** kw = env->syntax->keywords; *kw; kw++) {
  1313. int c = check_line(line, i, *kw, last);
  1314. if (c == 1) {
  1315. left = strlen(*kw)-1;
  1316. state = FLAG_KEYWORD;
  1317. goto _continue;
  1318. }
  1319. }
  1320. }
  1321. /* Type names */
  1322. if (env->syntax->types) {
  1323. for (char ** kw = env->syntax->types; *kw; kw++) {
  1324. int c = check_line(line, i, *kw, last);
  1325. if (c == 1) {
  1326. left = strlen(*kw)-1;
  1327. state = FLAG_TYPE;
  1328. goto _continue;
  1329. }
  1330. }
  1331. }
  1332. _continue:
  1333. line->text[i].flags = state;
  1334. }
  1335. state = 0;
  1336. _multiline:
  1337. /*
  1338. * If the next line's initial state does not match the state we ended on,
  1339. * then it needs to be recalculated (and redraw). This may lead to multiple
  1340. * recursive calls until a match is found.
  1341. */
  1342. if (offset + 1 < env->line_count && env->lines[offset+1]->istate != state) {
  1343. /* Set the next line's initial state to our ending state */
  1344. env->lines[offset+1]->istate = state;
  1345. /* Recursively recalculate */
  1346. recalculate_syntax(env->lines[offset+1],offset+1);
  1347. /*
  1348. * Determine if this is an on-screen line so we can redraw it;
  1349. * this ends up drawing from bottom to top when multiple lines
  1350. * need to be redrawn by a recursive call.
  1351. */
  1352. if (offset+1 >= env->offset && offset+1 < env->offset + global_config.term_height - global_config.bottom_size - 1) {
  1353. redraw_line(offset + 1 - env->offset,offset+1);
  1354. }
  1355. }
  1356. }
  1357. /**
  1358. * Recalculate tab widths.
  1359. */
  1360. void recalculate_tabs(line_t * line) {
  1361. if (env->loading) return;
  1362. int j = 0;
  1363. for (int i = 0; i < line->actual; ++i) {
  1364. if (line->text[i].codepoint == '\t') {
  1365. line->text[i].display_width = env->tabstop - (j % env->tabstop);
  1366. }
  1367. j += line->text[i].display_width;
  1368. }
  1369. }
  1370. /**
  1371. * TODO:
  1372. *
  1373. * The line editing functions should probably take a buffer_t *
  1374. * so that they can act on buffers other than the active one.
  1375. */
  1376. void recursive_history_free(history_t * root) {
  1377. if (!root->next) return;
  1378. history_t * n = root->next;
  1379. recursive_history_free(n);
  1380. switch (n->type) {
  1381. case HISTORY_REPLACE_LINE:
  1382. free(n->contents.remove_replace_line.contents);
  1383. /* fall-through */
  1384. case HISTORY_REMOVE_LINE:
  1385. free(n->contents.remove_replace_line.old_contents);
  1386. break;
  1387. default:
  1388. /* Nothing extra to free */
  1389. break;
  1390. }
  1391. free(n);
  1392. root->next = NULL;
  1393. }
  1394. #define HIST_APPEND(e) do { \
  1395. if (env->history) { \
  1396. e->previous = env->history; \
  1397. recursive_history_free(env->history); \
  1398. env->history->next = e; \
  1399. e->next = NULL; \
  1400. } \
  1401. env->history = e; \
  1402. } while (0)
  1403. /**
  1404. * Mark a point where a complete set of actions has ended.
  1405. */
  1406. void set_history_break(void) {
  1407. if (!global_config.history_enabled) return;
  1408. if (env->history->type != HISTORY_BREAK && env->history->type != HISTORY_SENTINEL) {
  1409. history_t * e = malloc(sizeof(history_t));
  1410. e->type = HISTORY_BREAK;
  1411. HIST_APPEND(e);
  1412. }
  1413. }
  1414. /**
  1415. * Insert a character into an existing line.
  1416. */
  1417. line_t * line_insert(line_t * line, char_t c, int offset, int lineno) {
  1418. if (!env->loading && global_config.history_enabled) {
  1419. history_t * e = malloc(sizeof(history_t));
  1420. e->type = HISTORY_INSERT;
  1421. e->contents.insert_delete_replace.lineno = lineno;
  1422. e->contents.insert_delete_replace.offset = offset;
  1423. e->contents.insert_delete_replace.codepoint = c.codepoint;
  1424. HIST_APPEND(e);
  1425. }
  1426. /* If there is not enough space... */
  1427. if (line->actual == line->available) {
  1428. /* Expand the line buffer */
  1429. if (line->available == 0) {
  1430. line->available = 8;
  1431. } else {
  1432. line->available *= 2;
  1433. }
  1434. line = realloc(line, sizeof(line_t) + sizeof(char_t) * line->available);
  1435. }
  1436. /* If this was not the last character, then shift remaining characters forward. */
  1437. if (offset < line->actual) {
  1438. memmove(&line->text[offset+1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1439. }
  1440. /* Insert the new character */
  1441. line->text[offset] = c;
  1442. /* There is one new character in the line */
  1443. line->actual += 1;
  1444. if (!env->loading) {
  1445. recalculate_tabs(line);
  1446. recalculate_syntax(line, lineno);
  1447. }
  1448. return line;
  1449. }
  1450. /**
  1451. * Delete a character from a line
  1452. */
  1453. void line_delete(line_t * line, int offset, int lineno) {
  1454. /* Can't delete character before start of line. */
  1455. if (offset == 0) return;
  1456. if (!env->loading && global_config.history_enabled) {
  1457. history_t * e = malloc(sizeof(history_t));
  1458. e->type = HISTORY_DELETE;
  1459. e->contents.insert_delete_replace.lineno = lineno;
  1460. e->contents.insert_delete_replace.offset = offset;
  1461. e->contents.insert_delete_replace.old_codepoint = line->text[offset-1].codepoint;
  1462. HIST_APPEND(e);
  1463. }
  1464. /* If this isn't the last character, we need to move all subsequent characters backwards */
  1465. if (offset < line->actual) {
  1466. memmove(&line->text[offset-1], &line->text[offset], sizeof(char_t) * (line->actual - offset));
  1467. }
  1468. /* The line is one character shorter */
  1469. line->actual -= 1;
  1470. recalculate_tabs(line);
  1471. recalculate_syntax(line, lineno);
  1472. }
  1473. /**
  1474. * Replace a character in a line
  1475. */
  1476. void line_replace(line_t * line, char_t _c, int offset, int lineno) {
  1477. if (!env->loading && global_config.history_enabled) {
  1478. history_t * e = malloc(sizeof(history_t));
  1479. e->type = HISTORY_REPLACE;
  1480. e->contents.insert_delete_replace.lineno = lineno;
  1481. e->contents.insert_delete_replace.offset = offset;
  1482. e->contents.insert_delete_replace.codepoint = _c.codepoint;
  1483. e->contents.insert_delete_replace.old_codepoint = line->text[offset].codepoint;
  1484. HIST_APPEND(e);
  1485. }
  1486. line->text[offset] = _c;
  1487. if (!env->loading) {
  1488. recalculate_tabs(line);
  1489. recalculate_syntax(line, lineno);
  1490. }
  1491. }
  1492. /**
  1493. * Remove a line from the active buffer
  1494. */
  1495. line_t ** remove_line(line_t ** lines, int offset) {
  1496. /* If there is only one line, clear it instead of removing it. */
  1497. if (env->line_count == 1) {
  1498. while (lines[offset]->actual > 0) {
  1499. line_delete(lines[offset], lines[offset]->actual, offset);
  1500. }
  1501. return lines;
  1502. }
  1503. if (!env->loading && global_config.history_enabled) {
  1504. history_t * e = malloc(sizeof(history_t));
  1505. e->type = HISTORY_REMOVE_LINE;
  1506. e->contents.remove_replace_line.lineno = offset;
  1507. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1508. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1509. HIST_APPEND(e);
  1510. }
  1511. /* Otherwise, free the data used by the line */
  1512. free(lines[offset]);
  1513. /* Move other lines up */
  1514. if (offset < env->line_count-1) {
  1515. memmove(&lines[offset], &lines[offset+1], sizeof(line_t *) * (env->line_count - (offset - 1)));
  1516. lines[env->line_count-1] = NULL;
  1517. }
  1518. /* There is one less line */
  1519. env->line_count -= 1;
  1520. return lines;
  1521. }
  1522. /**
  1523. * Add a new line to the active buffer.
  1524. */
  1525. line_t ** add_line(line_t ** lines, int offset) {
  1526. /* Invalid offset? */
  1527. if (offset > env->line_count) return lines;
  1528. if (!env->loading && global_config.history_enabled) {
  1529. history_t * e = malloc(sizeof(history_t));
  1530. e->type = HISTORY_ADD_LINE;
  1531. e->contents.add_merge_split_lines.lineno = offset;
  1532. HIST_APPEND(e);
  1533. }
  1534. /* Not enough space */
  1535. if (env->line_count == env->line_avail) {
  1536. /* Allocate more space */
  1537. env->line_avail *= 2;
  1538. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1539. }
  1540. /* If this isn't the last line, move other lines down */
  1541. if (offset < env->line_count) {
  1542. memmove(&lines[offset+1], &lines[offset], sizeof(line_t *) * (env->line_count - offset));
  1543. }
  1544. /* Allocate the new line */
  1545. lines[offset] = malloc(sizeof(line_t) + sizeof(char_t) * 32);
  1546. lines[offset]->available = 32;
  1547. lines[offset]->actual = 0;
  1548. lines[offset]->istate = 0;
  1549. lines[offset]->is_current = 0;
  1550. /* There is one new line */
  1551. env->line_count += 1;
  1552. env->lines = lines;
  1553. if (offset > 0 && !env->loading) {
  1554. recalculate_syntax(lines[offset-1],offset-1);
  1555. }
  1556. return lines;
  1557. }
  1558. /**
  1559. * Replace a line with data from another line (used by paste to paste yanked lines)
  1560. */
  1561. void replace_line(line_t ** lines, int offset, line_t * replacement) {
  1562. if (!env->loading && global_config.history_enabled) {
  1563. history_t * e = malloc(sizeof(history_t));
  1564. e->type = HISTORY_REPLACE_LINE;
  1565. e->contents.remove_replace_line.lineno = offset;
  1566. e->contents.remove_replace_line.old_contents = malloc(sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1567. memcpy(e->contents.remove_replace_line.old_contents, lines[offset], sizeof(line_t) + sizeof(char_t) * lines[offset]->available);
  1568. e->contents.remove_replace_line.contents = malloc(sizeof(line_t) + sizeof(char_t) * replacement->available);
  1569. memcpy(e->contents.remove_replace_line.contents, replacement, sizeof(line_t) + sizeof(char_t) * replacement->available);
  1570. HIST_APPEND(e);
  1571. }
  1572. if (lines[offset]->available < replacement->actual) {
  1573. lines[offset] = realloc(lines[offset], sizeof(line_t) + sizeof(char_t) * replacement->available);
  1574. lines[offset]->available = replacement->available;
  1575. }
  1576. lines[offset]->actual = replacement->actual;
  1577. memcpy(&lines[offset]->text, &replacement->text, sizeof(char_t) * replacement->actual);
  1578. if (!env->loading) {
  1579. recalculate_syntax(lines[offset],offset);
  1580. }
  1581. }
  1582. /**
  1583. * Merge two consecutive lines.
  1584. * lineb is the offset of the second line.
  1585. */
  1586. line_t ** merge_lines(line_t ** lines, int lineb) {
  1587. /* linea is the line immediately before lineb */
  1588. int linea = lineb - 1;
  1589. if (!env->loading && global_config.history_enabled) {
  1590. history_t * e = malloc(sizeof(history_t));
  1591. e->type = HISTORY_MERGE_LINES;
  1592. e->contents.add_merge_split_lines.lineno = lineb;
  1593. e->contents.add_merge_split_lines.split = env->lines[linea]->actual;
  1594. HIST_APPEND(e);
  1595. }
  1596. /* If there isn't enough space in linea hold both... */
  1597. while (lines[linea]->available < lines[linea]->actual + lines[lineb]->actual) {
  1598. /* ... allocate more space until it fits */
  1599. if (lines[linea]->available == 0) {
  1600. lines[linea]->available = 8;
  1601. } else {
  1602. lines[linea]->available *= 2;
  1603. }
  1604. /* XXX why not just do this once after calculating appropriate size */
  1605. lines[linea] = realloc(lines[linea], sizeof(line_t) + sizeof(char_t) * lines[linea]->available);
  1606. }
  1607. /* Copy the second line into the first line */
  1608. memcpy(&lines[linea]->text[lines[linea]->actual], &lines[lineb]->text, sizeof(char_t) * lines[lineb]->actual);
  1609. /* The first line is now longer */
  1610. lines[linea]->actual = lines[linea]->actual + lines[lineb]->actual;
  1611. if (!env->loading) {
  1612. recalculate_tabs(lines[linea]);
  1613. recalculate_syntax(lines[linea], linea);
  1614. }
  1615. /* Remove the second line */
  1616. free(lines[lineb]);
  1617. /* Move other lines up */
  1618. if (lineb < env->line_count) {
  1619. memmove(&lines[lineb], &lines[lineb+1], sizeof(line_t *) * (env->line_count - (lineb - 1)));
  1620. lines[env->line_count-1] = NULL;
  1621. }
  1622. /* There is one less line */
  1623. env->line_count -= 1;
  1624. return lines;
  1625. }
  1626. /**
  1627. * Split a line into two lines at the given column
  1628. */
  1629. line_t ** split_line(line_t ** lines, int line, int split) {
  1630. /* If we're trying to split from the start, just add a new blank line before */
  1631. if (split == 0) {
  1632. return add_line(lines, line);
  1633. }
  1634. if (!env->loading && global_config.history_enabled) {
  1635. history_t * e = malloc(sizeof(history_t));
  1636. e->type = HISTORY_SPLIT_LINE;
  1637. e->contents.add_merge_split_lines.lineno = line;
  1638. e->contents.add_merge_split_lines.split = split;
  1639. HIST_APPEND(e);
  1640. }
  1641. /* Allocate more space as needed */
  1642. if (env->line_count == env->line_avail) {
  1643. env->line_avail *= 2;
  1644. lines = realloc(lines, sizeof(line_t *) * env->line_avail);
  1645. }
  1646. /* Shift later lines down */
  1647. if (line < env->line_count) {
  1648. memmove(&lines[line+2], &lines[line+1], sizeof(line_t *) * (env->line_count - line));
  1649. }
  1650. /* I have no idea what this is doing */
  1651. int remaining = lines[line]->actual - split;
  1652. int v = remaining;
  1653. v--;
  1654. v |= v >> 1;
  1655. v |= v >> 2;
  1656. v |= v >> 4;
  1657. v |= v >> 8;
  1658. v |= v >> 16;
  1659. v++;
  1660. /* Allocate space for the new line */
  1661. lines[line+1] = malloc(sizeof(line_t) + sizeof(char_t) * v);
  1662. lines[line+1]->available = v;
  1663. lines[line+1]->actual = remaining;
  1664. lines[line+1]->istate = 0;
  1665. lines[line+1]->is_current = 0;
  1666. /* Move the data from the old line into the new line */
  1667. memmove(lines[line+1]->text, &lines[line]->text[split], sizeof(char_t) * remaining);
  1668. lines[line]->actual = split;
  1669. if (!env->loading) {
  1670. recalculate_tabs(lines[line]);
  1671. recalculate_tabs(lines[line+1]);
  1672. recalculate_syntax(lines[line], line);
  1673. recalculate_syntax(lines[line+1], line+1);
  1674. }
  1675. /* There is one new line */
  1676. env->line_count += 1;
  1677. /* We may have reallocated lines */
  1678. return lines;
  1679. }
  1680. /**
  1681. * Add indentation from the previous (temporally) line
  1682. */
  1683. void add_indent(int new_line, int old_line, int ignore_brace) {
  1684. if (env->indent) {
  1685. int changed = 0;
  1686. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1687. if (env->lines[old_line]->text[i].codepoint == ' ' ||
  1688. env->lines[old_line]->text[i].codepoint == '\t') {
  1689. env->lines[new_line] = line_insert(env->lines[new_line],env->lines[old_line]->text[i],i,new_line);
  1690. env->col_no++;
  1691. changed = 1;
  1692. } else {
  1693. break;
  1694. }
  1695. }
  1696. if (old_line < new_line && !ignore_brace &&
  1697. (env->lines[old_line]->text[env->lines[old_line]->actual-1].codepoint == '{' ||
  1698. env->lines[old_line]->text[env->lines[old_line]->actual-1].codepoint == ':')) {
  1699. if (env->tabs) {
  1700. char_t c;
  1701. c.codepoint = '\t';
  1702. c.display_width = env->tabstop;
  1703. env->lines[new_line] = line_insert(env->lines[new_line], c, env->lines[new_line]->actual, new_line);
  1704. env->col_no++;
  1705. changed = 1;
  1706. } else {
  1707. for (int j = 0; j < env->tabstop; ++j) {
  1708. char_t c;
  1709. c.codepoint = ' ';
  1710. c.display_width = 1;
  1711. c.flags = FLAG_SELECT;
  1712. env->lines[new_line] = line_insert(env->lines[new_line], c, env->lines[new_line]->actual, new_line);
  1713. env->col_no++;
  1714. }
  1715. changed = 1;
  1716. }
  1717. }
  1718. int was_whitespace = 1;
  1719. for (int i = 0; i < env->lines[old_line]->actual; ++i) {
  1720. if (env->lines[old_line]->text[i].codepoint != ' ' &&
  1721. env->lines[old_line]->text[i].codepoint != '\t') {
  1722. was_whitespace = 0;
  1723. break;
  1724. }
  1725. }
  1726. if (was_whitespace) {
  1727. while (env->lines[old_line]->actual) {
  1728. line_delete(env->lines[old_line], env->lines[old_line]->actual, old_line);
  1729. }
  1730. }
  1731. if (changed) {
  1732. recalculate_syntax(env->lines[new_line],new_line);
  1733. }
  1734. }
  1735. }
  1736. /**
  1737. * Initialize a buffer with default values
  1738. */
  1739. void setup_buffer(buffer_t * env) {
  1740. /* If this buffer was already initialized, clear out its line data */
  1741. if (env->lines) {
  1742. for (int i = 0; i < env->line_count; ++i) {
  1743. free(env->lines[i]);
  1744. }
  1745. free(env->lines);
  1746. }
  1747. /* Default state parameters */
  1748. env->line_no = 1; /* Default cursor position */
  1749. env->col_no = 1;
  1750. env->line_count = 1; /* Buffers always have at least one line */
  1751. env->modified = 0;
  1752. env->readonly = 0;
  1753. env->offset = 0;
  1754. env->line_avail = 8; /* Default line buffer capacity */
  1755. env->tabs = 1; /* Tabs by default */
  1756. env->tabstop = 4; /* Tab stop width */
  1757. env->indent = 1; /* Auto-indent by default */
  1758. env->history = malloc(sizeof(struct history));
  1759. memset(env->history, 0, sizeof(struct history));
  1760. env->last_save_history = env->history;
  1761. /* Allocate line buffer */
  1762. env->lines = malloc(sizeof(line_t *) * env->line_avail);
  1763. /* Initialize the first line */
  1764. env->lines[0] = malloc(sizeof(line_t) + sizeof(char_t) * 32);
  1765. env->lines[0]->available = 32;
  1766. env->lines[0]->actual = 0;
  1767. env->lines[0]->istate = 0;
  1768. env->lines[0]->is_current = 0;
  1769. }
  1770. /**
  1771. * Toggle buffered / unbuffered modes
  1772. */
  1773. struct termios old;
  1774. void get_initial_termios(void) {
  1775. tcgetattr(STDOUT_FILENO, &old);
  1776. }
  1777. void set_unbuffered(void) {
  1778. struct termios new = old;
  1779. new.c_iflag &= (~ICRNL);
  1780. new.c_lflag &= (~ICANON) & (~ECHO);
  1781. new.c_cc[VINTR] = 0;
  1782. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &new);
  1783. }
  1784. void set_buffered(void) {
  1785. tcsetattr(STDOUT_FILENO, TCSAFLUSH, &old);
  1786. }
  1787. /**
  1788. * Convert codepoint to utf-8 string
  1789. */
  1790. int to_eight(uint32_t codepoint, char * out) {
  1791. memset(out, 0x00, 7);
  1792. if (codepoint < 0x0080) {
  1793. out[0] = (char)codepoint;
  1794. } else if (codepoint < 0x0800) {
  1795. out[0] = 0xC0 | (codepoint >> 6);
  1796. out[1] = 0x80 | (codepoint & 0x3F);
  1797. } else if (codepoint < 0x10000) {
  1798. out[0] = 0xE0 | (codepoint >> 12);
  1799. out[1] = 0x80 | ((codepoint >> 6) & 0x3F);
  1800. out[2] = 0x80 | (codepoint & 0x3F);
  1801. } else if (codepoint < 0x200000) {
  1802. out[0] = 0xF0 | (codepoint >> 18);
  1803. out[1] = 0x80 | ((codepoint >> 12) & 0x3F);
  1804. out[2] = 0x80 | ((codepoint >> 6) & 0x3F);
  1805. out[3] = 0x80 | ((codepoint) & 0x3F);
  1806. } else if (codepoint < 0x4000000) {
  1807. out[0] = 0xF8 | (codepoint >> 24);
  1808. out[1] = 0x80 | (codepoint >> 18);
  1809. out[2] = 0x80 | ((codepoint >> 12) & 0x3F);
  1810. out[3] = 0x80 | ((codepoint >> 6) & 0x3F);
  1811. out[4] = 0x80 | ((codepoint) & 0x3F);
  1812. } else {
  1813. out[0] = 0xF8 | (codepoint >> 30);
  1814. out[1] = 0x80 | ((codepoint >> 24) & 0x3F);
  1815. out[2] = 0x80 | ((codepoint >> 18) & 0x3F);
  1816. out[3] = 0x80 | ((codepoint >> 12) & 0x3F);
  1817. out[4] = 0x80 | ((codepoint >> 6) & 0x3F);
  1818. out[5] = 0x80 | ((codepoint) & 0x3F);
  1819. }
  1820. return strlen(out);
  1821. }
  1822. /**
  1823. * Get the presentation width of a codepoint
  1824. */
  1825. int codepoint_width(wchar_t codepoint) {
  1826. if (codepoint == '\t') {
  1827. return 1; /* Recalculate later */
  1828. }
  1829. if (codepoint < 32) {
  1830. /* We render these as ^@ */
  1831. return 2;
  1832. }
  1833. if (codepoint == 0x7F) {
  1834. /* Renders as ^? */
  1835. return 2;
  1836. }
  1837. if (codepoint > 0x7f && codepoint < 0xa0) {
  1838. /* Upper control bytes <xx> */
  1839. return 4;
  1840. }
  1841. if (codepoint == 0xa0) {
  1842. /* Non-breaking space _ */
  1843. return 1;
  1844. }
  1845. /* Skip wcwidth for anything under 256 */
  1846. if (codepoint > 256) {
  1847. if (global_config.can_unicode) {
  1848. /* Higher codepoints may be wider (eg. Japanese) */
  1849. int out = wcwidth(codepoint);
  1850. if (out >= 1) return out;
  1851. }
  1852. /* Invalid character, render as [U+ABCD] or [U+ABCDEF] */
  1853. return (codepoint < 0x10000) ? 8 : 10;
  1854. }
  1855. return 1;
  1856. }
  1857. /**
  1858. * Move the terminal cursor
  1859. */
  1860. void place_cursor(int x, int y) {
  1861. printf("\033[%d;%dH", y, x);
  1862. fflush(stdout);
  1863. }
  1864. /**
  1865. * Set text colors
  1866. *
  1867. * Normally, text colors are just strings, but if they
  1868. * start with @ they will be parsed as integers
  1869. * representing one of the 16 standard colors, suitable
  1870. * for terminals without support for the 256- or 24-bit
  1871. * color modes.
  1872. */
  1873. void set_colors(const char * fg, const char * bg) {
  1874. printf("\033[22;23;");
  1875. if (*bg == '@') {
  1876. int _bg = atoi(bg+1);
  1877. if (_bg < 10) {
  1878. printf("4%d;", _bg);
  1879. } else {
  1880. printf("10%d;", _bg-10);
  1881. }
  1882. } else {
  1883. printf("48;%s;", bg);
  1884. }
  1885. if (*fg == '@') {
  1886. int _fg = atoi(fg+1);
  1887. if (_fg < 10) {
  1888. printf("3%dm", _fg);
  1889. } else {
  1890. printf("9%dm", _fg-10);
  1891. }
  1892. } else {
  1893. printf("38;%sm", fg);
  1894. }
  1895. fflush(stdout);
  1896. }
  1897. /**
  1898. * Set just the foreground color
  1899. *
  1900. * (See set_colors above)
  1901. */
  1902. void set_fg_color(const char * fg) {
  1903. printf("\033[22;23;");
  1904. if (*fg == '@') {
  1905. int _fg = atoi(fg+1);
  1906. if (_fg < 10) {
  1907. printf("3%dm", _fg);
  1908. } else {
  1909. printf("9%dm", _fg-10);
  1910. }
  1911. } else {
  1912. printf("38;%sm", fg);
  1913. }
  1914. fflush(stdout);
  1915. }
  1916. /**
  1917. * Clear the rest of this line
  1918. */
  1919. void clear_to_end(void) {
  1920. if (global_config.can_bce) {
  1921. printf("\033[K");
  1922. fflush(stdout);
  1923. }
  1924. }
  1925. /**
  1926. * For terminals without bce,
  1927. * prepaint the whole line, so we don't have to track
  1928. * where the cursor is for everything. Inefficient,
  1929. * but effective.
  1930. */
  1931. void paint_line(const char * bg) {
  1932. if (!global_config.can_bce) {
  1933. set_colors(COLOR_FG, bg);
  1934. for (int i = 0; i < global_config.term_width; ++i) {
  1935. printf(" ");
  1936. }
  1937. printf("\r");
  1938. }
  1939. }
  1940. /**
  1941. * Enable bold text display
  1942. */
  1943. void set_bold(void) {
  1944. printf("\033[1m");
  1945. fflush(stdout);
  1946. }
  1947. /**
  1948. * Enable underlined text display
  1949. */
  1950. void set_underline(void) {
  1951. printf("\033[4m");
  1952. fflush(stdout);
  1953. }
  1954. /**
  1955. * Reset text display attributes
  1956. */
  1957. void reset(void) {
  1958. printf("\033[0m");
  1959. fflush(stdout);
  1960. }
  1961. /**
  1962. * Clear the entire screen
  1963. */
  1964. void clear_screen(void) {
  1965. printf("\033[H\033[2J");
  1966. fflush(stdout);
  1967. }
  1968. /**
  1969. * Hide the cursor
  1970. */
  1971. void hide_cursor(void) {
  1972. if (global_config.can_hideshow) {
  1973. printf("\033[?25l");
  1974. }
  1975. fflush(stdout);
  1976. }
  1977. /*
  1978. * Show the cursor
  1979. */
  1980. void show_cursor(void) {
  1981. if (global_config.can_hideshow) {
  1982. printf("\033[?25h");
  1983. }
  1984. fflush(stdout);
  1985. }
  1986. /**
  1987. * Request mouse events
  1988. */
  1989. void mouse_enable(void) {
  1990. if (global_config.can_mouse) {
  1991. printf("\033[?1000h");
  1992. }
  1993. fflush(stdout);
  1994. }
  1995. /**
  1996. * Stop mouse events
  1997. */
  1998. void mouse_disable(void) {
  1999. if (global_config.can_mouse) {
  2000. printf("\033[?1000l");
  2001. }
  2002. fflush(stdout);
  2003. }
  2004. /**
  2005. * Shift the screen up one line
  2006. */
  2007. void shift_up(void) {
  2008. printf("\033[1S");
  2009. }
  2010. /**
  2011. * Shift the screen down one line.
  2012. */
  2013. void shift_down(void) {
  2014. printf("\033[1T");
  2015. }
  2016. /**
  2017. * Switch to the alternate terminal screen.
  2018. */
  2019. void set_alternate_screen(void) {
  2020. if (global_config.can_altscreen) {
  2021. printf("\033[?1049h");
  2022. }
  2023. }
  2024. /**
  2025. * Restore the standard terminal screen.
  2026. */
  2027. void unset_alternate_screen(void) {
  2028. if (global_config.can_altscreen) {
  2029. printf("\033[?1049l");
  2030. }
  2031. }
  2032. char * file_basename(char * file) {
  2033. char * c = strrchr(file, '/');
  2034. if (!c) return file;
  2035. return (c+1);
  2036. }
  2037. int draw_tab_name(buffer_t * _env, char * out) {
  2038. return sprintf(out, "%s %.40s ",
  2039. _env->modified ? " +" : "",
  2040. _env->file_name ? file_basename(_env->file_name) : "[No Name]");
  2041. }
  2042. /**
  2043. * Redaw the tabbar, with a tab for each buffer.
  2044. *
  2045. * The active buffer is highlighted.
  2046. */
  2047. void redraw_tabbar(void) {
  2048. /* Hide cursor while rendering UI */
  2049. hide_cursor();
  2050. /* Move to upper left */
  2051. place_cursor(1,1);
  2052. paint_line(COLOR_TABBAR_BG);
  2053. /* For each buffer... */
  2054. int offset = 0;
  2055. for (int i = 0; i < buffers_len; i++) {
  2056. buffer_t * _env = buffers[i];
  2057. if (_env == env) {
  2058. /* If this is the active buffer, hilight it */
  2059. reset();
  2060. set_colors(COLOR_FG, COLOR_BG);
  2061. set_bold();
  2062. } else {
  2063. /* Otherwise use default tab color */
  2064. reset();
  2065. set_colors(COLOR_FG, COLOR_TAB_BG);
  2066. set_underline();
  2067. }
  2068. char title[64];
  2069. int size = draw_tab_name(_env, title);
  2070. if (offset + size >= global_config.term_width) {
  2071. if (global_config.term_width - offset - 1 > 0) {
  2072. printf("%*s", global_config.term_width - offset - 1, title);
  2073. }
  2074. break;
  2075. } else {
  2076. printf("%s", title);
  2077. }
  2078. offset += size;
  2079. }
  2080. /* Reset bold/underline */
  2081. reset();
  2082. /* Fill the rest of the tab bar */
  2083. set_colors(COLOR_FG, COLOR_TABBAR_BG);
  2084. clear_to_end();
  2085. }
  2086. /**
  2087. * Braindead log10 implementation for the line numbers
  2088. */
  2089. int log_base_10(unsigned int v) {
  2090. int r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
  2091. (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
  2092. (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
  2093. return r;
  2094. }
  2095. /**
  2096. * Render a line of text
  2097. *
  2098. * This handles rendering the actual text content. A full line of text
  2099. * also includes a line number and some padding.
  2100. *
  2101. * width: width of the text display region (term width - line number width)
  2102. * offset: how many cells into the line to start rendering at
  2103. */
  2104. void render_line(line_t * line, int width, int offset) {
  2105. int i = 0; /* Offset in char_t line data entries */
  2106. int j = 0; /* Offset in terminal cells */
  2107. const char * last_color = NULL;
  2108. int was_selecting = 0, was_searching = 0;
  2109. /* Set default text colors */
  2110. set_colors(COLOR_FG, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2111. /*
  2112. * When we are rendering in the middle of a wide character,
  2113. * we render -'s to fill the remaining amount of the
  2114. * charater's width
  2115. */
  2116. int remainder = 0;
  2117. /* For each character in the line ... */
  2118. while (i < line->actual) {
  2119. /* If there is remaining text... */
  2120. if (remainder) {
  2121. /* If we should be drawing by now... */
  2122. if (j >= offset) {
  2123. /* Fill remainder with -'s */
  2124. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2125. printf("-");
  2126. set_colors(COLOR_FG, COLOR_BG);
  2127. }
  2128. /* One less remaining width cell to fill */
  2129. remainder--;
  2130. /* Terminal offset moves forward */
  2131. j++;
  2132. /*
  2133. * If this was the last remaining character, move to
  2134. * the next codepoint in the line
  2135. */
  2136. if (remainder == 0) {
  2137. i++;
  2138. }
  2139. continue;
  2140. }
  2141. /* Get the next character to draw */
  2142. char_t c = line->text[i];
  2143. /* If we should be drawing by now... */
  2144. if (j >= offset) {
  2145. /* If this character is going to fall off the edge of the screen... */
  2146. if (j - offset + c.display_width >= width) {
  2147. /* We draw this with special colors so it isn't ambiguous */
  2148. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2149. /* If it's wide, draw ---> as needed */
  2150. while (j - offset < width - 1) {
  2151. printf("-");
  2152. j++;
  2153. }
  2154. /* End the line with a > to show it overflows */
  2155. printf(">");
  2156. set_colors(COLOR_FG, COLOR_BG);
  2157. return;
  2158. }
  2159. /* Syntax hilighting */
  2160. const char * color = flag_to_color(c.flags);
  2161. if (c.flags & FLAG_SELECT) {
  2162. set_colors(COLOR_SELECTFG, COLOR_SELECTBG);
  2163. was_selecting = 1;
  2164. } else if (c.flags & FLAG_SEARCH) {
  2165. set_colors(COLOR_SEARCH_FG, COLOR_SEARCH_BG);
  2166. was_searching = 1;
  2167. } else {
  2168. if (was_selecting || was_searching) {
  2169. set_colors(color, line->is_current ? COLOR_ALT_BG : COLOR_BG);
  2170. last_color = color;
  2171. } else if (!last_color || strcmp(color, last_color)) {
  2172. set_fg_color(color);
  2173. last_color = color;
  2174. }
  2175. }
  2176. #define _set_colors(fg,bg) \
  2177. if (!(c.flags & FLAG_SELECT)) { \
  2178. set_colors(fg,(line->is_current && bg == COLOR_BG) ? COLOR_ALT_BG : bg); \
  2179. }
  2180. /* Render special characters */
  2181. if (c.codepoint == '\t') {
  2182. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2183. if (global_config.can_unicode) {
  2184. printf("»");
  2185. for (int i = 1; i < c.display_width; ++i) {
  2186. printf("·");
  2187. }
  2188. } else {
  2189. printf(">");
  2190. for (int i = 1; i < c.display_width; ++i) {
  2191. printf("-");
  2192. }
  2193. }
  2194. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2195. } else if (c.codepoint < 32) {
  2196. /* Codepoints under 32 to get converted to ^@ escapes */
  2197. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2198. printf("^%c", '@' + c.codepoint);
  2199. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2200. } else if (c.codepoint == 0x7f) {
  2201. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2202. printf("^?");
  2203. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2204. } else if (c.codepoint > 0x7f && c.codepoint < 0xa0) {
  2205. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2206. printf("<%2x>", c.codepoint);
  2207. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2208. } else if (c.codepoint == 0xa0) {
  2209. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2210. printf("_");
  2211. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2212. } else if (c.display_width == 8) {
  2213. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2214. printf("[U+%04x]", c.codepoint);
  2215. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2216. } else if (c.display_width == 10) {
  2217. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2218. printf("[U+%06x]", c.codepoint);
  2219. _set_colors(last_color ? last_color : COLOR_FG, COLOR_BG);
  2220. } else if (c.codepoint == ' ' && i == line->actual - 1) {
  2221. /* Special case: space at end of line */
  2222. _set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2223. printf("·");
  2224. _set_colors(COLOR_FG, COLOR_BG);
  2225. } else {
  2226. /* Normal characters get output */
  2227. char tmp[7]; /* Max six bytes, use 7 to ensure last is always nil */
  2228. to_eight(c.codepoint, tmp);
  2229. printf("%s", tmp);
  2230. }
  2231. /* Advance the terminal cell offset by the render width of this character */
  2232. j += c.display_width;
  2233. /* Advance to the next character */
  2234. i++;
  2235. } else if (c.display_width > 1) {
  2236. /*
  2237. * If this is a wide character but we aren't ready to render yet,
  2238. * we may need to draw some filler text for the remainder of its
  2239. * width to ensure we don't jump around when horizontally scrolling
  2240. * past wide characters.
  2241. */
  2242. remainder = c.display_width - 1;
  2243. j++;
  2244. } else {
  2245. /* Regular character, not ready to draw, advance without doing anything */
  2246. j++;
  2247. i++;
  2248. }
  2249. }
  2250. if (env->mode != MODE_LINE_SELECTION) {
  2251. if (line->is_current) {
  2252. set_colors(COLOR_FG, COLOR_ALT_BG);
  2253. } else {
  2254. set_colors(COLOR_FG, COLOR_BG);
  2255. }
  2256. }
  2257. if (!global_config.can_bce) {
  2258. /* Paint the rest of the line */
  2259. for (; j < width; ++j) {
  2260. printf(" ");
  2261. }
  2262. }
  2263. /* Clear the rest of the line */
  2264. clear_to_end();
  2265. }
  2266. /**
  2267. * Get the width of the line number region
  2268. */
  2269. int num_width(void) {
  2270. int w = log_base_10(env->line_count) + 1;
  2271. if (w < 2) return 2;
  2272. return w;
  2273. }
  2274. /**
  2275. * Draw the gutter and line numbers.
  2276. */
  2277. void draw_line_number(int x) {
  2278. /* Draw the line number */
  2279. if (env->lines[x]->is_current) {
  2280. set_colors(COLOR_NUMBER_BG, COLOR_NUMBER_FG);
  2281. } else {
  2282. set_colors(COLOR_NUMBER_FG, COLOR_NUMBER_BG);
  2283. }
  2284. int num_size = num_width();
  2285. for (int y = 0; y < num_size - log_base_10(x + 1); ++y) {
  2286. printf(" ");
  2287. }
  2288. printf("%d%c", x + 1, (x+1 == env->line_no && env->coffset > 0) ? '<' : ' ');
  2289. }
  2290. /**
  2291. * Used to highlight the current line after moving the cursor.
  2292. */
  2293. void recalculate_current_line(void) {
  2294. if (!global_config.hilight_current_line) return;
  2295. for (int i = 0; i < env->line_count; ++i) {
  2296. if (env->lines[i]->is_current && i != env->line_no-1) {
  2297. env->lines[i]->is_current = 0;
  2298. if ((i) - env->offset > -1 &&
  2299. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  2300. redraw_line((i) - env->offset, i);
  2301. }
  2302. } else if (i == env->line_no-1 && !env->lines[i]->is_current) {
  2303. env->lines[i]->is_current = 1;
  2304. if ((i) - env->offset > -1 &&
  2305. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  2306. redraw_line((i) - env->offset, i);
  2307. }
  2308. }
  2309. }
  2310. }
  2311. /**
  2312. * Redraw line.
  2313. *
  2314. * This draws the line number as well as the actual text.
  2315. * j = screen-relative line offset.
  2316. */
  2317. void redraw_line(int j, int x) {
  2318. if (env->loading) return;
  2319. /* Hide cursor when drawing */
  2320. hide_cursor();
  2321. /* Move cursor to upper left most cell of this line */
  2322. place_cursor(1,2 + j);
  2323. /* Draw a gutter on the left.
  2324. * TODO: The gutter can be used to show single-character
  2325. * line annotations, such as collapse state, or
  2326. * whether a search result was found on this line.
  2327. */
  2328. set_colors(COLOR_NUMBER_FG, COLOR_ALT_FG);
  2329. printf(" ");
  2330. draw_line_number(x);
  2331. /*
  2332. * Draw the line text
  2333. * If this is the active line, the current character cell offset should be used.
  2334. * (Non-active lines are not shifted and always render from the start of the line)
  2335. */
  2336. render_line(env->lines[x], global_config.term_width - 3 - num_width(), (x + 1 == env->line_no) ? env->coffset : 0);
  2337. }
  2338. /**
  2339. * Draw a ~ line where there is no buffer text.
  2340. */
  2341. void draw_excess_line(int j) {
  2342. place_cursor(1,2 + j);
  2343. paint_line(COLOR_ALT_BG);
  2344. set_colors(COLOR_ALT_FG, COLOR_ALT_BG);
  2345. printf("~");
  2346. clear_to_end();
  2347. }
  2348. /**
  2349. * Redraw the entire text area
  2350. */
  2351. void redraw_text(void) {
  2352. /* Hide cursor while rendering */
  2353. hide_cursor();
  2354. /* Figure out the available size of the text region */
  2355. int l = global_config.term_height - global_config.bottom_size - 1;
  2356. int j = 0;
  2357. /* Draw each line */
  2358. for (int x = env->offset; j < l && x < env->line_count; x++) {
  2359. redraw_line(j,x);
  2360. j++;
  2361. }
  2362. /* Draw the rest of the text region as ~ lines */
  2363. for (; j < l; ++j) {
  2364. draw_excess_line(j);
  2365. }
  2366. }
  2367. /**
  2368. * Draw the status bar
  2369. *
  2370. * The status bar shows the name of the file, whether it has modifications,
  2371. * and (in the future) what syntax highlighting mode is enabled.
  2372. *
  2373. * The right side of the tatus bar shows the line number and column.
  2374. */
  2375. void redraw_statusbar(void) {
  2376. /* Hide cursor while rendering */
  2377. hide_cursor();
  2378. /* Move cursor to the status bar line (second from bottom */
  2379. place_cursor(1, global_config.term_height - 1);
  2380. /* Set background colors for status line */
  2381. paint_line(COLOR_STATUS_BG);
  2382. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2383. /* Print the file name */
  2384. if (env->file_name) {
  2385. printf("%s", env->file_name);
  2386. } else {
  2387. printf("[No Name]");
  2388. }
  2389. printf(" ");
  2390. if (env->syntax) {
  2391. printf("[%s]", env->syntax->name);
  2392. }
  2393. /* Print file status indicators */
  2394. if (env->modified) {
  2395. printf("[+]");
  2396. }
  2397. if (env->readonly) {
  2398. printf("[ro]");
  2399. }
  2400. printf(" ");
  2401. if (env->tabs) {
  2402. printf("[tabs]");
  2403. } else {
  2404. printf("[spaces=%d]", env->tabstop);
  2405. }
  2406. if (global_config.yanks) {
  2407. printf("[y:%ld]", global_config.yank_count);
  2408. }
  2409. if (env->indent) {
  2410. printf("[indent]");
  2411. }
  2412. /* Clear the rest of the status bar */
  2413. clear_to_end();
  2414. /* Pre-render the right hand side of the status bar */
  2415. char right_hand[1024];
  2416. snprintf(right_hand, 1024, "Line %d/%d Col: %d ", env->line_no, env->line_count, env->col_no);
  2417. /* Move the cursor appropriately to draw it */
  2418. place_cursor(global_config.term_width - strlen(right_hand), global_config.term_height - 1);
  2419. /* TODO: What if we're localized and this has wide chars? */
  2420. printf("%s",right_hand);
  2421. fflush(stdout);
  2422. }
  2423. /**
  2424. * Draw the command line
  2425. *
  2426. * The command line either has input from the user (:quit, :!make, etc.)
  2427. * or shows the INSERT (or VISUAL in the future) mode name.
  2428. */
  2429. void redraw_commandline(void) {
  2430. /* Hide cursor while rendering */
  2431. hide_cursor();
  2432. /* Move cursor to the last line */
  2433. place_cursor(1, global_config.term_height);
  2434. /* Set background color */
  2435. paint_line(COLOR_BG);
  2436. set_colors(COLOR_FG, COLOR_BG);
  2437. /* If we are in an edit mode, note that. */
  2438. if (env->mode == MODE_INSERT) {
  2439. set_bold();
  2440. printf("-- INSERT --");
  2441. clear_to_end();
  2442. reset();
  2443. } else if (env->mode == MODE_LINE_SELECTION) {
  2444. set_bold();
  2445. printf("-- LINE SELECTION --");
  2446. clear_to_end();
  2447. reset();
  2448. } else if (env->mode == MODE_REPLACE) {
  2449. set_bold();
  2450. printf("-- REPLACE --");
  2451. clear_to_end();
  2452. reset();
  2453. } else if (env->mode == MODE_CHAR_SELECTION) {
  2454. set_bold();
  2455. printf("-- CHAR SELECTION --");
  2456. clear_to_end();
  2457. reset();
  2458. } else {
  2459. clear_to_end();
  2460. }
  2461. }
  2462. /**
  2463. * Draw a message on the command line.
  2464. */
  2465. void render_commandline_message(char * message, ...) {
  2466. /* varargs setup */
  2467. va_list args;
  2468. va_start(args, message);
  2469. char buf[1024];
  2470. /* Process format string */
  2471. vsnprintf(buf, 1024, message, args);
  2472. va_end(args);
  2473. /* Hide cursor while rendering */
  2474. hide_cursor();
  2475. /* Move cursor to the last line */
  2476. place_cursor(1, global_config.term_height);
  2477. /* Set background color */
  2478. paint_line(COLOR_BG);
  2479. set_colors(COLOR_FG, COLOR_BG);
  2480. printf("%s", buf);
  2481. /* Clear the rest of the status bar */
  2482. clear_to_end();
  2483. }
  2484. /**
  2485. * Draw all screen elements
  2486. */
  2487. void redraw_all(void) {
  2488. redraw_tabbar();
  2489. redraw_text();
  2490. redraw_statusbar();
  2491. redraw_commandline();
  2492. }
  2493. /**
  2494. * Update the terminal title bar
  2495. */
  2496. void update_title(void) {
  2497. if (!global_config.can_title) return;
  2498. char cwd[1024] = {'/',0};
  2499. getcwd(cwd, 1024);
  2500. for (int i = 1; i < 3; ++i) {
  2501. printf("\033]%d;%s%s (%s) - BIM\007", i, env->file_name ? env->file_name : "[No Name]", env->modified ? " +" : "", cwd);
  2502. }
  2503. }
  2504. /**
  2505. * Mark this buffer as modified and
  2506. * redraw the status and tabbar if needed.
  2507. */
  2508. void set_modified(void) {
  2509. /* If it was already marked modified, no need to do anything */
  2510. if (env->modified) return;
  2511. /* Mark as modified */
  2512. env->modified = 1;
  2513. /* Redraw some things */
  2514. update_title();
  2515. redraw_tabbar();
  2516. redraw_statusbar();
  2517. }
  2518. /**
  2519. * Draw a message on the status line
  2520. */
  2521. void render_status_message(char * message, ...) {
  2522. /* varargs setup */
  2523. va_list args;
  2524. va_start(args, message);
  2525. char buf[1024];
  2526. /* Process format string */
  2527. vsnprintf(buf, 1024, message, args);
  2528. va_end(args);
  2529. /* Hide cursor while rendering */
  2530. hide_cursor();
  2531. /* Move cursor to the status bar line (second from bottom */
  2532. place_cursor(1, global_config.term_height - 1);
  2533. /* Set background colors for status line */
  2534. paint_line(COLOR_STATUS_BG);
  2535. set_colors(COLOR_STATUS_FG, COLOR_STATUS_BG);
  2536. printf("%s", buf);
  2537. /* Clear the rest of the status bar */
  2538. clear_to_end();
  2539. }
  2540. /**
  2541. * Draw an errormessage to the command line.
  2542. */
  2543. void render_error(char * message, ...) {
  2544. /* varargs setup */
  2545. va_list args;
  2546. va_start(args, message);
  2547. char buf[1024];
  2548. /* Process format string */
  2549. vsnprintf(buf, 1024, message, args);
  2550. va_end(args);
  2551. /* Hide cursor while rendering */
  2552. hide_cursor();
  2553. /* Move cursor to the command line */
  2554. place_cursor(1, global_config.term_height);
  2555. /* Set appropriate error message colors */
  2556. set_colors(COLOR_ERROR_FG, COLOR_ERROR_BG);
  2557. /* Draw the message */
  2558. printf("%s", buf);
  2559. fflush(stdout);
  2560. }
  2561. char * paren_pairs = "()[]{}<>";
  2562. void find_matching_paren(int * out_line, int * out_col);
  2563. int is_paren(int c) {
  2564. char * p = paren_pairs;
  2565. while (*p) {
  2566. if (c == *p) return 1;
  2567. p++;
  2568. }
  2569. return 0;
  2570. }
  2571. /**
  2572. * If the config option is enabled, find the matching
  2573. * paren character and highlight it with the SELECT
  2574. * colors, clearing out other SELECT values. As we
  2575. * co-opt the SELECT flag, don't do this in selection
  2576. * modes - only in normal and insert modes.
  2577. */
  2578. void highlight_matching_paren(void) {
  2579. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) return;
  2580. if (!global_config.highlight_parens) return;
  2581. int line = -1, col = -1;
  2582. if (env->line_no <= env->line_count && env->col_no <= env->lines[env->line_no-1]->actual &&
  2583. is_paren(env->lines[env->line_no-1]->text[env->col_no-1].codepoint)) {
  2584. find_matching_paren(&line, &col);
  2585. if (line != -1) env->highlighting_paren = 1;
  2586. }
  2587. if (!env->highlighting_paren) return;
  2588. for (int i = 0; i < env->line_count; ++i) {
  2589. int redraw = 0;
  2590. for (int j = 0; j < env->lines[i]->actual; ++j) {
  2591. if (i == line-1 && j == col-1) {
  2592. env->lines[line-1]->text[col-1].flags |= FLAG_SELECT;
  2593. redraw = 1;
  2594. continue;
  2595. }
  2596. if (env->lines[i]->text[j].flags & FLAG_SELECT) {
  2597. redraw = 1;
  2598. }
  2599. env->lines[i]->text[j].flags &= (~FLAG_SELECT);
  2600. }
  2601. if (redraw) {
  2602. if ((i) - env->offset > -1 &&
  2603. (i) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 2) {
  2604. redraw_line((i) - env->offset, i);
  2605. }
  2606. }
  2607. }
  2608. if (line == -1) env->highlighting_paren = 0;
  2609. }
  2610. /**
  2611. * Move the cursor to the appropriate location based
  2612. * on where it is in the text region.
  2613. *
  2614. * This does some additional math to set the text
  2615. * region horizontal offset.
  2616. */
  2617. void place_cursor_actual(void) {
  2618. /* Invalid positions */
  2619. if (env->line_no < 1) env->line_no = 1;
  2620. if (env->col_no < 1) env->col_no = 1;
  2621. /* Account for the left hand gutter */
  2622. int num_size = num_width() + 3;
  2623. int x = num_size + 1 - env->coffset;
  2624. /* Determine where the cursor is physically */
  2625. for (int i = 0; i < env->col_no - 1; ++i) {
  2626. char_t * c = &env->lines[env->line_no-1]->text[i];
  2627. x += c->display_width;
  2628. }
  2629. /* y is a bit easier to calculate */
  2630. int y = env->line_no - env->offset + 1;
  2631. int needs_redraw = 0;
  2632. while (y < 2 + global_config.cursor_padding && env->offset > 0) {
  2633. y++;
  2634. env->offset--;
  2635. needs_redraw = 1;
  2636. }
  2637. while (y > global_config.term_height - global_config.bottom_size - global_config.cursor_padding) {
  2638. y--;
  2639. env->offset++;
  2640. needs_redraw = 1;
  2641. }
  2642. if (needs_redraw) {
  2643. redraw_text();
  2644. redraw_tabbar();
  2645. redraw_statusbar();
  2646. redraw_commandline();
  2647. }
  2648. /* If the cursor has gone off screen to the right... */
  2649. if (x > global_config.term_width - 1) {
  2650. /* Adjust the offset appropriately to scroll horizontally */
  2651. int diff = x - (global_config.term_width - 1);
  2652. env->coffset += diff;
  2653. x -= diff;
  2654. redraw_text();
  2655. }
  2656. /* Same for scrolling horizontally to the left */
  2657. if (x < num_size + 1) {
  2658. int diff = (num_size + 1) - x;
  2659. env->coffset -= diff;
  2660. x += diff;
  2661. redraw_text();
  2662. }
  2663. highlight_matching_paren();
  2664. recalculate_current_line();
  2665. /* Move the actual terminal cursor */
  2666. place_cursor(x,y);
  2667. /* Show the cursor */
  2668. show_cursor();
  2669. }
  2670. /**
  2671. * Update screen size
  2672. */
  2673. void update_screen_size(void) {
  2674. struct winsize w;
  2675. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  2676. global_config.term_width = w.ws_col;
  2677. global_config.term_height = w.ws_row;
  2678. }
  2679. /**
  2680. * Handle terminal size changes
  2681. */
  2682. void SIGWINCH_handler(int sig) {
  2683. (void)sig;
  2684. update_screen_size();
  2685. redraw_all();
  2686. signal(SIGWINCH, SIGWINCH_handler);
  2687. }
  2688. /**
  2689. * Handle suspend
  2690. */
  2691. void SIGTSTP_handler(int sig) {
  2692. (void)sig;
  2693. mouse_disable();
  2694. set_buffered();
  2695. reset();
  2696. clear_screen();
  2697. show_cursor();
  2698. unset_alternate_screen();
  2699. fflush(stdout);
  2700. signal(SIGTSTP, SIG_DFL);
  2701. raise(SIGTSTP);
  2702. }
  2703. void SIGCONT_handler(int sig) {
  2704. (void)sig;
  2705. set_alternate_screen();
  2706. set_unbuffered();
  2707. mouse_enable();
  2708. redraw_all();
  2709. signal(SIGCONT, SIGCONT_handler);
  2710. signal(SIGTSTP, SIGTSTP_handler);
  2711. }
  2712. /**
  2713. * Move the cursor to a specific line.
  2714. */
  2715. void goto_line(int line) {
  2716. /* Respect file bounds */
  2717. if (line < 1) line = 1;
  2718. if (line > env->line_count) line = env->line_count;
  2719. /* Move the cursor / text region offsets */
  2720. env->coffset = 0;
  2721. env->offset = line - 1;
  2722. env->line_no = line;
  2723. env->col_no = 1;
  2724. redraw_all();
  2725. }
  2726. /**
  2727. * UTF-8 parser state
  2728. */
  2729. static uint32_t codepoint_r;
  2730. static uint32_t state = 0;
  2731. #define UTF8_ACCEPT 0
  2732. #define UTF8_REJECT 1
  2733. static inline uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
  2734. static int state_table[32] = {
  2735. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* 0xxxxxxx */
  2736. 1,1,1,1,1,1,1,1, /* 10xxxxxx */
  2737. 2,2,2,2, /* 110xxxxx */
  2738. 3,3, /* 1110xxxx */
  2739. 4, /* 11110xxx */
  2740. 1 /* 11111xxx */
  2741. };
  2742. static int mask_bytes[32] = {
  2743. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  2744. 0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,0x7F,
  2745. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  2746. 0x1F,0x1F,0x1F,0x1F,
  2747. 0x0F,0x0F,
  2748. 0x07,
  2749. 0x00
  2750. };
  2751. static int next[5] = {
  2752. 0,
  2753. 1,
  2754. 0,
  2755. 2,
  2756. 3
  2757. };
  2758. if (*state == UTF8_ACCEPT) {
  2759. *codep = byte & mask_bytes[byte >> 3];
  2760. *state = state_table[byte >> 3];
  2761. } else if (*state > 0) {
  2762. *codep = (byte & 0x3F) | (*codep << 6);
  2763. *state = next[*state];
  2764. }
  2765. return *state;
  2766. }
  2767. /**
  2768. * Processs (part of) a file and add it to a buffer.
  2769. */
  2770. void add_buffer(uint8_t * buf, int size) {
  2771. for (int i = 0; i < size; ++i) {
  2772. if (!decode(&state, &codepoint_r, buf[i])) {
  2773. uint32_t c = codepoint_r;
  2774. if (c == '\n') {
  2775. env->lines = add_line(env->lines, env->line_no);
  2776. env->col_no = 1;
  2777. env->line_no += 1;
  2778. } else {
  2779. char_t _c;
  2780. _c.codepoint = (uint32_t)c;
  2781. _c.flags = 0;
  2782. _c.display_width = codepoint_width((wchar_t)c);
  2783. line_t * line = env->lines[env->line_no - 1];
  2784. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no-1);
  2785. if (line != nline) {
  2786. env->lines[env->line_no - 1] = nline;
  2787. }
  2788. env->col_no += 1;
  2789. }
  2790. } else if (state == UTF8_REJECT) {
  2791. state = 0;
  2792. }
  2793. }
  2794. }
  2795. struct syntax_definition * match_syntax(char * file) {
  2796. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  2797. for (char ** ext = s->ext; *ext; ++ext) {
  2798. int i = strlen(file);
  2799. int j = strlen(*ext);
  2800. do {
  2801. if (file[i] != (*ext)[j]) break;
  2802. if (j == 0) return s;
  2803. if (i == 0) break;
  2804. i--;
  2805. j--;
  2806. } while (1);
  2807. }
  2808. }
  2809. return NULL;
  2810. }
  2811. /**
  2812. * Check if a string is all numbers.
  2813. */
  2814. int is_all_numbers(const char * c) {
  2815. while (*c) {
  2816. if (!isdigit(*c)) return 0;
  2817. c++;
  2818. }
  2819. return 1;
  2820. }
  2821. /**
  2822. * Create a new buffer from a file.
  2823. */
  2824. void open_file(char * file) {
  2825. env = buffer_new();
  2826. env->loading = 1;
  2827. setup_buffer(env);
  2828. FILE * f;
  2829. int init_line = 1;
  2830. if (!strcmp(file,"-")) {
  2831. /**
  2832. * Read file from stdin. stderr provides terminal input.
  2833. */
  2834. f = stdin;
  2835. global_config.tty_in = STDERR_FILENO;
  2836. env->modified = 1;
  2837. } else {
  2838. char * l = strrchr(file, ':');
  2839. if (l && is_all_numbers(l+1)) {
  2840. *l = '\0';
  2841. l++;
  2842. init_line = atoi(l);
  2843. }
  2844. struct stat statbuf;
  2845. if (!stat(file, &statbuf) && S_ISDIR(statbuf.st_mode)) {
  2846. DIR * dirp = opendir(file);
  2847. if (!dirp) {
  2848. env->loading = 0;
  2849. return;
  2850. }
  2851. struct dirent * ent = readdir(dirp);
  2852. while (ent) {
  2853. add_buffer((unsigned char*)ent->d_name, strlen(ent->d_name));
  2854. add_buffer((unsigned char*)"\n",1);
  2855. ent = readdir(dirp);
  2856. }
  2857. closedir(dirp);
  2858. env->file_name = strdup(file);
  2859. env->readonly = 1;
  2860. env->loading = 0;
  2861. return;
  2862. }
  2863. f = fopen(file, "r");
  2864. env->file_name = strdup(file);
  2865. }
  2866. if (!f) {
  2867. if (global_config.hilight_on_open) {
  2868. env->syntax = match_syntax(file);
  2869. }
  2870. env->loading = 0;
  2871. return;
  2872. }
  2873. uint8_t buf[BLOCK_SIZE];
  2874. state = 0;
  2875. while (!feof(f) && !ferror(f)) {
  2876. size_t r = fread(buf, 1, BLOCK_SIZE, f);
  2877. add_buffer(buf, r);
  2878. }
  2879. if (ferror(f)) {
  2880. env->loading = 0;
  2881. return;
  2882. }
  2883. if (env->line_no && env->lines[env->line_no-1] && env->lines[env->line_no-1]->actual == 0) {
  2884. /* Remove blank line from end */
  2885. remove_line(env->lines, env->line_no-1);
  2886. }
  2887. if (global_config.hilight_on_open) {
  2888. env->syntax = match_syntax(file);
  2889. for (int i = 0; i < env->line_count; ++i) {
  2890. recalculate_syntax(env->lines[i],i);
  2891. }
  2892. }
  2893. /* Try to automatically figure out tabs vs. spaces */
  2894. int tabs = 0, spaces = 0;
  2895. for (int i = 0; i < env->line_count; ++i) {
  2896. if (env->lines[i]->actual > 1) { /* Make sure line has at least some text on it */
  2897. if (env->lines[i]->text[0].codepoint == '\t') tabs++;
  2898. if (env->lines[i]->text[0].codepoint == ' ' &&
  2899. env->lines[i]->text[1].codepoint == ' ') /* Ignore spaces at the start of asterisky C comments */
  2900. spaces++;
  2901. }
  2902. }
  2903. if (spaces > tabs) {
  2904. env->tabs = 0;
  2905. }
  2906. /* TODO figure out tabstop for spaces? */
  2907. env->loading = 0;
  2908. for (int i = 0; i < env->line_count; ++i) {
  2909. recalculate_tabs(env->lines[i]);
  2910. }
  2911. if (global_config.go_to_line) {
  2912. goto_line(init_line);
  2913. }
  2914. fclose(f);
  2915. }
  2916. /**
  2917. * Clean up the terminal and exit the editor.
  2918. */
  2919. void quit(void) {
  2920. mouse_disable();
  2921. set_buffered();
  2922. reset();
  2923. clear_screen();
  2924. show_cursor();
  2925. unset_alternate_screen();
  2926. exit(0);
  2927. }
  2928. /**
  2929. * Try to quit, but don't continue if there are
  2930. * modified buffers open.
  2931. */
  2932. void try_quit(void) {
  2933. for (int i = 0; i < buffers_len; i++ ) {
  2934. buffer_t * _env = buffers[i];
  2935. if (_env->modified) {
  2936. if (_env->file_name) {
  2937. render_error("Modifications made to file `%s` in tab %d. Aborting.", _env->file_name, i+1);
  2938. } else {
  2939. render_error("Unsaved new file in tab %d. Aborting.", i+1);
  2940. }
  2941. return;
  2942. }
  2943. }
  2944. quit();
  2945. }
  2946. /**
  2947. * Switch to the previous buffer
  2948. */
  2949. void previous_tab(void) {
  2950. buffer_t * last = NULL;
  2951. for (int i = 0; i < buffers_len; i++) {
  2952. buffer_t * _env = buffers[i];
  2953. if (_env == env) {
  2954. if (last) {
  2955. /* Wrap around */
  2956. env = last;
  2957. redraw_all();
  2958. return;
  2959. } else {
  2960. env = buffers[buffers_len-1];
  2961. redraw_all();
  2962. return;
  2963. }
  2964. }
  2965. last = _env;
  2966. }
  2967. }
  2968. /**
  2969. * Switch to the next buffer
  2970. */
  2971. void next_tab(void) {
  2972. for (int i = 0; i < buffers_len; i++) {
  2973. buffer_t * _env = buffers[i];
  2974. if (_env == env) {
  2975. if (i != buffers_len - 1) {
  2976. env = buffers[i+1];
  2977. redraw_all();
  2978. return;
  2979. } else {
  2980. /* Wrap around */
  2981. env = buffers[0];
  2982. redraw_all();
  2983. return;
  2984. }
  2985. }
  2986. }
  2987. }
  2988. /**
  2989. * Write active buffer to file
  2990. */
  2991. void write_file(char * file) {
  2992. if (!file) {
  2993. render_error("Need a file to write to.");
  2994. return;
  2995. }
  2996. FILE * f = fopen(file, "w+");
  2997. if (!f) {
  2998. render_error("Failed to open file for writing.");
  2999. return;
  3000. }
  3001. /* Go through each line and convert it back to UTF-8 */
  3002. int i, j;
  3003. for (i = 0; i < env->line_count; ++i) {
  3004. line_t * line = env->lines[i];
  3005. for (j = 0; j < line->actual; j++) {
  3006. char_t c = line->text[j];
  3007. if (c.codepoint == 0) {
  3008. char buf[1] = {0};
  3009. fwrite(buf, 1, 1, f);
  3010. } else {
  3011. char tmp[8] = {0};
  3012. int i = to_eight(c.codepoint, tmp);
  3013. fwrite(tmp, i, 1, f);
  3014. }
  3015. }
  3016. fputc('\n', f);
  3017. }
  3018. fclose(f);
  3019. /* Mark it no longer modified */
  3020. env->modified = 0;
  3021. env->last_save_history = env->history;
  3022. /* If there was no file name set, set one */
  3023. if (!env->file_name) {
  3024. env->file_name = malloc(strlen(file) + 1);
  3025. memcpy(env->file_name, file, strlen(file) + 1);
  3026. }
  3027. update_title();
  3028. redraw_all();
  3029. }
  3030. /**
  3031. * Close the active buffer
  3032. */
  3033. void close_buffer(void) {
  3034. buffer_t * previous_env = env;
  3035. buffer_t * new_env = buffer_close(env);
  3036. if (new_env == previous_env) {
  3037. /* ?? Failed to close buffer */
  3038. render_error("lolwat");
  3039. }
  3040. /* No more buffers, exit */
  3041. if (!new_env) {
  3042. quit();
  3043. }
  3044. /* Clean up the old buffer */
  3045. free(previous_env);
  3046. /* Set the new active buffer */
  3047. env = new_env;
  3048. /* Redraw the screen */
  3049. redraw_all();
  3050. }
  3051. void set_preferred_column(void) {
  3052. int c = 0;
  3053. for (int i = 0; i < env->lines[env->line_no-1]->actual && i < env->col_no-1; ++i) {
  3054. c += env->lines[env->line_no-1]->text[i].display_width;
  3055. }
  3056. env->preferred_column = c;
  3057. }
  3058. /**
  3059. * Move the cursor down one line in the text region
  3060. */
  3061. void cursor_down(void) {
  3062. /* If this isn't already the last line... */
  3063. if (env->line_no < env->line_count) {
  3064. /* Move the cursor down */
  3065. env->line_no += 1;
  3066. /* Try to place the cursor horizontally at the preferred column */
  3067. int _x = 0;
  3068. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3069. char_t * c = &env->lines[env->line_no-1]->text[i];
  3070. _x += c->display_width;
  3071. env->col_no = i+1;
  3072. if (_x > env->preferred_column) {
  3073. break;
  3074. }
  3075. }
  3076. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3077. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3078. }
  3079. /*
  3080. * If the horizontal cursor position exceeds the width the new line,
  3081. * then move the cursor left to the extent of the new line.
  3082. *
  3083. * If we're in insert mode, we can go one cell beyond the end of the line
  3084. */
  3085. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3086. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3087. if (env->col_no == 0) env->col_no = 1;
  3088. }
  3089. /*
  3090. * If the screen was scrolled horizontally, unscroll it;
  3091. * if it will be scrolled on this line as well, that will
  3092. * be handled by place_cursor_actual
  3093. */
  3094. int redraw = 0;
  3095. if (env->coffset != 0) {
  3096. env->coffset = 0;
  3097. redraw = 1;
  3098. }
  3099. /* If we've scrolled past the bottom of the screen, scroll the screen */
  3100. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1 - global_config.cursor_padding) {
  3101. env->offset += 1;
  3102. /* Tell terminal to scroll */
  3103. if (global_config.can_scroll) {
  3104. shift_up();
  3105. /* A new line appears on screen at the bottom, draw it */
  3106. int l = global_config.term_height - global_config.bottom_size - 1;
  3107. if (env->offset + l < env->line_count + 1) {
  3108. redraw_line(l-1, env->offset + l-1);
  3109. } else {
  3110. draw_excess_line(l - 1);
  3111. }
  3112. /* Redraw elements that were moved by scrolling */
  3113. redraw_tabbar();
  3114. redraw_statusbar();
  3115. redraw_commandline();
  3116. place_cursor_actual();
  3117. } else {
  3118. redraw_all();
  3119. }
  3120. return;
  3121. } else if (redraw) {
  3122. /* Otherwise, if we need to redraw because of coffset change, do that */
  3123. redraw_text();
  3124. }
  3125. /* Update the status bar */
  3126. redraw_statusbar();
  3127. /* Place the terminal cursor again */
  3128. place_cursor_actual();
  3129. }
  3130. }
  3131. /**
  3132. * Move the cursor up one line in the text region
  3133. */
  3134. void cursor_up(void) {
  3135. /* If this isn't the first line already */
  3136. if (env->line_no > 1) {
  3137. /* Move the cursor down */
  3138. env->line_no -= 1;
  3139. /* Try to place the cursor horizontally at the preferred column */
  3140. int _x = 0;
  3141. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  3142. char_t * c = &env->lines[env->line_no-1]->text[i];
  3143. _x += c->display_width;
  3144. env->col_no = i+1;
  3145. if (_x > env->preferred_column) {
  3146. break;
  3147. }
  3148. }
  3149. if (env->mode == MODE_INSERT && _x <= env->preferred_column) {
  3150. env->col_no = env->lines[env->line_no-1]->actual + 1;
  3151. }
  3152. /*
  3153. * If the horizontal cursor position exceeds the width the new line,
  3154. * then move the cursor left to the extent of the new line.
  3155. *
  3156. * If we're in insert mode, we can go one cell beyond the end of the line
  3157. */
  3158. if (env->col_no > env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT)) {
  3159. env->col_no = env->lines[env->line_no-1]->actual + (env->mode == MODE_INSERT);
  3160. if (env->col_no == 0) env->col_no = 1;
  3161. }
  3162. /*
  3163. * If the screen was scrolled horizontally, unscroll it;
  3164. * if it will be scrolled on this line as well, that will
  3165. * be handled by place_cursor_actual
  3166. */
  3167. int redraw = 0;
  3168. if (env->coffset != 0) {
  3169. env->coffset = 0;
  3170. redraw = 1;
  3171. }
  3172. int e = (env->offset == 0) ? env->offset : env->offset + global_config.cursor_padding;
  3173. if (env->line_no <= e) {
  3174. env->offset -= 1;
  3175. /* Tell terminal to scroll */
  3176. if (global_config.can_scroll) {
  3177. shift_down();
  3178. /*
  3179. * The line at the top of the screen should always be real
  3180. * so we can just call redraw_line here
  3181. */
  3182. redraw_line(0,env->offset);
  3183. /* Redraw elements that were moved by scrolling */
  3184. redraw_tabbar();
  3185. redraw_statusbar();
  3186. redraw_commandline();
  3187. place_cursor_actual();
  3188. } else {
  3189. redraw_all();
  3190. }
  3191. return;
  3192. } else if (redraw) {
  3193. /* Otherwise, if we need to redraw because of coffset change, do that */
  3194. redraw_text();
  3195. }
  3196. /* Update the status bar */
  3197. redraw_statusbar();
  3198. /* Place the terminal cursor again */
  3199. place_cursor_actual();
  3200. }
  3201. }
  3202. /**
  3203. * Move the cursor one column left.
  3204. */
  3205. void cursor_left(void) {
  3206. if (env->col_no > 1) {
  3207. env->col_no -= 1;
  3208. /* Update the status bar */
  3209. redraw_statusbar();
  3210. /* Place the terminal cursor again */
  3211. place_cursor_actual();
  3212. }
  3213. set_preferred_column();
  3214. }
  3215. /**
  3216. * Move the cursor one column right.
  3217. */
  3218. void cursor_right(void) {
  3219. /* If this isn't already the rightmost column we can reach on this line in this mode... */
  3220. if (env->col_no < env->lines[env->line_no-1]->actual + !!(env->mode == MODE_INSERT)) {
  3221. env->col_no += 1;
  3222. /* Update the status bar */
  3223. redraw_statusbar();
  3224. /* Place the terminal cursor again */
  3225. place_cursor_actual();
  3226. }
  3227. set_preferred_column();
  3228. }
  3229. /**
  3230. * Move the cursor to the fron the of the line
  3231. */
  3232. void cursor_home(void) {
  3233. env->col_no = 1;
  3234. set_preferred_column();
  3235. /* Update the status bar */
  3236. redraw_statusbar();
  3237. /* Place the terminal cursor again */
  3238. place_cursor_actual();
  3239. }
  3240. /**
  3241. * Move the cursor to the end of the line.
  3242. *
  3243. * In INSERT mode, moves one cell right of the end of the line.
  3244. * In NORMAL mode, moves the cursor to the last occupied cell.
  3245. */
  3246. void cursor_end(void) {
  3247. env->col_no = env->lines[env->line_no-1]->actual+!!(env->mode == MODE_INSERT);
  3248. set_preferred_column();
  3249. /* Update the status bar */
  3250. redraw_statusbar();
  3251. /* Place the terminal cursor again */
  3252. place_cursor_actual();
  3253. }
  3254. /**
  3255. * Leave INSERT mode
  3256. *
  3257. * If the cursor is too far right, adjust it.
  3258. * Redraw the command line.
  3259. */
  3260. void leave_insert(void) {
  3261. if (env->col_no > env->lines[env->line_no-1]->actual) {
  3262. env->col_no = env->lines[env->line_no-1]->actual;
  3263. if (env->col_no == 0) env->col_no = 1;
  3264. set_preferred_column();
  3265. }
  3266. set_history_break();
  3267. env->mode = MODE_NORMAL;
  3268. redraw_commandline();
  3269. }
  3270. /**
  3271. * Process a user command.
  3272. */
  3273. void process_command(char * cmd) {
  3274. /* Special case ! to run shell commands without parsing tokens */
  3275. int c;
  3276. if (*cmd == '!') {
  3277. /* Reset and draw some line feeds */
  3278. reset();
  3279. printf("\n\n");
  3280. /* Set buffered for shell application */
  3281. set_buffered();
  3282. /* Call the shell and wait for completion */
  3283. system(&cmd[1]);
  3284. /* Return to the editor, wait for user to press enter. */
  3285. set_unbuffered();
  3286. printf("\n\nPress ENTER to continue.");
  3287. fflush(stdout);
  3288. while ((c = bim_getch(), c != ENTER_KEY && c != LINE_FEED));
  3289. /* Redraw the screen */
  3290. redraw_all();
  3291. /* Done processing command */
  3292. return;
  3293. }
  3294. /* Tokenize argument string on spaces */
  3295. char *p, *argv[512], *last;
  3296. int argc = 0;
  3297. for ((p = strtok_r(cmd, " ", &last)); p;
  3298. (p = strtok_r(NULL, " ", &last)), argc++) {
  3299. if (argc < 511) argv[argc] = p;
  3300. }
  3301. argv[argc] = NULL;
  3302. if (argc < 1) {
  3303. /* no op */
  3304. return;
  3305. }
  3306. if (!strcmp(argv[0], "e")) {
  3307. /* e: edit file */
  3308. if (argc > 1) {
  3309. /* This actually opens a new tab */
  3310. open_file(argv[1]);
  3311. update_title();
  3312. } else {
  3313. /* TODO: Reopen file? */
  3314. render_error("Expected a file to open...");
  3315. }
  3316. } else if (!strcmp(argv[0], "tabnew")) {
  3317. if (argc > 1) {
  3318. open_file(argv[1]);
  3319. update_title();
  3320. } else {
  3321. env = buffer_new();
  3322. setup_buffer(env);
  3323. redraw_all();
  3324. update_title();
  3325. }
  3326. } else if (!strcmp(argv[0], "w")) {
  3327. /* w: write file */
  3328. if (argc > 1) {
  3329. write_file(argv[1]);
  3330. } else {
  3331. write_file(env->file_name);
  3332. }
  3333. } else if (!strcmp(argv[0], "wq")) {
  3334. /* wq: write file and close buffer; if there's no file to write to, may do weird things */
  3335. write_file(env->file_name);
  3336. close_buffer();
  3337. } else if (!strcmp(argv[0], "q")) {
  3338. /* close buffer if unmodified */
  3339. if (env->modified) {
  3340. render_error("No write since last change. Use :q! to force exit.");
  3341. } else {
  3342. close_buffer();
  3343. }
  3344. } else if (!strcmp(argv[0], "q!")) {
  3345. /* close buffer without warning if unmodified */
  3346. close_buffer();
  3347. } else if (!strcmp(argv[0], "qa") || !strcmp(argv[0], "qall")) {
  3348. /* Close all */
  3349. try_quit();
  3350. } else if (!strcmp(argv[0], "qa!")) {
  3351. /* Forcefully exit editor */
  3352. quit();
  3353. } else if (!strcmp(argv[0], "tabp")) {
  3354. /* Next tab */
  3355. previous_tab();
  3356. update_title();
  3357. } else if (!strcmp(argv[0], "tabn")) {
  3358. /* Previous tab */
  3359. next_tab();
  3360. update_title();
  3361. } else if (!strcmp(argv[0], "indent")) {
  3362. env->indent = 1;
  3363. redraw_statusbar();
  3364. } else if (!strcmp(argv[0], "noindent")) {
  3365. env->indent = 0;
  3366. redraw_statusbar();
  3367. } else if (!strcmp(argv[0], "cursorcolumn")) {
  3368. render_status_message("cursorcolumn=%d", env->preferred_column);
  3369. } else if (!strcmp(argv[0], "noh")) {
  3370. if (env->search) {
  3371. free(env->search);
  3372. env->search = NULL;
  3373. for (int i = 0; i < env->line_count; ++i) {
  3374. recalculate_syntax(env->lines[i],i);
  3375. }
  3376. redraw_text();
  3377. }
  3378. } else if (!strcmp(argv[0], "help")) {
  3379. /*
  3380. * The repeated calls to redraw_commandline here make use
  3381. * of scrolling to draw this multiline help message on
  3382. * the same background as the command line.
  3383. */
  3384. render_commandline_message(""); /* To clear command line */
  3385. render_commandline_message("\n");
  3386. render_commandline_message(" \033[1mbim - The standard ToaruOS Text Editor\033[22m\n");
  3387. render_commandline_message("\n");
  3388. render_commandline_message(" Available commands:\n");
  3389. 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");
  3390. render_commandline_message(" Write out with \033[3m:w \033[4mfile\033[24;23m\n");
  3391. render_commandline_message(" Set syntax with \033[3m:syntax \033[4mlanguage\033[24;23m\n");
  3392. render_commandline_message(" Open a new tab with \033[3m:e \033[4mpath/to/file\033[24;23m\n");
  3393. render_commandline_message(" \033[3m:tabn\033[23m and \033[3m:tabp\033[23m can be used to switch tabs\n");
  3394. render_commandline_message(" Set the color scheme with \033[3m:theme \033[4mtheme\033[24;23m\n");
  3395. render_commandline_message(" Set the behavior of the tab key with \033[3m:tabs\033[23m or \033[3m:spaces\033[23m\n");
  3396. render_commandline_message(" Set tabstop with \033[3m:tabstop \033[4mwidth\033[24;23m\n");
  3397. render_commandline_message("\n");
  3398. render_commandline_message(" %s\n", BIM_COPYRIGHT);
  3399. render_commandline_message("\n");
  3400. /* Redrawing the tabbar makes it look like we just shifted the whole view up */
  3401. redraw_tabbar();
  3402. redraw_commandline();
  3403. fflush(stdout);
  3404. /* Wait for a character so we can redraw the screen before continuing */
  3405. int c;
  3406. while ((c = bim_getch())== -1);
  3407. /* Make sure that key press actually gets used */
  3408. bim_unget(c);
  3409. /*
  3410. * Redraw everything to hide the help message and get the
  3411. * upper few lines of text on screen again
  3412. */
  3413. redraw_all();
  3414. } else if (!strcmp(argv[0], "theme")) {
  3415. if (argc < 2) {
  3416. render_status_message("theme=%s", current_theme);
  3417. return;
  3418. }
  3419. for (struct theme_def * d = themes; d->name; ++d) {
  3420. if (!strcmp(argv[1], d->name)) {
  3421. d->load();
  3422. redraw_all();
  3423. return;
  3424. }
  3425. }
  3426. } else if (!strcmp(argv[0], "syntax")) {
  3427. if (argc < 2) {
  3428. render_status_message("syntax=%s", env->syntax ? env->syntax->name : "none");
  3429. return;
  3430. }
  3431. if (!strcmp(argv[1],"none")) {
  3432. for (int i = 0; i < env->line_count; ++i) {
  3433. env->lines[i]->istate = 0;
  3434. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3435. env->lines[i]->text[j].flags = 0;
  3436. }
  3437. }
  3438. redraw_all();
  3439. return;
  3440. }
  3441. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3442. if (!strcmp(argv[1],s->name)) {
  3443. env->syntax = s;
  3444. for (int i = 0; i < env->line_count; ++i) {
  3445. env->lines[i]->istate = 0;
  3446. }
  3447. for (int i = 0; i < env->line_count; ++i) {
  3448. recalculate_syntax(env->lines[i],i);
  3449. }
  3450. redraw_all();
  3451. return;
  3452. }
  3453. }
  3454. render_error("unrecognized syntax type");
  3455. } else if (!strcmp(argv[0], "recalc")) {
  3456. for (int i = 0; i < env->line_count; ++i) {
  3457. env->lines[i]->istate = 0;
  3458. }
  3459. for (int i = 0; i < env->line_count; ++i) {
  3460. recalculate_syntax(env->lines[i],i);
  3461. }
  3462. redraw_all();
  3463. } else if (!strcmp(argv[0], "tabs")) {
  3464. env->tabs = 1;
  3465. redraw_statusbar();
  3466. } else if (!strcmp(argv[0], "spaces")) {
  3467. env->tabs = 0;
  3468. redraw_statusbar();
  3469. } else if (!strcmp(argv[0], "tabstop")) {
  3470. if (argc < 2) {
  3471. render_status_message("tabstop=%d", env->tabstop);
  3472. } else {
  3473. int t = atoi(argv[1]);
  3474. if (t > 0 && t < 32) {
  3475. env->tabstop = t;
  3476. for (int i = 0; i < env->line_count; ++i) {
  3477. recalculate_tabs(env->lines[i]);
  3478. }
  3479. redraw_all();
  3480. } else {
  3481. render_error("Invalid tabstop: %s", argv[1]);
  3482. }
  3483. }
  3484. } else if (!strcmp(argv[0], "clearyank")) {
  3485. if (global_config.yanks) {
  3486. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  3487. free(global_config.yanks[i]);
  3488. }
  3489. free(global_config.yanks);
  3490. global_config.yanks = NULL;
  3491. global_config.yank_count = 0;
  3492. redraw_statusbar();
  3493. }
  3494. } else if (!strcmp(argv[0], "padding")) {
  3495. if (argc < 2) {
  3496. render_status_message("padding=%d", global_config.cursor_padding);
  3497. } else {
  3498. global_config.cursor_padding = atoi(argv[1]);
  3499. place_cursor_actual();
  3500. }
  3501. } else if (!strcmp(argv[0], "smartcase")) {
  3502. if (argc < 2) {
  3503. render_status_message("smartcase=%d", global_config.smart_case);
  3504. } else {
  3505. global_config.smart_case = atoi(argv[1]);
  3506. place_cursor_actual();
  3507. }
  3508. } else if (!strcmp(argv[0], "hlparen")) {
  3509. if (argc < 2) {
  3510. render_status_message("hlparen=%d", global_config.highlight_parens);
  3511. } else {
  3512. global_config.highlight_parens = atoi(argv[1]);
  3513. for (int i = 0; i < env->line_count; ++i) {
  3514. recalculate_syntax(env->lines[i],i);
  3515. }
  3516. redraw_text();
  3517. place_cursor_actual();
  3518. }
  3519. } else if (!strcmp(argv[0], "hlcurrent")) {
  3520. if (argc < 2) {
  3521. render_status_message("hlcurrent=%d", global_config.hilight_current_line);
  3522. } else {
  3523. global_config.hilight_current_line = atoi(argv[1]);
  3524. if (!global_config.hilight_current_line) {
  3525. for (int i = 0; i < env->line_count; ++i) {
  3526. env->lines[i]->is_current = 0;
  3527. }
  3528. }
  3529. redraw_text();
  3530. place_cursor_actual();
  3531. }
  3532. } else if (isdigit(*argv[0])) {
  3533. /* Go to line number */
  3534. goto_line(atoi(argv[0]));
  3535. } else {
  3536. /* Unrecognized command */
  3537. render_error("Not an editor command: %s", argv[0]);
  3538. }
  3539. }
  3540. /**
  3541. * Tab completion for command mode.
  3542. */
  3543. void command_tab_complete(char * buffer) {
  3544. /* Figure out which argument this is and where it starts */
  3545. int arg = 0;
  3546. char * buf = strdup(buffer);
  3547. char * b = buf;
  3548. char * args[32];
  3549. int candidate_count= 0;
  3550. int candidate_space = 4;
  3551. char ** candidates = malloc(sizeof(char*)*candidate_space);
  3552. /* Accept whitespace before first argument */
  3553. while (*b == ' ') b++;
  3554. char * start = b;
  3555. args[0] = start;
  3556. while (*b && *b != ' ') b++;
  3557. while (*b) {
  3558. while (*b == ' ') {
  3559. *b = '\0';
  3560. b++;
  3561. }
  3562. start = b;
  3563. arg++;
  3564. if (arg < 32) {
  3565. args[arg] = start;
  3566. }
  3567. while (*b && *b != ' ') b++;
  3568. }
  3569. /**
  3570. * Check a possible candidate and add it to the
  3571. * candidates list, expanding as necessary,
  3572. * if it matches for the current argument.
  3573. */
  3574. #define add_candidate(candidate) \
  3575. do { \
  3576. char * _arg = args[arg]; \
  3577. int r = strncmp(_arg, candidate, strlen(_arg)); \
  3578. if (!r) { \
  3579. if (candidate_count == candidate_space) { \
  3580. candidate_space *= 2; \
  3581. candidates = realloc(candidates,sizeof(char *) * candidate_space); \
  3582. } \
  3583. candidates[candidate_count] = strdup(candidate); \
  3584. candidate_count++; \
  3585. } \
  3586. } while (0)
  3587. if (arg == 0) {
  3588. /* Complete command names */
  3589. add_candidate("help");
  3590. add_candidate("recalc");
  3591. add_candidate("syntax");
  3592. add_candidate("tabn");
  3593. add_candidate("tabp");
  3594. add_candidate("tabnew");
  3595. add_candidate("theme");
  3596. add_candidate("tabs");
  3597. add_candidate("tabstop");
  3598. add_candidate("spaces");
  3599. add_candidate("noh");
  3600. add_candidate("clearyank");
  3601. add_candidate("indent");
  3602. add_candidate("noindent");
  3603. add_candidate("padding");
  3604. add_candidate("hlparen");
  3605. add_candidate("hlcurrent");
  3606. add_candidate("cursorcolumn");
  3607. add_candidate("smartcase");
  3608. goto _accept_candidate;
  3609. }
  3610. if (arg == 1 && !strcmp(args[0], "syntax")) {
  3611. /* Complete syntax options */
  3612. add_candidate("none");
  3613. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  3614. add_candidate(s->name);
  3615. }
  3616. goto _accept_candidate;
  3617. }
  3618. if (arg == 1 && !strcmp(args[0], "theme")) {
  3619. /* Complete color theme names */
  3620. for (struct theme_def * s = themes; s->name; ++s) {
  3621. add_candidate(s->name);
  3622. }
  3623. goto _accept_candidate;
  3624. }
  3625. if (arg == 1 && (!strcmp(args[0], "e") || !strcmp(args[0], "tabnew"))) {
  3626. /* Complete file paths */
  3627. /* First, find the deepest directory match */
  3628. char * tmp = strdup(args[arg]);
  3629. char * last_slash = strrchr(tmp, '/');
  3630. DIR * dirp;
  3631. if (last_slash) {
  3632. *last_slash = '\0';
  3633. if (last_slash == tmp) {
  3634. /* Started with slash, and it was the only slash */
  3635. dirp = opendir("/");
  3636. } else {
  3637. dirp = opendir(tmp);
  3638. }
  3639. } else {
  3640. /* No directory match, completing from current directory */
  3641. dirp = opendir(".");
  3642. tmp[0] = '\0';
  3643. }
  3644. if (!dirp) {
  3645. /* Directory match doesn't exist, no candidates to populate */
  3646. free(tmp);
  3647. goto done;
  3648. }
  3649. struct dirent * ent = readdir(dirp);
  3650. while (ent != NULL) {
  3651. if (ent->d_name[0] != '.' || (last_slash ? (last_slash[1] == '.') : (tmp[0] == '.'))) {
  3652. struct stat statbuf;
  3653. /* Figure out if this file is a directory */
  3654. if (last_slash) {
  3655. char * x = malloc(strlen(tmp) + 1 + strlen(ent->d_name) + 1);
  3656. snprintf(x, strlen(tmp) + 1 + strlen(ent->d_name) + 1, "%s/%s",tmp,ent->d_name);
  3657. stat(x, &statbuf);
  3658. free(x);
  3659. } else {
  3660. stat(ent->d_name, &statbuf);
  3661. }
  3662. /* Build the complete argument name to tab complete */
  3663. char s[1024] = {0};
  3664. if (last_slash == tmp) {
  3665. strcat(s,"/");
  3666. } else if (*tmp) {
  3667. strcat(s,tmp);
  3668. strcat(s,"/");
  3669. }
  3670. strcat(s,ent->d_name);
  3671. /*
  3672. * If it is a directory, add a / to the end so the next completion
  3673. * attempt will complete the directory's contents.
  3674. */
  3675. if (S_ISDIR(statbuf.st_mode)) {
  3676. strcat(s,"/");
  3677. }
  3678. add_candidate(s);
  3679. }
  3680. ent = readdir(dirp);
  3681. }
  3682. closedir(dirp);
  3683. free(tmp);
  3684. goto _accept_candidate;
  3685. }
  3686. _accept_candidate:
  3687. if (candidate_count == 0) {
  3688. redraw_statusbar();
  3689. goto done;
  3690. }
  3691. if (candidate_count == 1) {
  3692. /* Only one completion possibility */
  3693. redraw_statusbar();
  3694. /* Fill out the rest of the command */
  3695. char * cstart = (buffer) + (start - buf);
  3696. for (unsigned int i = 0; i < strlen(candidates[0]); ++i) {
  3697. *cstart = candidates[0][i];
  3698. cstart++;
  3699. }
  3700. *cstart = '\0';
  3701. } else {
  3702. /* Print candidates in status bar */
  3703. char * tmp = malloc(global_config.term_width+1);
  3704. memset(tmp, 0, global_config.term_width+1);
  3705. int offset = 0;
  3706. for (int i = 0; i < candidate_count; ++i) {
  3707. if (offset + 1 + (signed)strlen(candidates[i]) > global_config.term_width - 5) {
  3708. strcat(tmp, "...");
  3709. break;
  3710. }
  3711. if (offset > 0) {
  3712. strcat(tmp, " ");
  3713. offset++;
  3714. }
  3715. strcat(tmp, candidates[i]);
  3716. offset += strlen(candidates[i]);
  3717. }
  3718. render_status_message("%s", tmp);
  3719. free(tmp);
  3720. /* Complete to longest common substring */
  3721. char * cstart = (buffer) + (start - buf);
  3722. for (int i = 0; i < 1023 /* max length of command */; i++) {
  3723. for (int j = 1; j < candidate_count; ++j) {
  3724. if (candidates[0][i] != candidates[j][i]) goto _reject;
  3725. }
  3726. *cstart = candidates[0][i];
  3727. cstart++;
  3728. }
  3729. /* End of longest common substring */
  3730. _reject:
  3731. *cstart = '\0';
  3732. }
  3733. /* Free candidates */
  3734. for (int i = 0; i < candidate_count; ++i) {
  3735. free(candidates[i]);
  3736. }
  3737. /* Redraw command line */
  3738. done:
  3739. redraw_commandline();
  3740. printf(":%s", buffer);
  3741. free(candidates);
  3742. free(buf);
  3743. }
  3744. /**
  3745. * Command mode
  3746. *
  3747. * Accept a user command and then process it and
  3748. * return to normal mode.
  3749. *
  3750. * TODO: We only have basic line editing here; it might be
  3751. * nice to add more advanced line editing, like cursor
  3752. * movement, tab completion, etc. This is easier than
  3753. * with the shell since we have a lot more control over
  3754. * where the command input bar is rendered.
  3755. */
  3756. void command_mode(void) {
  3757. int c;
  3758. char buffer[1024] = {0};
  3759. int buffer_len = 0;
  3760. redraw_commandline();
  3761. printf(":");
  3762. show_cursor();
  3763. while ((c = bim_getch())) {
  3764. if (c == -1) {
  3765. /* Time out */
  3766. continue;
  3767. }
  3768. if (c == '\033') {
  3769. /* Escape, cancel command */
  3770. break;
  3771. } else if (c == ENTER_KEY || c == LINE_FEED) {
  3772. /* Enter, run command */
  3773. process_command(buffer);
  3774. break;
  3775. } else if (c == '\t') {
  3776. /* Handle tab completion */
  3777. command_tab_complete(buffer);
  3778. buffer_len = strlen(buffer);
  3779. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  3780. /* Backspace, delete last character in command buffer */
  3781. if (buffer_len > 0) {
  3782. buffer_len -= 1;
  3783. buffer[buffer_len] = '\0';
  3784. redraw_commandline();
  3785. printf(":%s", buffer);
  3786. } else {
  3787. /* If backspaced through entire command, cancel command mode */
  3788. redraw_commandline();
  3789. break;
  3790. }
  3791. } else {
  3792. /* Regular character */
  3793. buffer[buffer_len] = c;
  3794. buffer_len++;
  3795. printf("%c", c);
  3796. }
  3797. show_cursor();
  3798. }
  3799. }
  3800. int search_matches(uint32_t a, uint32_t b, int mode) {
  3801. if (mode == 0) {
  3802. return a == b;
  3803. } else if (mode == 1) {
  3804. return tolower(a) == tolower(b);
  3805. }
  3806. return 0;
  3807. }
  3808. int smart_case(uint32_t * str) {
  3809. if (!global_config.smart_case) return 0;
  3810. for (uint32_t * s = str; *s; ++s) {
  3811. if (tolower(*s) != (int)*s) {
  3812. return 0;
  3813. }
  3814. }
  3815. return 1;
  3816. }
  3817. /**
  3818. * Search forward from the given cursor position
  3819. * to find a basic search match.
  3820. *
  3821. * This could be more complicated...
  3822. */
  3823. void find_match(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  3824. int col = from_col;
  3825. int ignorecase = smart_case(str);
  3826. for (int i = from_line; i <= env->line_count; ++i) {
  3827. line_t * line = env->lines[i - 1];
  3828. int j = col - 1;
  3829. while (j < line->actual + 1) {
  3830. int k = j;
  3831. uint32_t * match = str;
  3832. while (k < line->actual + 1) {
  3833. if (*match == '\0') {
  3834. *out_line = i;
  3835. *out_col = j + 1;
  3836. return;
  3837. }
  3838. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  3839. match++;
  3840. k++;
  3841. }
  3842. j++;
  3843. }
  3844. col = 0;
  3845. }
  3846. }
  3847. /**
  3848. * Search backwards for matching string.
  3849. */
  3850. void find_match_backwards(int from_line, int from_col, int * out_line, int * out_col, uint32_t * str) {
  3851. int col = from_col;
  3852. int ignorecase = smart_case(str);
  3853. for (int i = from_line; i >= 1; --i) {
  3854. line_t * line = env->lines[i-1];
  3855. int j = col - 1;
  3856. while (j > -1) {
  3857. int k = j;
  3858. uint32_t * match = str;
  3859. while (k < line->actual + 1) {
  3860. if (*match == '\0') {
  3861. *out_line = i;
  3862. *out_col = j + 1;
  3863. return;
  3864. }
  3865. if (!(search_matches(*match, line->text[k].codepoint, ignorecase))) break;
  3866. match++;
  3867. k++;
  3868. }
  3869. j--;
  3870. }
  3871. col = (i > 1) ? (env->lines[i-2]->actual) : -1;
  3872. }
  3873. }
  3874. /**
  3875. * Draw the matched search result.
  3876. */
  3877. void draw_search_match(uint32_t * buffer, int redraw_buffer) {
  3878. for (int i = 0; i < env->line_count; ++i) {
  3879. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3880. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  3881. }
  3882. }
  3883. int line = -1, col = -1, _line = 1, _col = 1;
  3884. do {
  3885. find_match(_line, _col, &line, &col, buffer);
  3886. if (line != -1) {
  3887. line_t * l = env->lines[line-1];
  3888. uint32_t * t = buffer;
  3889. for (int i = col; *t; ++i, ++t) {
  3890. l->text[i-1].flags |= FLAG_SEARCH;
  3891. }
  3892. }
  3893. _line = line;
  3894. _col = col+1;
  3895. line = -1;
  3896. col = -1;
  3897. } while (_line != -1);
  3898. redraw_text();
  3899. place_cursor_actual();
  3900. redraw_statusbar();
  3901. redraw_commandline();
  3902. if (redraw_buffer != -1) {
  3903. printf(redraw_buffer == 1 ? "/" : "?");
  3904. uint32_t * c = buffer;
  3905. while (*c) {
  3906. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  3907. to_eight(*c, tmp);
  3908. printf("%s", tmp);
  3909. c++;
  3910. }
  3911. }
  3912. }
  3913. /**
  3914. * Search mode
  3915. *
  3916. * Search text for substring match.
  3917. */
  3918. void search_mode(int direction) {
  3919. uint32_t c;
  3920. uint32_t buffer[1024] = {0};
  3921. int buffer_len = 0;
  3922. /* utf-8 decoding */
  3923. /* Remember where the cursor is so we can cancel */
  3924. int prev_line = env->line_no;
  3925. int prev_col = env->col_no;
  3926. int prev_coffset = env->coffset;
  3927. int prev_offset = env->offset;
  3928. redraw_commandline();
  3929. printf(direction == 1 ? "/" : "?");
  3930. show_cursor();
  3931. uint32_t state = 0;
  3932. int cin;
  3933. while ((cin = bim_getch())) {
  3934. if (cin == -1) {
  3935. /* Time out */
  3936. continue;
  3937. }
  3938. if (!decode(&state, &c, cin)) {
  3939. if (c == '\033') {
  3940. /* Cancel search */
  3941. env->line_no = prev_line;
  3942. env->col_no = prev_col;
  3943. /* Unhighlight search matches */
  3944. for (int i = 0; i < env->line_count; ++i) {
  3945. for (int j = 0; j < env->lines[i]->actual; ++j) {
  3946. env->lines[i]->text[j].flags &= (~FLAG_SEARCH);
  3947. }
  3948. }
  3949. redraw_all();
  3950. break;
  3951. } else if (c == ENTER_KEY || c == LINE_FEED) {
  3952. /* Exit search */
  3953. if (env->search) {
  3954. free(env->search);
  3955. }
  3956. env->search = malloc((buffer_len + 1) * sizeof(uint32_t));
  3957. memcpy(env->search, buffer, (buffer_len + 1) * sizeof(uint32_t));
  3958. break;
  3959. } else if (c == BACKSPACE_KEY || c == DELETE_KEY) {
  3960. /* Backspace, delete last character in search buffer */
  3961. if (buffer_len > 0) {
  3962. buffer_len -= 1;
  3963. buffer[buffer_len] = '\0';
  3964. /* Search from beginning to find first match */
  3965. int line = -1, col = -1;
  3966. if (direction == 1) {
  3967. find_match(prev_line, prev_col, &line, &col, buffer);
  3968. } else {
  3969. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  3970. }
  3971. if (line != -1) {
  3972. env->col_no = col;
  3973. env->line_no = line;
  3974. set_preferred_column();
  3975. }
  3976. draw_search_match(buffer, direction);
  3977. } else {
  3978. /* If backspaced through entire search term, cancel search */
  3979. redraw_commandline();
  3980. env->coffset = prev_coffset;
  3981. env->offset = prev_offset;
  3982. env->col_no = prev_col;
  3983. set_preferred_column();
  3984. env->line_no = prev_line;
  3985. redraw_all();
  3986. break;
  3987. }
  3988. } else {
  3989. /* Regular character */
  3990. buffer[buffer_len] = c;
  3991. buffer_len++;
  3992. buffer[buffer_len] = '\0';
  3993. char tmp[7] = {0}; /* Max six bytes, use 7 to ensure last is always nil */
  3994. to_eight(c, tmp);
  3995. printf("%s", tmp);
  3996. /* Find the next search match */
  3997. int line = -1, col = -1;
  3998. if (direction == 1) {
  3999. find_match(prev_line, prev_col, &line, &col, buffer);
  4000. } else {
  4001. find_match_backwards(prev_line, prev_col, &line, &col, buffer);
  4002. }
  4003. if (line != -1) {
  4004. env->col_no = col;
  4005. env->line_no = line;
  4006. set_preferred_column();
  4007. } else {
  4008. env->coffset = prev_coffset;
  4009. env->offset = prev_offset;
  4010. env->col_no = prev_col;
  4011. set_preferred_column();
  4012. env->line_no = prev_line;
  4013. }
  4014. draw_search_match(buffer, direction);
  4015. }
  4016. show_cursor();
  4017. } else if (state == UTF8_REJECT) {
  4018. state = 0;
  4019. }
  4020. }
  4021. }
  4022. /**
  4023. * Find the next search result, or loop back around if at the end.
  4024. */
  4025. void search_next(void) {
  4026. if (!env->search) return;
  4027. if (env->coffset) env->coffset = 0;
  4028. int line = -1, col = -1;
  4029. find_match(env->line_no, env->col_no+1, &line, &col, env->search);
  4030. if (line == -1) {
  4031. find_match(1,1, &line, &col, env->search);
  4032. if (line == -1) return;
  4033. }
  4034. env->col_no = col;
  4035. env->line_no = line;
  4036. set_preferred_column();
  4037. draw_search_match(env->search, -1);
  4038. }
  4039. /**
  4040. * Find the previous search result, or loop to the end of the file.
  4041. */
  4042. void search_prev(void) {
  4043. if (!env->search) return;
  4044. if (env->coffset) env->coffset = 0;
  4045. int line = -1, col = -1;
  4046. find_match_backwards(env->line_no, env->col_no-1, &line, &col, env->search);
  4047. if (line == -1) {
  4048. find_match_backwards(env->line_count, env->lines[env->line_count-1]->actual, &line, &col, env->search);
  4049. if (line == -1) return;
  4050. }
  4051. env->col_no = col;
  4052. env->line_no = line;
  4053. set_preferred_column();
  4054. draw_search_match(env->search, -1);
  4055. }
  4056. /**
  4057. * Find the matching paren for this one.
  4058. *
  4059. * This approach skips having to do its own syntax parsing
  4060. * to deal with, eg., erroneous parens in comments. It does
  4061. * this by finding the matching paren with the same flag
  4062. * value, thus parens in strings will match, parens outside
  4063. * of strings will match, but parens in strings won't
  4064. * match parens outside of strings and so on.
  4065. */
  4066. void find_matching_paren(int * out_line, int * out_col) {
  4067. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4068. return; /* Invalid cursor position */
  4069. }
  4070. /* TODO: vim can find the nearest paren to start searching from, we need to be on one right now */
  4071. int paren_match = 0;
  4072. int direction = 0;
  4073. int start = env->lines[env->line_no-1]->text[env->col_no-1].codepoint;
  4074. int flags = env->lines[env->line_no-1]->text[env->col_no-1].flags & 0xF;
  4075. int count = 0;
  4076. /* TODO what about unicode parens? */
  4077. for (int i = 0; paren_pairs[i]; ++i) {
  4078. if (start == paren_pairs[i]) {
  4079. direction = (i % 2 == 0) ? 1 : -1;
  4080. paren_match = paren_pairs[(i % 2 == 0) ? (i+1) : (i-1)];
  4081. break;
  4082. }
  4083. }
  4084. if (!paren_match) return;
  4085. /* Scan for match */
  4086. int line = env->line_no;
  4087. int col = env->col_no;
  4088. do {
  4089. while (col > 0 && col < env->lines[line-1]->actual + 1) {
  4090. /* Only match on same syntax */
  4091. if ((env->lines[line-1]->text[col-1].flags & 0xF) == flags) {
  4092. /* Count up on same direction */
  4093. if (env->lines[line-1]->text[col-1].codepoint == start) count++;
  4094. /* Count down on opposite direction */
  4095. if (env->lines[line-1]->text[col-1].codepoint == paren_match) {
  4096. count--;
  4097. /* When count == 0 we have a match */
  4098. if (count == 0) goto _match_found;
  4099. }
  4100. }
  4101. col += direction;
  4102. }
  4103. line += direction;
  4104. /* Reached first/last line with no match */
  4105. if (line == 0 || line == env->line_count + 1) {
  4106. return;
  4107. }
  4108. /* Reset column to start/end of line, depending on direction */
  4109. if (direction > 0) {
  4110. col = 1;
  4111. } else {
  4112. col = env->lines[line-1]->actual;
  4113. }
  4114. } while (1);
  4115. _match_found:
  4116. *out_line = line;
  4117. *out_col = col;
  4118. }
  4119. /**
  4120. * Handle mouse event
  4121. */
  4122. void handle_mouse(void) {
  4123. int buttons = bim_getch() - 32;
  4124. int x = bim_getch() - 32;
  4125. int y = bim_getch() - 32;
  4126. if (buttons == 64) {
  4127. /* Scroll up */
  4128. for (int i = 0; i < 5; ++i) {
  4129. cursor_up();
  4130. }
  4131. return;
  4132. } else if (buttons == 65) {
  4133. /* Scroll down */
  4134. for (int i = 0; i < 5; ++i) {
  4135. cursor_down();
  4136. }
  4137. return;
  4138. } else if (buttons == 3) {
  4139. /* Move cursor to position */
  4140. if (x < 0) return;
  4141. if (y < 0) return;
  4142. if (y == 1) {
  4143. /* Pick from tabs */
  4144. int _x = 0;
  4145. for (int i = 0; i < buffers_len; i++) {
  4146. buffer_t * _env = buffers[i];
  4147. char tmp[64];
  4148. _x += draw_tab_name(_env, tmp);
  4149. if (_x >= x) {
  4150. env = buffers[i];
  4151. redraw_all();
  4152. return;
  4153. }
  4154. }
  4155. return;
  4156. }
  4157. /* Figure out y coordinate */
  4158. int line_no = y + env->offset - 1;
  4159. int col_no = -1;
  4160. if (line_no > env->line_count) {
  4161. line_no = env->line_count;
  4162. }
  4163. /* Account for the left hand gutter */
  4164. int num_size = num_width() + 3;
  4165. int _x = num_size - (line_no == env->line_no ? env->coffset : 0);
  4166. /* Determine where the cursor is physically */
  4167. for (int i = 0; i < env->lines[line_no-1]->actual; ++i) {
  4168. char_t * c = &env->lines[line_no-1]->text[i];
  4169. _x += c->display_width;
  4170. if (_x > x-1) {
  4171. col_no = i+1;
  4172. break;
  4173. }
  4174. }
  4175. if (col_no == -1 || col_no > env->lines[line_no-1]->actual) {
  4176. col_no = env->lines[line_no-1]->actual;
  4177. }
  4178. env->line_no = line_no;
  4179. env->col_no = col_no;
  4180. set_preferred_column();
  4181. place_cursor_actual();
  4182. }
  4183. return;
  4184. }
  4185. /**
  4186. * Append a character at the current cursor point.
  4187. */
  4188. void insert_char(unsigned int c) {
  4189. if (!c) {
  4190. render_error("Inserted nil byte?");
  4191. return;
  4192. }
  4193. char_t _c;
  4194. _c.codepoint = c;
  4195. _c.flags = 0;
  4196. _c.display_width = codepoint_width(c);
  4197. line_t * line = env->lines[env->line_no - 1];
  4198. line_t * nline = line_insert(line, _c, env->col_no - 1, env->line_no - 1);
  4199. if (line != nline) {
  4200. env->lines[env->line_no - 1] = nline;
  4201. }
  4202. env->col_no += 1;
  4203. set_modified();
  4204. }
  4205. /**
  4206. * Replace a single character at the current cursor point
  4207. */
  4208. void replace_char(unsigned int c) {
  4209. if (env->col_no < 1 || env->col_no > env->lines[env->line_no-1]->actual) return;
  4210. char_t _c;
  4211. _c.codepoint = c;
  4212. _c.flags = 0;
  4213. _c.display_width = codepoint_width(c);
  4214. line_replace(env->lines[env->line_no-1], _c, env->col_no-1, env->line_no-1);
  4215. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4216. set_modified();
  4217. }
  4218. /**
  4219. * Undo a history entry.
  4220. */
  4221. void undo_history(void) {
  4222. if (!global_config.history_enabled) return;
  4223. env->loading = 1;
  4224. history_t * e = env->history;
  4225. if (e->type == HISTORY_SENTINEL) {
  4226. env->loading = 0;
  4227. render_commandline_message("Already at oldest change");
  4228. return;
  4229. }
  4230. int count_chars = 0;
  4231. int count_lines = 0;
  4232. do {
  4233. if (e->type == HISTORY_SENTINEL) break;
  4234. switch (e->type) {
  4235. case HISTORY_INSERT:
  4236. /* Delete */
  4237. line_delete(
  4238. env->lines[e->contents.insert_delete_replace.lineno],
  4239. e->contents.insert_delete_replace.offset+1,
  4240. e->contents.insert_delete_replace.lineno
  4241. );
  4242. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4243. env->col_no = e->contents.insert_delete_replace.offset + 1;
  4244. count_chars++;
  4245. break;
  4246. case HISTORY_DELETE:
  4247. {
  4248. char_t _c = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  4249. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  4250. env->lines[e->contents.insert_delete_replace.lineno],
  4251. _c,
  4252. e->contents.insert_delete_replace.offset-1,
  4253. e->contents.insert_delete_replace.lineno
  4254. );
  4255. }
  4256. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4257. env->col_no = e->contents.insert_delete_replace.offset + 2;
  4258. count_chars++;
  4259. break;
  4260. case HISTORY_REPLACE:
  4261. {
  4262. char_t _o = {codepoint_width(e->contents.insert_delete_replace.old_codepoint),0,e->contents.insert_delete_replace.old_codepoint};
  4263. line_replace(
  4264. env->lines[e->contents.insert_delete_replace.lineno],
  4265. _o,
  4266. e->contents.insert_delete_replace.offset,
  4267. e->contents.insert_delete_replace.lineno
  4268. );
  4269. }
  4270. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4271. env->col_no = e->contents.insert_delete_replace.offset + 1;
  4272. count_chars++;
  4273. break;
  4274. case HISTORY_REMOVE_LINE:
  4275. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  4276. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  4277. env->line_no = e->contents.remove_replace_line.lineno + 2;
  4278. env->col_no = 1;
  4279. count_lines++;
  4280. break;
  4281. case HISTORY_ADD_LINE:
  4282. env->lines = remove_line(env->lines, e->contents.add_merge_split_lines.lineno);
  4283. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  4284. env->col_no = 1;
  4285. count_lines++;
  4286. break;
  4287. case HISTORY_REPLACE_LINE:
  4288. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.old_contents);
  4289. env->line_no = e->contents.remove_replace_line.lineno + 1;
  4290. env->col_no = 1;
  4291. count_lines++;
  4292. break;
  4293. case HISTORY_SPLIT_LINE:
  4294. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno+1);
  4295. env->line_no = e->contents.add_merge_split_lines.lineno + 2;
  4296. env->col_no = 1;
  4297. count_lines++;
  4298. break;
  4299. case HISTORY_MERGE_LINES:
  4300. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno-1, e->contents.add_merge_split_lines.split);
  4301. env->line_no = e->contents.add_merge_split_lines.lineno;
  4302. env->col_no = 1;
  4303. count_lines++;
  4304. break;
  4305. case HISTORY_BREAK:
  4306. /* Ignore break */
  4307. break;
  4308. default:
  4309. render_error("Unknown type %d!\n", e->type);
  4310. break;
  4311. }
  4312. env->history = e->previous;
  4313. e = env->history;
  4314. } while (e->type != HISTORY_BREAK);
  4315. if (env->line_no > env->line_count) env->line_no = env->line_count;
  4316. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  4317. env->modified = (env->history != env->last_save_history);
  4318. env->loading = 0;
  4319. for (int i = 0; i < env->line_count; ++i) {
  4320. env->lines[i]->istate = 0;
  4321. recalculate_tabs(env->lines[i]);
  4322. }
  4323. for (int i = 0; i < env->line_count; ++i) {
  4324. recalculate_syntax(env->lines[i],i);
  4325. }
  4326. place_cursor_actual();
  4327. update_title();
  4328. redraw_all();
  4329. render_commandline_message("%d character%s, %d line%s changed",
  4330. count_chars, (count_chars == 1) ? "" : "s",
  4331. count_lines, (count_lines == 1) ? "" : "s");
  4332. }
  4333. /**
  4334. * Replay a history entry.
  4335. */
  4336. void redo_history(void) {
  4337. if (!global_config.history_enabled) return;
  4338. env->loading = 1;
  4339. history_t * e = env->history->next;
  4340. if (!e) {
  4341. env->loading = 0;
  4342. render_commandline_message("Already at newest change");
  4343. return;
  4344. }
  4345. int count_chars = 0;
  4346. int count_lines = 0;
  4347. while (e) {
  4348. if (e->type == HISTORY_BREAK) {
  4349. env->history = e;
  4350. break;
  4351. }
  4352. switch (e->type) {
  4353. case HISTORY_INSERT:
  4354. {
  4355. char_t _c = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  4356. env->lines[e->contents.insert_delete_replace.lineno] = line_insert(
  4357. env->lines[e->contents.insert_delete_replace.lineno],
  4358. _c,
  4359. e->contents.insert_delete_replace.offset,
  4360. e->contents.insert_delete_replace.lineno
  4361. );
  4362. }
  4363. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4364. env->col_no = e->contents.insert_delete_replace.offset + 2;
  4365. count_chars++;
  4366. break;
  4367. case HISTORY_DELETE:
  4368. /* Delete */
  4369. line_delete(
  4370. env->lines[e->contents.insert_delete_replace.lineno],
  4371. e->contents.insert_delete_replace.offset,
  4372. e->contents.insert_delete_replace.lineno
  4373. );
  4374. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4375. env->col_no = e->contents.insert_delete_replace.offset + 1;
  4376. count_chars++;
  4377. break;
  4378. case HISTORY_REPLACE:
  4379. {
  4380. char_t _o = {codepoint_width(e->contents.insert_delete_replace.codepoint),0,e->contents.insert_delete_replace.codepoint};
  4381. line_replace(
  4382. env->lines[e->contents.insert_delete_replace.lineno],
  4383. _o,
  4384. e->contents.insert_delete_replace.offset,
  4385. e->contents.insert_delete_replace.lineno
  4386. );
  4387. }
  4388. env->line_no = e->contents.insert_delete_replace.lineno + 1;
  4389. env->col_no = e->contents.insert_delete_replace.offset + 2;
  4390. count_chars++;
  4391. break;
  4392. case HISTORY_ADD_LINE:
  4393. env->lines = add_line(env->lines, e->contents.remove_replace_line.lineno);
  4394. env->line_no = e->contents.remove_replace_line.lineno + 2;
  4395. env->col_no = 1;
  4396. count_lines++;
  4397. break;
  4398. case HISTORY_REMOVE_LINE:
  4399. env->lines = remove_line(env->lines, e->contents.remove_replace_line.lineno);
  4400. env->line_no = e->contents.add_merge_split_lines.lineno + 1;
  4401. env->col_no = 1;
  4402. count_lines++;
  4403. break;
  4404. case HISTORY_REPLACE_LINE:
  4405. replace_line(env->lines, e->contents.remove_replace_line.lineno, e->contents.remove_replace_line.contents);
  4406. env->line_no = e->contents.remove_replace_line.lineno + 2;
  4407. env->col_no = 1;
  4408. count_lines++;
  4409. break;
  4410. case HISTORY_MERGE_LINES:
  4411. env->lines = merge_lines(env->lines, e->contents.add_merge_split_lines.lineno);
  4412. env->line_no = e->contents.remove_replace_line.lineno + 1;
  4413. env->col_no = 1;
  4414. count_lines++;
  4415. break;
  4416. case HISTORY_SPLIT_LINE:
  4417. env->lines = split_line(env->lines, e->contents.add_merge_split_lines.lineno, e->contents.add_merge_split_lines.split);
  4418. env->line_no = e->contents.remove_replace_line.lineno + 2;
  4419. env->col_no = 1;
  4420. count_lines++;
  4421. break;
  4422. case HISTORY_BREAK:
  4423. /* Ignore break */
  4424. break;
  4425. default:
  4426. render_error("Unknown type %d!\n", e->type);
  4427. break;
  4428. }
  4429. env->history = e;
  4430. e = e->next;
  4431. }
  4432. if (env->line_no > env->line_count) env->line_no = env->line_count;
  4433. if (env->col_no > env->lines[env->line_no-1]->actual) env->col_no = env->lines[env->line_no-1]->actual;
  4434. env->modified = (env->history != env->last_save_history);
  4435. env->loading = 0;
  4436. for (int i = 0; i < env->line_count; ++i) {
  4437. env->lines[i]->istate = 0;
  4438. recalculate_tabs(env->lines[i]);
  4439. }
  4440. for (int i = 0; i < env->line_count; ++i) {
  4441. recalculate_syntax(env->lines[i],i);
  4442. }
  4443. place_cursor_actual();
  4444. update_title();
  4445. redraw_all();
  4446. render_commandline_message("%d character%s, %d line%s changed",
  4447. count_chars, (count_chars == 1) ? "" : "s",
  4448. count_lines, (count_lines == 1) ? "" : "s");
  4449. }
  4450. /**
  4451. * Move the cursor the start of the previous word.
  4452. */
  4453. void word_left(void) {
  4454. int line_no = env->line_no;
  4455. int col_no = env->col_no;
  4456. do {
  4457. col_no--;
  4458. while (col_no == 0) {
  4459. line_no--;
  4460. if (line_no == 0) {
  4461. goto_line(1);
  4462. set_preferred_column();
  4463. return;
  4464. }
  4465. col_no = env->lines[line_no-1]->actual;
  4466. }
  4467. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4468. do {
  4469. col_no--;
  4470. if (col_no == 0) {
  4471. col_no = 1;
  4472. break;
  4473. }
  4474. if (col_no == 1) {
  4475. env->col_no = 1;
  4476. env->line_no = line_no;
  4477. set_preferred_column();
  4478. redraw_statusbar();
  4479. place_cursor_actual();
  4480. return;
  4481. }
  4482. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4483. env->col_no = col_no;
  4484. env->line_no = line_no;
  4485. set_preferred_column();
  4486. cursor_right();
  4487. }
  4488. /**
  4489. * Word right
  4490. */
  4491. void word_right(void) {
  4492. int line_no = env->line_no;
  4493. int col_no = env->col_no;
  4494. do {
  4495. col_no++;
  4496. if (col_no > env->lines[line_no-1]->actual) {
  4497. line_no++;
  4498. if (line_no > env->line_count) {
  4499. env->line_no = env->line_count;
  4500. env->col_no = env->lines[env->line_no-1]->actual;
  4501. set_preferred_column();
  4502. redraw_statusbar();
  4503. place_cursor_actual();
  4504. return;
  4505. }
  4506. col_no = 0;
  4507. break;
  4508. }
  4509. } while (!isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4510. do {
  4511. col_no++;
  4512. while (col_no > env->lines[line_no-1]->actual) {
  4513. line_no++;
  4514. if (line_no >= env->line_count) {
  4515. env->col_no = env->lines[env->line_count-1]->actual;
  4516. env->line_no = env->line_count;
  4517. set_preferred_column();
  4518. redraw_statusbar();
  4519. place_cursor_actual();
  4520. return;
  4521. }
  4522. col_no = 1;
  4523. }
  4524. } while (isspace(env->lines[line_no-1]->text[col_no-1].codepoint));
  4525. env->col_no = col_no;
  4526. env->line_no = line_no;
  4527. set_preferred_column();
  4528. redraw_statusbar();
  4529. place_cursor_actual();
  4530. return;
  4531. }
  4532. /**
  4533. * Backspace from the current cursor position.
  4534. */
  4535. void delete_at_cursor(void) {
  4536. if (env->col_no > 1) {
  4537. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  4538. env->col_no -= 1;
  4539. if (env->coffset > 0) env->coffset--;
  4540. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4541. set_modified();
  4542. redraw_statusbar();
  4543. place_cursor_actual();
  4544. } else if (env->line_no > 1) {
  4545. int tmp = env->lines[env->line_no - 2]->actual;
  4546. merge_lines(env->lines, env->line_no - 1);
  4547. env->line_no -= 1;
  4548. env->col_no = tmp+1;
  4549. set_preferred_column();
  4550. redraw_text();
  4551. set_modified();
  4552. redraw_statusbar();
  4553. place_cursor_actual();
  4554. }
  4555. }
  4556. void delete_word(void) {
  4557. if (!env->lines[env->line_no-1]) return;
  4558. if (env->col_no > 1) {
  4559. do {
  4560. if (env->col_no > 1) {
  4561. line_delete(env->lines[env->line_no - 1], env->col_no - 1, env->line_no - 1);
  4562. env->col_no -= 1;
  4563. if (env->coffset > 0) env->coffset--;
  4564. }
  4565. } while (env->col_no > 1 && env->lines[env->line_no - 1]->text[env->col_no - 2].codepoint != ' ');
  4566. set_preferred_column();
  4567. redraw_text();
  4568. set_modified();
  4569. redraw_statusbar();
  4570. place_cursor_actual();
  4571. }
  4572. }
  4573. /**
  4574. * Break the current line in two at the current cursor position.
  4575. */
  4576. void insert_line_feed(void) {
  4577. if (env->col_no == env->lines[env->line_no - 1]->actual + 1) {
  4578. env->lines = add_line(env->lines, env->line_no);
  4579. } else {
  4580. env->lines = split_line(env->lines, env->line_no-1, env->col_no - 1);
  4581. }
  4582. env->col_no = 1;
  4583. env->line_no += 1;
  4584. set_preferred_column();
  4585. add_indent(env->line_no-1,env->line_no-2,0);
  4586. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  4587. env->offset += 1;
  4588. }
  4589. set_modified();
  4590. }
  4591. /**
  4592. * Yank lines between line start and line end (which may be in either order)
  4593. */
  4594. void yank_lines(int start, int end) {
  4595. if (global_config.yanks) {
  4596. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4597. free(global_config.yanks[i]);
  4598. }
  4599. free(global_config.yanks);
  4600. }
  4601. int lines_to_yank;
  4602. int start_point;
  4603. if (start <= end) {
  4604. lines_to_yank = end - start + 1;
  4605. start_point = start - 1;
  4606. } else {
  4607. lines_to_yank = start - end + 1;
  4608. start_point = end - 1;
  4609. }
  4610. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  4611. global_config.yank_count = lines_to_yank;
  4612. global_config.yank_is_full_lines = 1;
  4613. for (int i = 0; i < lines_to_yank; ++i) {
  4614. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  4615. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  4616. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  4617. global_config.yanks[i]->istate = 0;
  4618. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  4619. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  4620. global_config.yanks[i]->text[j].flags = 0;
  4621. }
  4622. }
  4623. }
  4624. /**
  4625. * Helper to yank part of a line into a new yank line.
  4626. */
  4627. void yank_partial_line(int yank_no, int line_no, int start_off, int count) {
  4628. global_config.yanks[yank_no] = malloc(sizeof(line_t) + sizeof(char_t) * (count + 1));
  4629. global_config.yanks[yank_no]->available = count + 1; /* ensure extra space */
  4630. global_config.yanks[yank_no]->actual = count;
  4631. global_config.yanks[yank_no]->istate = 0;
  4632. memcpy(&global_config.yanks[yank_no]->text, &env->lines[line_no]->text[start_off], sizeof(char_t) * count);
  4633. for (int i = 0; i < count; ++i) {
  4634. global_config.yanks[yank_no]->text[i].flags = 0;
  4635. }
  4636. }
  4637. /**
  4638. * Yank text...
  4639. */
  4640. void yank_text(int start_line, int start_col, int end_line, int end_col) {
  4641. if (global_config.yanks) {
  4642. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  4643. free(global_config.yanks[i]);
  4644. }
  4645. free(global_config.yanks);
  4646. }
  4647. int lines_to_yank = end_line - start_line + 1;
  4648. int start_point = start_line - 1;
  4649. global_config.yanks = malloc(sizeof(line_t *) * lines_to_yank);
  4650. global_config.yank_count = lines_to_yank;
  4651. global_config.yank_is_full_lines = 0;
  4652. if (lines_to_yank == 1) {
  4653. yank_partial_line(0, start_point, start_col - 1, (end_col - start_col + 1));
  4654. } else {
  4655. yank_partial_line(0, start_point, start_col - 1, (env->lines[start_point]->actual - start_col + 1));
  4656. /* Yank middle lines */
  4657. for (int i = 1; i < lines_to_yank - 1; ++i) {
  4658. global_config.yanks[i] = malloc(sizeof(line_t) + sizeof(char_t) * (env->lines[start_point+i]->available));
  4659. global_config.yanks[i]->available = env->lines[start_point+i]->available;
  4660. global_config.yanks[i]->actual = env->lines[start_point+i]->actual;
  4661. global_config.yanks[i]->istate = 0;
  4662. memcpy(&global_config.yanks[i]->text, &env->lines[start_point+i]->text, sizeof(char_t) * (env->lines[start_point+i]->actual));
  4663. for (int j = 0; j < global_config.yanks[i]->actual; ++j) {
  4664. global_config.yanks[i]->text[j].flags = 0;
  4665. }
  4666. }
  4667. /* Yank end line */
  4668. yank_partial_line(lines_to_yank-1, end_line - 1, 0, end_col);
  4669. }
  4670. }
  4671. /**
  4672. * Handle shared escape keys (mostly navigation)
  4673. */
  4674. int handle_escape(int * this_buf, int * timeout, int c) {
  4675. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '\033') {
  4676. this_buf[*timeout] = c;
  4677. (*timeout)++;
  4678. return 1;
  4679. }
  4680. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c != '[') {
  4681. *timeout = 0;
  4682. bim_unget(c);
  4683. return 1;
  4684. }
  4685. if (*timeout >= 1 && this_buf[*timeout-1] == '\033' && c == '[') {
  4686. *timeout = 1;
  4687. this_buf[*timeout] = c;
  4688. (*timeout)++;
  4689. return 0;
  4690. }
  4691. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[' &&
  4692. (isdigit(c) || c == ';')) {
  4693. this_buf[*timeout] = c;
  4694. (*timeout)++;
  4695. return 0;
  4696. }
  4697. if (*timeout >= 2 && this_buf[0] == '\033' && this_buf[1] == '[') {
  4698. switch (c) {
  4699. case 'M':
  4700. handle_mouse();
  4701. break;
  4702. case 'A': // up
  4703. cursor_up();
  4704. break;
  4705. case 'B': // down
  4706. cursor_down();
  4707. break;
  4708. case 'C': // right
  4709. if (this_buf[*timeout-1] == '5') {
  4710. word_right();
  4711. } else {
  4712. cursor_right();
  4713. }
  4714. break;
  4715. case 'D': // left
  4716. if (this_buf[*timeout-1] == '5') {
  4717. word_left();
  4718. } else {
  4719. cursor_left();
  4720. }
  4721. break;
  4722. case 'H': // home
  4723. cursor_home();
  4724. break;
  4725. case 'F': // end
  4726. cursor_end();
  4727. break;
  4728. case 'I':
  4729. goto_line(env->line_no - (global_config.term_height - 6));
  4730. break;
  4731. case 'G':
  4732. goto_line(env->line_no + global_config.term_height - 6);
  4733. break;
  4734. case 'Z':
  4735. /* Shift tab */
  4736. if (env->mode == MODE_LINE_SELECTION) {
  4737. *timeout = 0;
  4738. return 'Z';
  4739. }
  4740. break;
  4741. case '~':
  4742. switch (this_buf[*timeout-1]) {
  4743. case '1':
  4744. cursor_home();
  4745. break;
  4746. case '3':
  4747. if (env->mode == MODE_INSERT || env->mode == MODE_REPLACE) {
  4748. if (env->col_no < env->lines[env->line_no - 1]->actual + 1) {
  4749. line_delete(env->lines[env->line_no - 1], env->col_no, env->line_no - 1);
  4750. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4751. set_modified();
  4752. redraw_statusbar();
  4753. place_cursor_actual();
  4754. } else if (env->line_no < env->line_count) {
  4755. merge_lines(env->lines, env->line_no);
  4756. redraw_text();
  4757. set_modified();
  4758. redraw_statusbar();
  4759. place_cursor_actual();
  4760. }
  4761. }
  4762. break;
  4763. case '4':
  4764. cursor_end();
  4765. break;
  4766. case '5':
  4767. goto_line(env->line_no - (global_config.term_height - 6));
  4768. break;
  4769. case '6':
  4770. goto_line(env->line_no + global_config.term_height - 6);
  4771. break;
  4772. }
  4773. break;
  4774. default:
  4775. render_error("Unrecognized escape sequence identifier: %c", c);
  4776. break;
  4777. }
  4778. *timeout = 0;
  4779. return 0;
  4780. }
  4781. *timeout = 0;
  4782. return 0;
  4783. }
  4784. /**
  4785. * Standard navigation shared by normal, line, and char selection.
  4786. */
  4787. void handle_navigation(int c) {
  4788. switch (c) {
  4789. case 2: /* ctrl-b = page up */
  4790. goto_line(env->line_no - (global_config.term_height - 6));
  4791. break;
  4792. case 6: /* ctrl-f = page down */
  4793. goto_line(env->line_no + global_config.term_height - 6);
  4794. break;
  4795. case ':': /* Switch to command mode */
  4796. command_mode();
  4797. break;
  4798. case '/': /* Switch to search mode */
  4799. search_mode(1);
  4800. break;
  4801. case '?': /* Switch to search mode */
  4802. search_mode(0);
  4803. break;
  4804. case 'n': /* Jump to next search result */
  4805. search_next();
  4806. break;
  4807. case 'N': /* Jump backwards to previous search result */
  4808. search_prev();
  4809. break;
  4810. case 'j': /* Move cursor down */
  4811. cursor_down();
  4812. break;
  4813. case 'k': /* Move cursor up */
  4814. cursor_up();
  4815. break;
  4816. case 'h': /* Move cursor left */
  4817. cursor_left();
  4818. break;
  4819. case 'l': /* Move cursor right*/
  4820. cursor_right();
  4821. break;
  4822. case 'w': /* Move cursor one word right */
  4823. word_right();
  4824. break;
  4825. case ' ': /* Jump forward several lines */
  4826. goto_line(env->line_no + global_config.term_height - 6);
  4827. break;
  4828. case '%': /* Jump to matching brace/bracket */
  4829. if (env->mode == MODE_LINE_SELECTION || env->mode == MODE_CHAR_SELECTION) {
  4830. /* These modes need to recalculate syntax as find_matching_brace uses it to find appropriate match */
  4831. for (int i = 0; i < env->line_count; ++i) {
  4832. recalculate_syntax(env->lines[i],i);
  4833. }
  4834. }
  4835. {
  4836. int paren_line = -1, paren_col = -1;
  4837. find_matching_paren(&paren_line, &paren_col);
  4838. if (paren_line != -1) {
  4839. env->line_no = paren_line;
  4840. env->col_no = paren_col;
  4841. set_preferred_column();
  4842. place_cursor_actual();
  4843. redraw_statusbar();
  4844. }
  4845. }
  4846. break;
  4847. case '{': /* Jump to previous blank line */
  4848. env->col_no = 1;
  4849. if (env->line_no == 1) break;
  4850. do {
  4851. env->line_no--;
  4852. if (env->lines[env->line_no-1]->actual == 0) break;
  4853. } while (env->line_no > 1);
  4854. set_preferred_column();
  4855. redraw_statusbar();
  4856. break;
  4857. case '}': /* Jump to next blank line */
  4858. env->col_no = 1;
  4859. if (env->line_no == env->line_count) break;
  4860. do {
  4861. env->line_no++;
  4862. if (env->lines[env->line_no-1]->actual == 0) break;
  4863. } while (env->line_no < env->line_count);
  4864. set_preferred_column();
  4865. redraw_statusbar();
  4866. break;
  4867. case '$': /* Move cursor to end of line */
  4868. cursor_end();
  4869. break;
  4870. case '^':
  4871. case '0': /* Move cursor to beginning of line */
  4872. cursor_home();
  4873. break;
  4874. }
  4875. }
  4876. /**
  4877. * Macro for redrawing selected lines with appropriate highlighting.
  4878. */
  4879. #define _redraw_line(line, force_start_line) \
  4880. do { \
  4881. if (!(force_start_line) && (line) == start_line) break; \
  4882. if ((line) > env->line_count + 1) { \
  4883. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  4884. draw_excess_line((line) - env->offset - 1); \
  4885. } \
  4886. break; \
  4887. } \
  4888. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  4889. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  4890. (env->line_no == start_line && (line) != start_line)) { \
  4891. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  4892. } else { \
  4893. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  4894. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  4895. } \
  4896. } \
  4897. if ((line) - env->offset + 1 > 1 && \
  4898. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  4899. redraw_line((line) - env->offset - 1, (line)-1); \
  4900. } \
  4901. } while (0)
  4902. /**
  4903. * Adjust indentation on selected lines.
  4904. */
  4905. void adjust_indent(int start_line, int direction) {
  4906. int lines_to_cover = 0;
  4907. int start_point = 0;
  4908. if (start_line <= env->line_no) {
  4909. start_point = start_line - 1;
  4910. lines_to_cover = env->line_no - start_line + 1;
  4911. } else {
  4912. start_point = env->line_no - 1;
  4913. lines_to_cover = start_line - env->line_no + 1;
  4914. }
  4915. for (int i = 0; i < lines_to_cover; ++i) {
  4916. if ((direction == -1) && env->lines[start_point + i]->actual < 1) continue;
  4917. if (direction == -1) {
  4918. if (env->tabs) {
  4919. if (env->lines[start_point + i]->text[0].codepoint == '\t') {
  4920. line_delete(env->lines[start_point + i],1,start_point+i);
  4921. _redraw_line(start_point+i+1,1);
  4922. }
  4923. } else {
  4924. for (int j = 0; j < env->tabstop; ++j) {
  4925. if (env->lines[start_point + i]->text[0].codepoint == ' ') {
  4926. line_delete(env->lines[start_point + i],1,start_point+i);
  4927. }
  4928. }
  4929. _redraw_line(start_point+i+1,1);
  4930. }
  4931. } else if (direction == 1) {
  4932. if (env->tabs) {
  4933. char_t c;
  4934. c.codepoint = '\t';
  4935. c.display_width = env->tabstop;
  4936. c.flags = FLAG_SELECT;
  4937. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  4938. } else {
  4939. for (int j = 0; j < env->tabstop; ++j) {
  4940. char_t c;
  4941. c.codepoint = ' ';
  4942. c.display_width = 1;
  4943. c.flags = FLAG_SELECT;
  4944. env->lines[start_point + i] = line_insert(env->lines[start_point + i], c, 0, start_point + i);
  4945. }
  4946. }
  4947. _redraw_line(start_point+i+1,1);
  4948. }
  4949. }
  4950. if (env->col_no > env->lines[env->line_no-1]->actual) {
  4951. env->col_no = env->lines[env->line_no-1]->actual;
  4952. }
  4953. set_preferred_column();
  4954. set_modified();
  4955. }
  4956. /**
  4957. * LINE SELECTION mode
  4958. *
  4959. * Equivalent to visual line in vim; selects lines of texts.
  4960. */
  4961. void line_selection_mode(void) {
  4962. int start_line = env->line_no;
  4963. int prev_line = start_line;
  4964. env->mode = MODE_LINE_SELECTION;
  4965. redraw_commandline();
  4966. int c;
  4967. int timeout = 0;
  4968. int this_buf[20];
  4969. for (int j = 0; j < env->lines[env->line_no-1]->actual; ++j) {
  4970. env->lines[env->line_no-1]->text[j].flags |= FLAG_SELECT;
  4971. }
  4972. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  4973. while ((c = bim_getch())) {
  4974. if (c == -1) {
  4975. if (timeout && this_buf[timeout-1] == '\033') {
  4976. goto _leave_select_line;
  4977. }
  4978. timeout = 0;
  4979. continue;
  4980. } else {
  4981. if (timeout == 0) {
  4982. switch (c) {
  4983. case '\033':
  4984. if (timeout == 0) {
  4985. this_buf[timeout] = c;
  4986. timeout++;
  4987. }
  4988. break;
  4989. case DELETE_KEY:
  4990. case BACKSPACE_KEY:
  4991. cursor_left();
  4992. break;
  4993. case '\t':
  4994. if (env->readonly) goto _readonly;
  4995. adjust_indent(start_line, 1);
  4996. break;
  4997. case 'V':
  4998. goto _leave_select_line;
  4999. case 'y':
  5000. yank_lines(start_line, env->line_no);
  5001. goto _leave_select_line;
  5002. case 'D':
  5003. case 'd':
  5004. if (env->readonly) goto _readonly;
  5005. yank_lines(start_line, env->line_no);
  5006. if (start_line <= env->line_no) {
  5007. int lines_to_delete = env->line_no - start_line + 1;
  5008. for (int i = 0; i < lines_to_delete; ++i) {
  5009. remove_line(env->lines, start_line-1);
  5010. }
  5011. env->line_no = start_line;
  5012. } else {
  5013. int lines_to_delete = start_line - env->line_no + 1;
  5014. for (int i = 0; i < lines_to_delete; ++i) {
  5015. remove_line(env->lines, env->line_no-1);
  5016. }
  5017. }
  5018. if (env->line_no > env->line_count) {
  5019. env->line_no = env->line_count;
  5020. }
  5021. if (env->col_no > env->lines[env->line_no-1]->actual) {
  5022. env->col_no = env->lines[env->line_no-1]->actual;
  5023. }
  5024. set_preferred_column();
  5025. set_modified();
  5026. goto _leave_select_line;
  5027. default:
  5028. handle_navigation(c);
  5029. break;
  5030. }
  5031. } else {
  5032. switch (handle_escape(this_buf,&timeout,c)) {
  5033. case 1:
  5034. bim_unget(c);
  5035. goto _leave_select_line;
  5036. case 'Z':
  5037. /* Unindent */
  5038. if (env->readonly) goto _readonly;
  5039. adjust_indent(start_line, -1);
  5040. break;
  5041. }
  5042. }
  5043. /* Mark current line */
  5044. _redraw_line(env->line_no,0);
  5045. /* Properly mark everything in the span we just moved through */
  5046. if (prev_line < env->line_no) {
  5047. for (int i = prev_line; i < env->line_no; ++i) {
  5048. _redraw_line(i,0);
  5049. }
  5050. prev_line = env->line_no;
  5051. } else if (prev_line > env->line_no) {
  5052. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  5053. _redraw_line(i,0);
  5054. }
  5055. prev_line = env->line_no;
  5056. }
  5057. place_cursor_actual();
  5058. continue;
  5059. _readonly:
  5060. render_error("Buffer is read-only");
  5061. }
  5062. }
  5063. _leave_select_line:
  5064. set_history_break();
  5065. env->mode = MODE_NORMAL;
  5066. for (int i = 0; i < env->line_count; ++i) {
  5067. recalculate_syntax(env->lines[i],i);
  5068. }
  5069. redraw_all();
  5070. }
  5071. /**
  5072. * Determine if a column + line number are within range of the
  5073. * current character selection specified by start_line, etc.
  5074. *
  5075. * Used to determine how syntax flags should be set when redrawing
  5076. * selected text in CHAR SELECTION mode.
  5077. */
  5078. int point_in_range(int start_line, int end_line, int start_col, int end_col, int line, int col) {
  5079. if (start_line == end_line) {
  5080. if ( end_col < start_col) {
  5081. int tmp = end_col;
  5082. end_col = start_col;
  5083. start_col = tmp;
  5084. }
  5085. return (col >= start_col && col <= end_col);
  5086. }
  5087. if (start_line > end_line) {
  5088. int tmp = end_line;
  5089. end_line = start_line;
  5090. start_line = tmp;
  5091. tmp = end_col;
  5092. end_col = start_col;
  5093. start_col = tmp;
  5094. }
  5095. if (line < start_line || line > end_line) return 0;
  5096. if (line == start_line) {
  5097. return col >= start_col;
  5098. }
  5099. if (line == end_line) {
  5100. return col <= end_col;
  5101. }
  5102. return 1;
  5103. }
  5104. #define _redraw_line_char(line, force_start_line) \
  5105. do { \
  5106. if (!(force_start_line) && (line) == start_line) break; \
  5107. if ((line) > env->line_count + 1) { \
  5108. if ((line) - env->offset - 1 < global_config.term_height - global_config.bottom_size - 1) { \
  5109. draw_excess_line((line) - env->offset - 1); \
  5110. } \
  5111. break; \
  5112. } \
  5113. if ((env->line_no < start_line && ((line) < env->line_no || (line) > start_line)) || \
  5114. (env->line_no > start_line && ((line) > env->line_no || (line) < start_line)) || \
  5115. (env->line_no == start_line && (line) != start_line)) { \
  5116. /* Line is completely outside selection */ \
  5117. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  5118. } else { \
  5119. if ((line) == start_line || (line) == env->line_no) { \
  5120. recalculate_syntax(env->lines[(line)-1],(line)-1); \
  5121. } \
  5122. for (int j = 0; j < env->lines[(line)-1]->actual; ++j) { \
  5123. if (point_in_range(start_line, env->line_no,start_col, env->col_no, (line), j+1)) { \
  5124. env->lines[(line)-1]->text[j].flags |= FLAG_SELECT; \
  5125. } \
  5126. } \
  5127. } \
  5128. if ((line) - env->offset + 1 > 1 && \
  5129. (line) - env->offset - 1< global_config.term_height - global_config.bottom_size - 1) { \
  5130. redraw_line((line) - env->offset - 1, (line)-1); \
  5131. } \
  5132. } while (0)
  5133. /**
  5134. * CHAR SELECTION mode.
  5135. */
  5136. void char_selection_mode(void) {
  5137. int start_line = env->line_no;
  5138. int start_col = env->col_no;
  5139. int prev_line = start_line;
  5140. env->mode = MODE_CHAR_SELECTION;
  5141. redraw_commandline();
  5142. int c;
  5143. int timeout = 0;
  5144. int this_buf[20];
  5145. /* Select single character */
  5146. env->lines[env->line_no-1]->text[env->col_no-1].flags |= FLAG_SELECT;
  5147. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  5148. while ((c = bim_getch())) {
  5149. if (c == -1) {
  5150. if (timeout && this_buf[timeout-1] == '\033') {
  5151. goto _leave_select_char;
  5152. }
  5153. timeout = 0;
  5154. continue;
  5155. } else {
  5156. if (timeout == 0) {
  5157. switch (c) {
  5158. case '\033':
  5159. if (timeout == 0) {
  5160. this_buf[timeout] = c;
  5161. timeout++;
  5162. }
  5163. break;
  5164. case DELETE_KEY:
  5165. case BACKSPACE_KEY:
  5166. cursor_left();
  5167. break;
  5168. case 'v':
  5169. goto _leave_select_char;
  5170. case 'y':
  5171. {
  5172. int end_line = env->line_no;
  5173. int end_col = env->col_no;
  5174. if (start_line == end_line) {
  5175. if (start_col > end_col) {
  5176. int tmp = start_col;
  5177. start_col = end_col;
  5178. end_col = tmp;
  5179. }
  5180. } else if (start_line > end_line) {
  5181. int tmp = start_line;
  5182. start_line = end_line;
  5183. end_line = tmp;
  5184. tmp = start_col;
  5185. start_col = end_col;
  5186. end_col = tmp;
  5187. }
  5188. yank_text(start_line, start_col, end_line, end_col);
  5189. }
  5190. goto _leave_select_char;
  5191. case 'D':
  5192. case 'd':
  5193. if (env->readonly) goto _readonly;
  5194. {
  5195. int end_line = env->line_no;
  5196. int end_col = env->col_no;
  5197. if (start_line == end_line) {
  5198. if (start_col > end_col) {
  5199. int tmp = start_col;
  5200. start_col = end_col;
  5201. end_col = tmp;
  5202. }
  5203. yank_text(start_line, start_col, end_line, end_col);
  5204. for (int i = start_col; i <= end_col; ++i) {
  5205. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  5206. }
  5207. env->col_no = start_col;
  5208. } else {
  5209. if (start_line > end_line) {
  5210. int tmp = start_line;
  5211. start_line = end_line;
  5212. end_line = tmp;
  5213. tmp = start_col;
  5214. start_col = end_col;
  5215. end_col = tmp;
  5216. }
  5217. /* Copy lines */
  5218. yank_text(start_line, start_col, end_line, end_col);
  5219. /* Delete lines */
  5220. for (int i = start_line+1; i < end_line; ++i) {
  5221. remove_line(env->lines, start_line);
  5222. } /* end_line is no longer valid; should be start_line+1*/
  5223. /* Delete from start_col forward */
  5224. int tmp = env->lines[start_line-1]->actual;
  5225. for (int i = start_col; i <= tmp; ++i) {
  5226. line_delete(env->lines[start_line-1], start_col, start_line - 1);
  5227. }
  5228. for (int i = 1; i <= end_col; ++i) {
  5229. line_delete(env->lines[start_line], 1, start_line);
  5230. }
  5231. /* Merge start and end lines */
  5232. merge_lines(env->lines, start_line);
  5233. env->line_no = start_line;
  5234. env->col_no = start_col;
  5235. }
  5236. }
  5237. if (env->line_no > env->line_count) {
  5238. env->line_no = env->line_count;
  5239. }
  5240. set_preferred_column();
  5241. set_modified();
  5242. goto _leave_select_char;
  5243. default:
  5244. handle_navigation(c);
  5245. break;
  5246. }
  5247. } else {
  5248. switch (handle_escape(this_buf,&timeout,c)) {
  5249. case 1:
  5250. bim_unget(c);
  5251. goto _leave_select_char;
  5252. }
  5253. }
  5254. /* Mark current line */
  5255. _redraw_line_char(env->line_no,1);
  5256. /* Properly mark everything in the span we just moved through */
  5257. if (prev_line < env->line_no) {
  5258. for (int i = prev_line; i < env->line_no; ++i) {
  5259. _redraw_line_char(i,1);
  5260. }
  5261. prev_line = env->line_no;
  5262. } else if (prev_line > env->line_no) {
  5263. for (int i = env->line_no + 1; i <= prev_line; ++i) {
  5264. _redraw_line_char(i,1);
  5265. }
  5266. prev_line = env->line_no;
  5267. }
  5268. place_cursor_actual();
  5269. continue;
  5270. _readonly:
  5271. render_error("Buffer is read-only");
  5272. }
  5273. }
  5274. _leave_select_char:
  5275. set_history_break();
  5276. env->mode = MODE_NORMAL;
  5277. for (int i = 0; i < env->line_count; ++i) {
  5278. recalculate_syntax(env->lines[i],i);
  5279. }
  5280. redraw_all();
  5281. }
  5282. /**
  5283. * INSERT mode
  5284. *
  5285. * Accept input into the text buffer.
  5286. */
  5287. void insert_mode(void) {
  5288. int cin;
  5289. uint32_t c;
  5290. /* Set mode line */
  5291. env->mode = MODE_INSERT;
  5292. redraw_commandline();
  5293. /* Place the cursor in the text area */
  5294. place_cursor_actual();
  5295. int timeout = 0;
  5296. int this_buf[20];
  5297. uint32_t istate = 0;
  5298. int redraw = 0;
  5299. while ((cin = bim_getch_timeout((redraw ? 10 : 200)))) {
  5300. if (cin == -1) {
  5301. if (redraw) {
  5302. if (redraw & 2) {
  5303. redraw_text();
  5304. } else {
  5305. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  5306. }
  5307. redraw_statusbar();
  5308. place_cursor_actual();
  5309. redraw = 0;
  5310. }
  5311. if (timeout && this_buf[timeout-1] == '\033') {
  5312. leave_insert();
  5313. return;
  5314. }
  5315. timeout = 0;
  5316. continue;
  5317. }
  5318. if (!decode(&istate, &c, cin)) {
  5319. if (timeout == 0) {
  5320. switch (c) {
  5321. case '\033':
  5322. if (timeout == 0) {
  5323. this_buf[timeout] = c;
  5324. timeout++;
  5325. }
  5326. break;
  5327. case DELETE_KEY:
  5328. case BACKSPACE_KEY:
  5329. delete_at_cursor();
  5330. break;
  5331. case ENTER_KEY:
  5332. case LINE_FEED:
  5333. insert_line_feed();
  5334. redraw |= 2;
  5335. break;
  5336. case 22: /* ^V */
  5337. /* Insert next byte raw */
  5338. {
  5339. /* Indicate we're in literal mode */
  5340. render_commandline_message("^V");
  5341. /* Put the cursor back into the text field */
  5342. place_cursor_actual();
  5343. /* Get next character */
  5344. while ((cin = bim_getch()) == -1);
  5345. /* Insert literal */
  5346. insert_char(cin);
  5347. /* Redraw INSERT */
  5348. redraw_commandline();
  5349. /* Draw text */
  5350. redraw |= 1;
  5351. }
  5352. break;
  5353. case 23: /* ^W */
  5354. delete_word();
  5355. set_preferred_column();
  5356. break;
  5357. case '\t':
  5358. if (env->tabs) {
  5359. insert_char('\t');
  5360. } else {
  5361. for (int i = 0; i < env->tabstop; ++i) {
  5362. insert_char(' ');
  5363. }
  5364. }
  5365. redraw |= 1;
  5366. set_preferred_column();
  5367. break;
  5368. case '}':
  5369. if (env->indent) {
  5370. int was_whitespace = 1;
  5371. for (int i = 0; i < env->lines[env->line_no-1]->actual; ++i) {
  5372. if (env->lines[env->line_no-1]->text[i].codepoint != ' ' &&
  5373. env->lines[env->line_no-1]->text[i].codepoint != '\t') {
  5374. was_whitespace = 0;
  5375. break;
  5376. }
  5377. }
  5378. insert_char('}');
  5379. if (was_whitespace) {
  5380. int line = -1, col = -1;
  5381. env->col_no--;
  5382. find_matching_paren(&line,&col);
  5383. if (line != -1) {
  5384. while (env->lines[env->line_no-1]->actual) {
  5385. line_delete(env->lines[env->line_no-1], env->lines[env->line_no-1]->actual, env->line_no-1);
  5386. }
  5387. add_indent(env->line_no-1,line-1,1);
  5388. env->col_no = env->lines[env->line_no-1]->actual + 1;
  5389. insert_char('}');
  5390. }
  5391. }
  5392. set_preferred_column();
  5393. redraw |= 1;
  5394. break;
  5395. }
  5396. /* fallthrough */
  5397. default:
  5398. insert_char(c);
  5399. set_preferred_column();
  5400. redraw |= 1;
  5401. break;
  5402. }
  5403. } else {
  5404. if (handle_escape(this_buf,&timeout,c)) {
  5405. bim_unget(c);
  5406. leave_insert();
  5407. return;
  5408. }
  5409. }
  5410. } else if (istate == UTF8_REJECT) {
  5411. istate = 0;
  5412. }
  5413. }
  5414. }
  5415. /*
  5416. * REPLACE mode
  5417. *
  5418. * Like insert, but replaces characters.
  5419. */
  5420. void replace_mode(void) {
  5421. int cin;
  5422. uint32_t c;
  5423. /* Set mode line */
  5424. env->mode = MODE_REPLACE;
  5425. redraw_commandline();
  5426. /* Place the cursor in the text area */
  5427. place_cursor_actual();
  5428. int timeout = 0;
  5429. int this_buf[20];
  5430. uint32_t istate = 0;
  5431. while ((cin = bim_getch())) {
  5432. if (cin == -1) {
  5433. if (timeout && this_buf[timeout-1] == '\033') {
  5434. leave_insert();
  5435. return;
  5436. }
  5437. timeout = 0;
  5438. continue;
  5439. }
  5440. if (!decode(&istate, &c, cin)) {
  5441. if (timeout == 0) {
  5442. switch (c) {
  5443. case '\033':
  5444. if (timeout == 0) {
  5445. this_buf[timeout] = c;
  5446. timeout++;
  5447. }
  5448. break;
  5449. case DELETE_KEY:
  5450. case BACKSPACE_KEY:
  5451. if (env->line_no > 1 && env->col_no == 1) {
  5452. env->line_no--;
  5453. env->col_no = env->lines[env->line_no-1]->actual;
  5454. set_preferred_column();
  5455. place_cursor_actual();
  5456. } else {
  5457. cursor_left();
  5458. }
  5459. break;
  5460. case ENTER_KEY:
  5461. case LINE_FEED:
  5462. insert_line_feed();
  5463. redraw_text();
  5464. set_modified();
  5465. redraw_statusbar();
  5466. place_cursor_actual();
  5467. break;
  5468. default:
  5469. if (env->col_no <= env->lines[env->line_no - 1]->actual) {
  5470. replace_char(c);
  5471. env->col_no += 1;
  5472. } else {
  5473. insert_char(c);
  5474. redraw_line(env->line_no - env->offset - 1, env->line_no-1);
  5475. }
  5476. redraw_statusbar();
  5477. place_cursor_actual();
  5478. break;
  5479. }
  5480. } else {
  5481. if (handle_escape(this_buf,&timeout,c)) {
  5482. bim_unget(c);
  5483. leave_insert();
  5484. return;
  5485. }
  5486. }
  5487. } else if (istate == UTF8_REJECT) {
  5488. istate = 0;
  5489. }
  5490. }
  5491. }
  5492. /**
  5493. * NORMAL mode
  5494. *
  5495. * Default editor mode - just cursor navigation and keybinds
  5496. * to enter the other modes.
  5497. */
  5498. void normal_mode(void) {
  5499. while (1) {
  5500. place_cursor_actual();
  5501. int c;
  5502. int timeout = 0;
  5503. int this_buf[20];
  5504. while ((c = bim_getch())) {
  5505. if (c == -1) {
  5506. /* getch timed out, nothing to do in normal mode */
  5507. continue;
  5508. }
  5509. if (timeout == 0) {
  5510. switch (c) {
  5511. case '\033':
  5512. if (timeout == 0) {
  5513. this_buf[timeout] = c;
  5514. timeout++;
  5515. }
  5516. break;
  5517. case DELETE_KEY:
  5518. case BACKSPACE_KEY:
  5519. if (env->line_no > 1 && env->col_no == 1) {
  5520. env->line_no--;
  5521. env->col_no = env->lines[env->line_no-1]->actual;
  5522. set_preferred_column();
  5523. place_cursor_actual();
  5524. } else {
  5525. cursor_left();
  5526. }
  5527. break;
  5528. case 'V': /* Enter LINE SELECTION mode */
  5529. line_selection_mode();
  5530. break;
  5531. case 'v': /* Enter CHAR SELECTION mode */
  5532. char_selection_mode();
  5533. break;
  5534. case 'O': /* Append line before and enter INSERT mode */
  5535. {
  5536. if (env->readonly) goto _readonly;
  5537. env->lines = add_line(env->lines, env->line_no-1);
  5538. env->col_no = 1;
  5539. add_indent(env->line_no-1,env->line_no,0);
  5540. redraw_text();
  5541. set_preferred_column();
  5542. set_modified();
  5543. place_cursor_actual();
  5544. goto _insert;
  5545. }
  5546. case 'o': /* Append line after and enter INSERT mode */
  5547. {
  5548. if (env->readonly) goto _readonly;
  5549. env->lines = add_line(env->lines, env->line_no);
  5550. env->col_no = 1;
  5551. env->line_no += 1;
  5552. add_indent(env->line_no-1,env->line_no-2,0);
  5553. set_preferred_column();
  5554. if (env->line_no > env->offset + global_config.term_height - global_config.bottom_size - 1) {
  5555. env->offset += 1;
  5556. }
  5557. redraw_text();
  5558. set_modified();
  5559. place_cursor_actual();
  5560. goto _insert;
  5561. }
  5562. case 'a': /* Enter INSERT mode with cursor after current position */
  5563. if (env->col_no < env->lines[env->line_no-1]->actual + 1) {
  5564. env->col_no += 1;
  5565. }
  5566. goto _insert;
  5567. case 'P': /* Paste before */
  5568. case 'p': /* Paste after */
  5569. if (env->readonly) goto _readonly;
  5570. if (global_config.yanks) {
  5571. if (!global_config.yank_is_full_lines) {
  5572. /* Handle P for paste before, p for past after */
  5573. int target_column = (c == 'P' ? (env->col_no) : (env->col_no+1));
  5574. if (target_column > env->lines[env->line_no-1]->actual + 1) {
  5575. target_column = env->lines[env->line_no-1]->actual + 1;
  5576. }
  5577. if (global_config.yank_count > 1) {
  5578. /* Spit the current line at the current position */
  5579. env->lines = split_line(env->lines, env->line_no - 1, target_column - 1); /* Split after */
  5580. }
  5581. /* Insert first line at current position */
  5582. for (int i = 0; i < global_config.yanks[0]->actual; ++i) {
  5583. 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);
  5584. }
  5585. if (global_config.yank_count > 1) {
  5586. /* Insert full lines */
  5587. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  5588. env->lines = add_line(env->lines, env->line_no);
  5589. }
  5590. for (unsigned int i = 1; i < global_config.yank_count - 1; ++i) {
  5591. replace_line(env->lines, env->line_no + i - 1, global_config.yanks[i]);
  5592. }
  5593. /* Insert characters from last line into (what was) the next line */
  5594. for (int i = 0; i < global_config.yanks[global_config.yank_count-1]->actual; ++i) {
  5595. 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);
  5596. }
  5597. }
  5598. } else {
  5599. /* Insert full lines */
  5600. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5601. env->lines = add_line(env->lines, env->line_no - (c == 'P' ? 1 : 0));
  5602. }
  5603. for (unsigned int i = 0; i < global_config.yank_count; ++i) {
  5604. replace_line(env->lines, env->line_no - (c == 'P' ? 1 : 0) + i, global_config.yanks[i]);
  5605. }
  5606. }
  5607. /* Recalculate whole document syntax */
  5608. for (int i = 0; i < env->line_count; ++i) {
  5609. env->lines[i]->istate = 0;
  5610. }
  5611. for (int i = 0; i < env->line_count; ++i) {
  5612. recalculate_syntax(env->lines[i],i);
  5613. }
  5614. set_history_break();
  5615. set_modified();
  5616. redraw_all();
  5617. }
  5618. break;
  5619. case 'u': /* Undo one block of history */
  5620. undo_history();
  5621. break;
  5622. case 18: /* ^R - Redo one block of history */
  5623. redo_history();
  5624. break;
  5625. case 12: /* ^L - Repaint the whole screen */
  5626. redraw_all();
  5627. break;
  5628. case 'i': /* Enter INSERT mode */
  5629. _insert:
  5630. if (env->readonly) goto _readonly;
  5631. insert_mode();
  5632. redraw_statusbar();
  5633. redraw_commandline();
  5634. timeout = 0;
  5635. break;
  5636. case 'R': /* Enter REPLACE mode */
  5637. if (env->readonly) goto _readonly;
  5638. replace_mode();
  5639. redraw_statusbar();
  5640. redraw_commandline();
  5641. timeout = 0;
  5642. break;
  5643. _readonly:
  5644. render_error("Buffer is read-only");
  5645. break;
  5646. default:
  5647. handle_navigation(c);
  5648. break;
  5649. }
  5650. } else {
  5651. handle_escape(this_buf,&timeout,c);
  5652. }
  5653. place_cursor_actual();
  5654. }
  5655. }
  5656. }
  5657. /**
  5658. * Show help text for -?
  5659. */
  5660. static void show_usage(char * argv[]) {
  5661. #define _s "\033[3m"
  5662. #define _e "\033[0m\n"
  5663. printf(
  5664. "bim - Text editor\n"
  5665. "\n"
  5666. "usage: %s [options] [file]\n"
  5667. " %s [options] -- -\n"
  5668. "\n"
  5669. " -R " _s "open initial buffer read-only" _e
  5670. " -O " _s "set various options:" _e
  5671. " noscroll " _s "disable terminal scrolling" _e
  5672. " noaltscreen " _s "disable alternate screen buffer" _e
  5673. " nomouse " _s "disable mouse support" _e
  5674. " nounicode " _s "disable unicode display" _e
  5675. " nobright " _s "disable bright next" _e
  5676. " nohideshow " _s "disable togglging cursor visibility" _e
  5677. " nosyntax " _s "disable syntax highlighting on load" _e
  5678. " notitle " _s "disable title-setting escapes" _e
  5679. " history " _s "enable experimental undo/redo" _e
  5680. " -c,-C " _s "print file to stdout with syntax hilighting" _e
  5681. " " _s "-C includes line numbers, -c does not" _e
  5682. " -u " _s "override bimrc file" _e
  5683. " -? " _s "show this help text" _e
  5684. "\n", argv[0], argv[0]);
  5685. #undef _e
  5686. #undef _s
  5687. }
  5688. /**
  5689. * Load bimrc configuration file.
  5690. *
  5691. * At the moment, this a simple key=value list.
  5692. */
  5693. void load_bimrc(void) {
  5694. if (!global_config.bimrc_path) return;
  5695. /* Default is ~/.bimrc */
  5696. char * tmp = strdup(global_config.bimrc_path);
  5697. if (!*tmp) {
  5698. free(tmp);
  5699. return;
  5700. }
  5701. /* Parse ~ at the front of the path. */
  5702. if (*tmp == '~') {
  5703. char path[1024] = {0};
  5704. char * home = getenv("HOME");
  5705. if (!home) {
  5706. /* $HOME is unset? */
  5707. free(tmp);
  5708. return;
  5709. }
  5710. /* New path is $HOME/.bimrc */
  5711. snprintf(path, 1024, "%s%s", home, tmp+1);
  5712. free(tmp);
  5713. tmp = strdup(path);
  5714. }
  5715. /* Try to open the file */
  5716. FILE * bimrc = fopen(tmp, "r");
  5717. free(tmp);
  5718. if (!bimrc) {
  5719. /* No bimrc, or bad permissions */
  5720. return;
  5721. }
  5722. /* Parse through lines */
  5723. char line[1024];
  5724. while (!feof(bimrc)) {
  5725. char * l = fgets(line, 1023, bimrc);
  5726. /* Ignore bad lines */
  5727. if (!l) break;
  5728. if (!*l) continue;
  5729. if (*l == '\n') continue;
  5730. /* Ignore comment lines */
  5731. if (*l == '#') continue;
  5732. /* Remove linefeed at the end */
  5733. char *nl = strstr(l,"\n");
  5734. if (nl) *nl = '\0';
  5735. /* Extract value from keypair, if available
  5736. * (I foresee options without values in the future) */
  5737. char *value= strstr(l,"=");
  5738. if (value) {
  5739. *value = '\0';
  5740. value++;
  5741. }
  5742. /* theme=... */
  5743. if (!strcmp(l,"theme") && value) {
  5744. /* Examine available themes for a match. */
  5745. for (struct theme_def * d = themes; d->name; ++d) {
  5746. if (!strcmp(value, d->name)) {
  5747. d->load();
  5748. break;
  5749. }
  5750. }
  5751. }
  5752. /* enable history (experimental) */
  5753. if (!strcmp(l,"history")) {
  5754. global_config.history_enabled = (value ? atoi(value) : 1);
  5755. }
  5756. /* padding= */
  5757. if (!strcmp(l,"padding") && value) {
  5758. global_config.cursor_padding = atoi(value);
  5759. }
  5760. if (!strcmp(l,"hlparen") && value) {
  5761. global_config.highlight_parens = atoi(value);
  5762. }
  5763. /* Disable hilighting of current line */
  5764. if (!strcmp(l,"hlcurrent") && value) {
  5765. global_config.hilight_current_line = atoi(value);
  5766. }
  5767. }
  5768. fclose(bimrc);
  5769. }
  5770. /**
  5771. * Set some default values when certain terminals are detected.
  5772. */
  5773. void detect_weird_terminals(void) {
  5774. char * term = getenv("TERM");
  5775. if (term && !strcmp(term,"linux")) {
  5776. /* Linux VTs can't scroll. */
  5777. global_config.can_scroll = 0;
  5778. }
  5779. if (term && !strcmp(term,"cons25")) {
  5780. /* Dragonfly BSD console */
  5781. global_config.can_hideshow = 0;
  5782. global_config.can_altscreen = 0;
  5783. global_config.can_mouse = 0;
  5784. global_config.can_unicode = 0;
  5785. global_config.can_bright = 0;
  5786. }
  5787. if (term && !strcmp(term,"sortix")) {
  5788. /* sortix will spew title escapes to the screen, no good */
  5789. global_config.can_title = 0;
  5790. }
  5791. if (term && strstr(term,"tmux") == term) {
  5792. global_config.can_scroll = 0;
  5793. global_config.can_bce = 0;
  5794. }
  5795. if (term && strstr(term,"screen") == term) {
  5796. /* unfortunately */
  5797. global_config.can_24bit = 0;
  5798. global_config.can_italic = 0;
  5799. }
  5800. if (term && strstr(term,"toaru-vga") == term) {
  5801. global_config.can_24bit = 0; /* Also not strictly true */
  5802. global_config.can_256color = 0; /* Not strictly true */
  5803. }
  5804. }
  5805. /**
  5806. * Run global initialization tasks
  5807. */
  5808. void initialize(void) {
  5809. setlocale(LC_ALL, "");
  5810. detect_weird_terminals();
  5811. load_colorscheme_ansi();
  5812. load_bimrc();
  5813. buffers_avail = 4;
  5814. buffers = malloc(sizeof(buffer_t *) * buffers_avail);
  5815. }
  5816. /**
  5817. * Initialize terminal for editor display.
  5818. */
  5819. void init_terminal(void) {
  5820. set_alternate_screen();
  5821. update_screen_size();
  5822. get_initial_termios();
  5823. set_unbuffered();
  5824. mouse_enable();
  5825. signal(SIGWINCH, SIGWINCH_handler);
  5826. signal(SIGCONT, SIGCONT_handler);
  5827. signal(SIGTSTP, SIGTSTP_handler);
  5828. }
  5829. int main(int argc, char * argv[]) {
  5830. int opt;
  5831. while ((opt = getopt(argc, argv, "?c:C:u:RO:-:")) != -1) {
  5832. switch (opt) {
  5833. case 'R':
  5834. global_config.initial_file_is_read_only = 1;
  5835. break;
  5836. case 'c':
  5837. case 'C':
  5838. /* Print file to stdout using our syntax highlighting and color theme */
  5839. initialize();
  5840. global_config.go_to_line = 0;
  5841. open_file(optarg);
  5842. for (int i = 0; i < env->line_count; ++i) {
  5843. if (opt == 'C') {
  5844. draw_line_number(i);
  5845. }
  5846. render_line(env->lines[i], 6 * (env->lines[i]->actual + 1), 0);
  5847. reset();
  5848. fprintf(stdout, "\n");
  5849. }
  5850. return 0;
  5851. case 'u':
  5852. global_config.bimrc_path = optarg;
  5853. break;
  5854. case 'O':
  5855. /* Set various display options */
  5856. if (!strcmp(optarg,"noaltscreen")) global_config.can_altscreen = 0;
  5857. else if (!strcmp(optarg,"noscroll")) global_config.can_scroll = 0;
  5858. else if (!strcmp(optarg,"nomouse")) global_config.can_mouse = 0;
  5859. else if (!strcmp(optarg,"nounicode")) global_config.can_unicode = 0;
  5860. else if (!strcmp(optarg,"nobright")) global_config.can_bright = 0;
  5861. else if (!strcmp(optarg,"nohideshow")) global_config.can_hideshow = 0;
  5862. else if (!strcmp(optarg,"nosyntax")) global_config.hilight_on_open = 0;
  5863. else if (!strcmp(optarg,"nohistory")) global_config.history_enabled = 0;
  5864. else if (!strcmp(optarg,"notitle")) global_config.can_title = 0;
  5865. else if (!strcmp(optarg,"nobce")) global_config.can_bce = 0;
  5866. else {
  5867. fprintf(stderr, "%s: unrecognized -O option: %s\n", argv[0], optarg);
  5868. return 1;
  5869. }
  5870. break;
  5871. case '-':
  5872. if (!strcmp(optarg,"version")) {
  5873. fprintf(stderr, "bim %s %s\n", BIM_VERSION, BIM_COPYRIGHT);
  5874. fprintf(stderr, " Available syntax highlighters:");
  5875. for (struct syntax_definition * s = syntaxes; s->name; ++s) {
  5876. fprintf(stderr, " %s", s->name);
  5877. }
  5878. fprintf(stderr, "\n");
  5879. fprintf(stderr, " Available color themes:");
  5880. for (struct theme_def * d = themes; d->name; ++d) {
  5881. fprintf(stderr, " %s", d->name);
  5882. }
  5883. fprintf(stderr, "\n");
  5884. return 0;
  5885. }
  5886. break;
  5887. case '?':
  5888. show_usage(argv);
  5889. return 0;
  5890. }
  5891. }
  5892. /* Set up terminal */
  5893. initialize();
  5894. init_terminal();
  5895. /* Open file */
  5896. if (argc > optind) {
  5897. open_file(argv[optind]);
  5898. update_title();
  5899. if (global_config.initial_file_is_read_only) {
  5900. env->readonly = 1;
  5901. }
  5902. } else {
  5903. env = buffer_new();
  5904. update_title();
  5905. setup_buffer(env);
  5906. }
  5907. /* Draw the screen once */
  5908. redraw_all();
  5909. /* Start accepting key commands */
  5910. normal_mode();
  5911. return 0;
  5912. }