bim.c 155 KB

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