bim.c 146 KB

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