org-table.el 235 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346
  1. ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; URL: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains the table editor and spreadsheet for Org mode.
  23. ;; Watch out: Here we are talking about two different kind of tables.
  24. ;; Most of the code is for the tables created with the Org mode table editor.
  25. ;; Sometimes, we talk about tables created and edited with the table.el
  26. ;; Emacs package. We call the former org-type tables, and the latter
  27. ;; table.el-type tables.
  28. ;;; Code:
  29. (require 'cl-lib)
  30. (require 'org-macs)
  31. (require 'org-compat)
  32. (require 'org-keys)
  33. (declare-function calc-eval "calc" (str &optional separator &rest args))
  34. (declare-function face-remap-remove-relative "face-remap" (cookie))
  35. (declare-function face-remap-add-relative "face-remap" (face &rest specs))
  36. (declare-function org-at-timestamp-p "org" (&optional extended))
  37. (declare-function org-delete-backward-char "org" (N))
  38. (declare-function org-mode "org" ())
  39. (declare-function org-duration-p "org-duration" (duration &optional canonical))
  40. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  41. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  42. (declare-function org-element-contents "org-element" (element))
  43. (declare-function org-element-extract-element "org-element" (element))
  44. (declare-function org-element-interpret-data "org-element" (data))
  45. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  46. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  47. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  48. (declare-function org-element-property "org-element" (property element))
  49. (declare-function org-element-type "org-element" (element))
  50. (declare-function org-element-cache-reset "org-element" (&optional all))
  51. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  52. (declare-function org-export-create-backend "ox" (&rest rest) t)
  53. (declare-function org-export-data-with-backend "ox" (data backend info))
  54. (declare-function org-export-filter-apply-functions "ox" (filters value info))
  55. (declare-function org-export-first-sibling-p "ox" (blob info))
  56. (declare-function org-export-get-backend "ox" (name))
  57. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  58. (declare-function org-export-install-filters "ox" (info))
  59. (declare-function org-export-table-has-special-column-p "ox" (table))
  60. (declare-function org-export-table-row-is-special-p "ox" (table-row info))
  61. (declare-function org-forward-paragraph "org" (&optional arg))
  62. (declare-function org-id-find "org-id" (id &optional markerp))
  63. (declare-function org-indent-line "org" ())
  64. (declare-function org-load-modules-maybe "org" (&optional force))
  65. (declare-function org-restart-font-lock "org" ())
  66. (declare-function org-sort-remove-invisible "org" (s))
  67. (declare-function org-time-stamp-format "org" (&optional long inactive))
  68. (declare-function org-time-string-to-absolute "org" (s &optional daynr prefer buffer pos))
  69. (declare-function org-time-string-to-time "org" (s))
  70. (declare-function org-timestamp-up-day "org" (&optional arg))
  71. (defvar constants-unit-system)
  72. (defvar org-M-RET-may-split-line)
  73. (defvar org-element-use-cache)
  74. (defvar org-export-filters-alist)
  75. (defvar org-finish-function)
  76. (defvar org-inhibit-highlight-removal)
  77. (defvar org-inhibit-startup)
  78. (defvar org-selected-window)
  79. (defvar org-self-insert-cluster-for-undo)
  80. (defvar org-self-insert-command-undo-counter)
  81. (defvar org-ts-regexp)
  82. (defvar org-ts-regexp-both)
  83. (defvar org-ts-regexp-inactive)
  84. (defvar org-ts-regexp3)
  85. (defvar org-window-configuration)
  86. (defvar sort-fold-case)
  87. ;;; Customizables
  88. (defgroup org-table nil
  89. "Options concerning tables in Org mode."
  90. :tag "Org Table"
  91. :group 'org)
  92. (defcustom orgtbl-optimized t
  93. "Non-nil means use the optimized table editor version for `orgtbl-mode'.
  94. In the optimized version, the table editor takes over all simple keys that
  95. normally just insert a character. In tables, the characters are inserted
  96. in a way to minimize disturbing the table structure (i.e. in overwrite mode
  97. for empty fields). Outside tables, the correct binding of the keys is
  98. restored.
  99. Changing this variable requires a restart of Emacs to become
  100. effective."
  101. :group 'org-table
  102. :type 'boolean)
  103. (defcustom orgtbl-radio-table-templates
  104. '((latex-mode "% BEGIN RECEIVE ORGTBL %n
  105. % END RECEIVE ORGTBL %n
  106. \\begin{comment}
  107. #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
  108. | | |
  109. \\end{comment}\n")
  110. (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
  111. @c END RECEIVE ORGTBL %n
  112. @ignore
  113. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  114. | | |
  115. @end ignore\n")
  116. (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
  117. <!-- END RECEIVE ORGTBL %n -->
  118. <!--
  119. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  120. | | |
  121. -->\n")
  122. (org-mode "#+ BEGIN RECEIVE ORGTBL %n
  123. #+ END RECEIVE ORGTBL %n
  124. #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
  125. | | |
  126. "))
  127. "Templates for radio tables in different major modes.
  128. Each template must define lines that will be treated as a comment and that
  129. must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
  130. lines where \"%n\" will be replaced with the name of the table during
  131. insertion of the template. The transformed table will later be inserted
  132. between these lines.
  133. The template should also contain a minimal table in a multiline comment.
  134. If multiline comments are not possible in the buffer language,
  135. you can pack it into a string that will not be used when the code
  136. is compiled or executed. Above the table will you need a line with
  137. the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
  138. convert the table into a data structure useful in the
  139. language of the buffer. Check the manual for the section on
  140. \"Translator functions\", and more generally check out
  141. the Info node `(org)Tables in arbitrary syntax'.
  142. All occurrences of %n in a template will be replaced with the name of the
  143. table, obtained by prompting the user."
  144. :group 'org-table
  145. :type '(repeat
  146. (list (symbol :tag "Major mode")
  147. (string :tag "Format"))))
  148. (defgroup org-table-settings nil
  149. "Settings for tables in Org mode."
  150. :tag "Org Table Settings"
  151. :group 'org-table)
  152. (defcustom org-table-header-line-p nil
  153. "Activate `org-table-header-line-mode' by default?"
  154. :type 'boolean
  155. :package-version '(Org . "9.4")
  156. :group 'org-table)
  157. (defcustom org-table-default-size "5x2"
  158. "The default size for newly created tables, Columns x Rows."
  159. :group 'org-table-settings
  160. :type 'string)
  161. (defcustom org-table-number-regexp
  162. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][[:xdigit:].]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
  163. "Regular expression for recognizing numbers in table columns.
  164. If a table column contains mostly numbers, it will be aligned to the
  165. right. If not, it will be aligned to the left.
  166. The default value of this option is a regular expression which allows
  167. anything which looks remotely like a number as used in scientific
  168. context. For example, all of the following will be considered a
  169. number:
  170. 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
  171. Other options offered by the customize interface are more restrictive."
  172. :group 'org-table-settings
  173. :type '(choice
  174. (const :tag "Positive Integers"
  175. "^[0-9]+$")
  176. (const :tag "Integers"
  177. "^[-+]?[0-9]+$")
  178. (const :tag "Floating Point Numbers"
  179. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
  180. (const :tag "Floating Point Number or Integer"
  181. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
  182. (const :tag "Exponential, Floating point, Integer"
  183. "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
  184. (const :tag "Very General Number-Like, including hex and Calc radix"
  185. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][[:xdigit:].]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  186. (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
  187. "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][[:xdigit:].]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  188. (regexp :tag "Regexp:")))
  189. (defcustom org-table-number-fraction 0.5
  190. "Fraction of numbers in a column required to make the column align right.
  191. In a column all non-white fields are considered. If at least
  192. this fraction of fields is matched by `org-table-number-regexp',
  193. alignment to the right border applies."
  194. :group 'org-table-settings
  195. :type 'number)
  196. (defcustom org-table-formula-field-format "%s"
  197. "Format for fields which contain the result of a formula.
  198. For example, using \"~%s~\" will display the result within tilde
  199. characters. Beware that modifying the display can prevent the
  200. field from being used in another formula."
  201. :group 'org-table-settings
  202. :version "24.1"
  203. :type 'string)
  204. (defgroup org-table-editing nil
  205. "Behavior of tables during editing in Org mode."
  206. :tag "Org Table Editing"
  207. :group 'org-table)
  208. (defcustom org-table-automatic-realign t
  209. "Non-nil means automatically re-align table when pressing TAB or RETURN.
  210. When nil, aligning is only done with `\\[org-table-align]', or after column
  211. removal/insertion."
  212. :group 'org-table-editing
  213. :type 'boolean)
  214. (defcustom org-table-auto-blank-field t
  215. "Non-nil means automatically blank table field when starting to type into it.
  216. This only happens when typing immediately after a field motion
  217. command (TAB, S-TAB or RET)."
  218. :group 'org-table-editing
  219. :type 'boolean)
  220. (defcustom org-table-exit-follow-field-mode-when-leaving-table t
  221. "Non-nil means automatically exit the follow mode.
  222. When nil, the follow mode will stay on and be active in any table
  223. the cursor enters. Since the table follow filed mode messes with the
  224. window configuration, it is not recommended to set this variable to nil,
  225. except maybe locally in a special file that has mostly tables with long
  226. fields."
  227. :group 'org-table
  228. :version "24.1"
  229. :type 'boolean)
  230. (defcustom org-table-fix-formulas-confirm nil
  231. "Whether the user should confirm when Org fixes formulas."
  232. :group 'org-table-editing
  233. :version "24.1"
  234. :type '(choice
  235. (const :tag "with yes-or-no" yes-or-no-p)
  236. (const :tag "with y-or-n" y-or-n-p)
  237. (const :tag "no confirmation" nil)))
  238. (defcustom org-table-tab-jumps-over-hlines t
  239. "Non-nil means tab in the last column of a table with jump over a hline.
  240. If a horizontal separator line is following the current line,
  241. `org-table-next-field' can either create a new row before that line, or jump
  242. over the line. When this option is nil, a new line will be created before
  243. this line."
  244. :group 'org-table-editing
  245. :type 'boolean)
  246. (defcustom org-table-shrunk-column-indicator "…"
  247. "String to be displayed in a shrunk column."
  248. :group 'org-table-editing
  249. :type 'string
  250. :package-version '(Org . "9.2")
  251. :safe (lambda (v) (and (stringp v) (not (equal v "")))))
  252. (defgroup org-table-calculation nil
  253. "Options concerning tables in Org mode."
  254. :tag "Org Table Calculation"
  255. :group 'org-table)
  256. (defcustom org-table-use-standard-references 'from
  257. "Non-nil means using table references like B3 instead of @3$2.
  258. Possible values are:
  259. nil never use them
  260. from accept as input, do not present for editing
  261. t accept as input and present for editing"
  262. :group 'org-table-calculation
  263. :type '(choice
  264. (const :tag "Never, don't even check user input for them" nil)
  265. (const :tag "Always, both as user input, and when editing" t)
  266. (const :tag "Convert user input, don't offer during editing" from)))
  267. (defcustom org-table-copy-increment t
  268. "Non-nil means increment when copying current field with \
  269. `\\[org-table-copy-down]'."
  270. :group 'org-table-calculation
  271. :version "26.1"
  272. :package-version '(Org . "8.3")
  273. :type '(choice
  274. (const :tag "Use the difference between the current and the above fields" t)
  275. (integer :tag "Use a number" 1)
  276. (const :tag "Don't increment the value when copying a field" nil)))
  277. (defcustom org-calc-default-modes
  278. '(calc-internal-prec 12
  279. calc-float-format (float 8)
  280. calc-angle-mode deg
  281. calc-prefer-frac nil
  282. calc-symbolic-mode nil
  283. calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
  284. calc-display-working-message t)
  285. "List with Calc mode settings for use in `calc-eval' for table formulas.
  286. The list must contain alternating symbols (Calc modes variables and values).
  287. Don't remove any of the default settings, just change the values. Org mode
  288. relies on the variables to be present in the list."
  289. :group 'org-table-calculation
  290. :type 'plist)
  291. (defcustom org-table-duration-custom-format 'hours
  292. "Format for the output of calc computations like $1+$2;t.
  293. The default value is `hours', and will output the results as a
  294. number of hours. Other allowed values are `seconds', `minutes' and
  295. `days', and the output will be a fraction of seconds, minutes or
  296. days. `hh:mm' selects to use hours and minutes, ignoring seconds.
  297. The `U' flag in a table formula will select this specific format for
  298. a single formula."
  299. :group 'org-table-calculation
  300. :version "24.1"
  301. :type '(choice (symbol :tag "Seconds" 'seconds)
  302. (symbol :tag "Minutes" 'minutes)
  303. (symbol :tag "Hours " 'hours)
  304. (symbol :tag "Days " 'days)
  305. (symbol :tag "HH:MM " 'hh:mm)))
  306. (defcustom org-table-duration-hour-zero-padding t
  307. "Non-nil means hours in table duration computations should be zero-padded.
  308. So this is about 08:32:34 versus 8:33:34."
  309. :group 'org-table-calculation
  310. :version "26.1"
  311. :package-version '(Org . "9.1")
  312. :type 'boolean
  313. :safe #'booleanp)
  314. (defcustom org-table-formula-evaluate-inline t
  315. "Non-nil means TAB and RET evaluate a formula in current table field.
  316. If the current field starts with an equal sign, it is assumed to be a formula
  317. which should be evaluated as described in the manual and in the documentation
  318. string of the command `org-table-eval-formula'. This feature requires the
  319. Emacs calc package.
  320. When this variable is nil, formula calculation is only available through
  321. the command `\\[org-table-eval-formula]'."
  322. :group 'org-table-calculation
  323. :type 'boolean)
  324. (defcustom org-table-formula-use-constants t
  325. "Non-nil means interpret constants in formulas in tables.
  326. A constant looks like `$c' or `$Grav' and will be replaced before evaluation
  327. by the value given in `org-table-formula-constants', or by a value obtained
  328. from the `constants.el' package."
  329. :group 'org-table-calculation
  330. :type 'boolean)
  331. (defcustom org-table-formula-constants nil
  332. "Alist with constant names and values, for use in table formulas.
  333. The car of each element is a name of a constant, without the `$' before it.
  334. The cdr is the value as a string. For example, if you'd like to use the
  335. speed of light in a formula, you would configure
  336. (setq org-table-formula-constants \\='((\"c\" . \"299792458.\")))
  337. and then use it in an equation like `$1*$c'.
  338. Constants can also be defined on a per-file basis using a line like
  339. #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
  340. :group 'org-table-calculation
  341. :type '(repeat
  342. (cons (string :tag "name")
  343. (string :tag "value"))))
  344. (defcustom org-table-allow-automatic-line-recalculation t
  345. "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
  346. \\<org-mode-map>\
  347. Automatically means when `TAB' or `RET' or `\\[org-ctrl-c-ctrl-c]' \
  348. are pressed in the line."
  349. :group 'org-table-calculation
  350. :type 'boolean)
  351. (defcustom org-table-relative-ref-may-cross-hline t
  352. "Non-nil means relative formula references may cross hlines.
  353. Here are the allowed values:
  354. nil Relative references may not cross hlines. They will reference the
  355. field next to the hline instead. Coming from below, the reference
  356. will be to the field below the hline. Coming from above, it will be
  357. to the field above.
  358. t Relative references may cross hlines.
  359. error An attempt to cross a hline will throw an error.
  360. It is probably good to never set this variable to nil, for the sake of
  361. portability of tables."
  362. :group 'org-table-calculation
  363. :type '(choice
  364. (const :tag "Allow to cross" t)
  365. (const :tag "Stick to hline" nil)
  366. (const :tag "Error on attempt to cross" error)))
  367. (defcustom org-table-formula-create-columns nil
  368. "Non-nil means evaluation of formula can add new columns.
  369. When non-nil, evaluating an out-of-bounds field can insert as
  370. many columns as needed. When set to `warn', issue a warning when
  371. doing so. When set to `prompt', ask user before creating a new
  372. column. Otherwise, throw an error."
  373. :group 'org-table-calculation
  374. :package-version '(Org . "8.3")
  375. :type '(choice
  376. (const :tag "Out-of-bounds field generates an error (default)" nil)
  377. (const :tag "Out-of-bounds field silently adds columns as needed" t)
  378. (const :tag "Out-of-bounds field adds columns, but issues a warning" warn)
  379. (const :tag "Prompt user when setting an out-of-bounds field" prompt)))
  380. (defgroup org-table-import-export nil
  381. "Options concerning table import and export in Org mode."
  382. :tag "Org Table Import Export"
  383. :group 'org-table)
  384. (defcustom org-table-export-default-format "orgtbl-to-tsv"
  385. "Default export parameters for `org-table-export'.
  386. These can be overridden for a specific table by setting the
  387. TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
  388. radio tables for the different export transformations and
  389. available parameters."
  390. :group 'org-table-import-export
  391. :type 'string)
  392. (defcustom org-table-convert-region-max-lines 999
  393. "Max lines that `org-table-convert-region' will attempt to process.
  394. The function can be slow on larger regions; this safety feature
  395. prevents it from hanging Emacs."
  396. :group 'org-table-import-export
  397. :type 'integer
  398. :package-version '(Org . "8.3"))
  399. ;;; Org table header minor mode
  400. (defun org-table-row-get-visible-string (&optional pos)
  401. "Get the visible string of a table row.
  402. This may be useful when columns have been shrunk."
  403. (save-excursion
  404. (when pos (goto-char pos))
  405. (goto-char (line-beginning-position))
  406. (let ((end (line-end-position)) str)
  407. (goto-char (1- pos))
  408. (while (progn (forward-char 1) (< (point) end))
  409. (let ((ov (car (overlays-at (point)))))
  410. (if (not ov)
  411. (push (char-to-string (char-after)) str)
  412. (push (overlay-get ov 'display) str)
  413. (goto-char (1- (overlay-end ov))))))
  414. (format "|%s" (mapconcat #'identity (reverse str) "")))))
  415. (defvar-local org-table-header-overlay nil)
  416. (defun org-table-header-set-header ()
  417. "Display the header of the table at point."
  418. (let ((gcol temporary-goal-column))
  419. (unwind-protect
  420. (progn
  421. (when (overlayp org-table-header-overlay)
  422. (delete-overlay org-table-header-overlay))
  423. (let* ((ws (window-start))
  424. (beg (save-excursion
  425. (goto-char (org-table-begin))
  426. (while (or (org-at-table-hline-p)
  427. (looking-at-p ".*|\\s-+<[rcl]?\\([0-9]+\\)?>"))
  428. (move-beginning-of-line 2))
  429. (line-beginning-position)))
  430. (end (save-excursion (goto-char beg) (point-at-eol))))
  431. (if (pos-visible-in-window-p beg)
  432. (when (overlayp org-table-header-overlay)
  433. (delete-overlay org-table-header-overlay))
  434. (setq org-table-header-overlay
  435. (make-overlay ws (+ ws (- end beg))))
  436. (org-overlay-display
  437. org-table-header-overlay
  438. (org-table-row-get-visible-string beg)
  439. 'org-table-header))))
  440. (setq temporary-goal-column gcol))))
  441. ;;;###autoload
  442. (define-minor-mode org-table-header-line-mode
  443. "Display the first row of the table at point in the header line."
  444. :lighter " TblHeader"
  445. (unless (eq major-mode 'org-mode)
  446. (user-error "Cannot turn org table header mode outside org-mode buffers"))
  447. (if org-table-header-line-mode
  448. (add-hook 'post-command-hook #'org-table-header-set-header nil t)
  449. (when (overlayp org-table-header-overlay)
  450. (delete-overlay org-table-header-overlay)
  451. (setq org-table-header-overlay nil))
  452. (remove-hook 'post-command-hook #'org-table-header-set-header t)))
  453. ;;; Regexps Constants
  454. (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
  455. "Detect an org-type or table-type table.")
  456. (defconst org-table-line-regexp "^[ \t]*|"
  457. "Detect an org-type table line.")
  458. (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
  459. "Detect an org-type table line.")
  460. (defconst org-table-hline-regexp "^[ \t]*|-"
  461. "Detect an org-type table hline.")
  462. (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
  463. "Detect a table-type table hline.")
  464. (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
  465. "Detect the first line outside a table when searching from within it.
  466. This works for both table types.")
  467. (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
  468. "Detect a #+TBLFM line.")
  469. (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
  470. (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
  471. "Regexp matching a line marked for automatic recalculation.")
  472. (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
  473. "Regexp matching a line marked for recalculation.")
  474. (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
  475. "Regexp matching a line marked for calculation.")
  476. (defconst org-table-border-regexp "^[ \t]*[^| \t]"
  477. "Regexp matching any line outside an Org table.")
  478. (defconst org-table-range-regexp
  479. "@\\([-+]?I*[-+]?[0-9]*\\)\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)\\(\\$[-+]?[0-9]+\\)?\\)?"
  480. ;; 1 2 3 4 5
  481. "Regular expression for matching ranges in formulas.")
  482. (defconst org-table-range-regexp2
  483. (concat
  484. "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
  485. "\\.\\."
  486. "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
  487. "Match a range for reference display.")
  488. (defconst org-table-translate-regexp
  489. (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
  490. "Match a reference that needs translation, for reference display.")
  491. (defconst org-table-separator-space
  492. (propertize " " 'display '(space :relative-width 1))
  493. "Space used around fields when aligning the table.
  494. This space serves as a segment separator for the purposes of the
  495. bidirectional reordering.")
  496. ;;; Internal Variables
  497. (defvar org-table-last-highlighted-reference nil)
  498. (defvar org-table-formula-history nil)
  499. (defvar org-field-marker nil)
  500. (defvar org-table-buffer-is-an nil)
  501. (defvar-local org-table-formula-constants-local nil
  502. "Local version of `org-table-formula-constants'.")
  503. (defvar org-table-may-need-update t
  504. "Indicates that a table might need an update.
  505. This variable is set by `org-before-change-function'.
  506. `org-table-align' sets it back to nil.")
  507. (defvar orgtbl-after-send-table-hook nil
  508. "Hook for functions attaching to `C-c C-c', if the table is sent.
  509. This can be used to add additional functionality after the table is sent
  510. to the receiver position, otherwise, if table is not sent, the functions
  511. are not run.")
  512. (defvar org-table-column-names nil
  513. "Alist with column names, derived from the `!' line.
  514. This variable is initialized with `org-table-analyze'.")
  515. (defvar org-table-column-name-regexp nil
  516. "Regular expression matching the current column names.
  517. This variable is initialized with `org-table-analyze'.")
  518. (defvar org-table-local-parameters nil
  519. "Alist with parameter names, derived from the `$' line.
  520. This variable is initialized with `org-table-analyze'.")
  521. (defvar org-table-named-field-locations nil
  522. "Alist with locations of named fields.
  523. Associations follow the pattern (NAME LINE COLUMN) where
  524. NAME is the name of the field as a string,
  525. LINE is the number of lines from the beginning of the table,
  526. COLUMN is the column of the field, as an integer.
  527. This variable is initialized with `org-table-analyze'.")
  528. (defvar org-table-current-line-types nil
  529. "Table row types in current table.
  530. This variable is initialized with `org-table-analyze'.")
  531. (defvar org-table-current-begin-pos nil
  532. "Current table begin position, as a marker.
  533. This variable is initialized with `org-table-analyze'.")
  534. (defvar org-table-current-ncol nil
  535. "Number of columns in current table.
  536. This variable is initialized with `org-table-analyze'.")
  537. (defvar org-table-dlines nil
  538. "Vector of data line line numbers in the current table.
  539. Line numbers are counted from the beginning of the table. This
  540. variable is initialized with `org-table-analyze'.")
  541. (defvar org-table-hlines nil
  542. "Vector of hline line numbers in the current table.
  543. Line numbers are counted from the beginning of the table. This
  544. variable is initialized with `org-table-analyze'.")
  545. (defvar org-table-aligned-begin-marker (make-marker)
  546. "Marker at the beginning of the table last aligned.
  547. Used to check if cursor still is in that table, to minimize realignment.")
  548. (defvar org-table-aligned-end-marker (make-marker)
  549. "Marker at the end of the table last aligned.
  550. Used to check if cursor still is in that table, to minimize realignment.")
  551. (defvar org-table-last-alignment nil
  552. "List of flags for flushright alignment, from the last re-alignment.
  553. This is being used to correctly align a single field after TAB or RET.")
  554. (defvar org-table-last-column-widths nil
  555. "List of max width of fields in each column.
  556. This is being used to correctly align a single field after TAB or RET.")
  557. (defvar-local org-table-formula-debug nil
  558. "Non-nil means debug table formulas.
  559. When nil, simply write \"#ERROR\" in corrupted fields.")
  560. (defvar-local org-table-overlay-coordinates nil
  561. "Overlay coordinates after each align of a table.")
  562. (defvar org-last-recalc-line nil)
  563. (defvar org-show-positions nil)
  564. (defvar org-table-rectangle-overlays nil)
  565. (defvar org-table-clip nil
  566. "Clipboard for table regions.")
  567. (defvar org-timecnt nil)
  568. (defvar org-recalc-commands nil
  569. "List of commands triggering the recalculation of a line.
  570. Will be filled automatically during use.")
  571. (defvar org-recalc-marks
  572. '((" " . "Unmarked: no special line, no automatic recalculation")
  573. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  574. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  575. ("!" . "Column name definition line. Reference in formula as $name.")
  576. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  577. ("_" . "Names for values in row below this one.")
  578. ("^" . "Names for values in row above this one.")))
  579. (defvar org-pos nil)
  580. ;;; Macros and Inlined Functions
  581. (defmacro org-table-with-shrunk-columns (&rest body)
  582. "Expand all columns before executing BODY, then shrink them again."
  583. (declare (debug (body)))
  584. (org-with-gensyms (shrunk-columns begin end)
  585. `(let ((,begin (copy-marker (org-table-begin)))
  586. (,end (copy-marker (org-table-end) t))
  587. (,shrunk-columns (org-table--list-shrunk-columns)))
  588. (org-with-point-at ,begin (org-table-expand ,begin ,end))
  589. (unwind-protect
  590. (progn ,@body)
  591. (org-table--shrink-columns ,shrunk-columns ,begin ,end)
  592. (set-marker ,begin nil)
  593. (set-marker ,end nil)))))
  594. (defmacro org-table-with-shrunk-field (&rest body)
  595. "Save field shrunk state, execute BODY and restore state."
  596. (declare (debug (body)))
  597. (org-with-gensyms (end shrunk size)
  598. `(let* ((,shrunk (save-match-data (org-table--shrunk-field)))
  599. (,end (and ,shrunk (copy-marker (overlay-end ,shrunk) t)))
  600. (,size (and ,shrunk (- ,end (overlay-start ,shrunk)))))
  601. (when ,shrunk (delete-overlay ,shrunk))
  602. (unwind-protect (progn ,@body)
  603. (when ,shrunk (move-overlay ,shrunk (- ,end ,size) ,end))))))
  604. (defmacro org-table-save-field (&rest body)
  605. "Save current field; execute BODY; restore field.
  606. Field is restored even in case of abnormal exit."
  607. (declare (debug (body)))
  608. (org-with-gensyms (line column)
  609. `(let ((,line (copy-marker (line-beginning-position)))
  610. (,column (org-table-current-column)))
  611. (unwind-protect
  612. (progn ,@body)
  613. (goto-char ,line)
  614. (org-table-goto-column ,column)
  615. (set-marker ,line nil)))))
  616. ;;; Predicates
  617. (defun org-at-TBLFM-p (&optional pos)
  618. "Non-nil when point (or POS) is in #+TBLFM line."
  619. (save-excursion
  620. (goto-char (or pos (point)))
  621. (beginning-of-line)
  622. (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
  623. (eq (org-element-type (org-element-at-point)) 'table))))
  624. (defun org-at-table-p (&optional table-type)
  625. "Non-nil if the cursor is inside an Org table.
  626. If TABLE-TYPE is non-nil, also check for table.el-type tables."
  627. (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
  628. (or (not (derived-mode-p 'org-mode))
  629. (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
  630. (and e (or table-type
  631. (eq 'org (org-element-property :type e))))))))
  632. (defun org-at-table.el-p ()
  633. "Non-nil when point is at a table.el table."
  634. (and (org-match-line "[ \t]*[|+]")
  635. (let ((element (org-element-at-point)))
  636. (and (eq (org-element-type element) 'table)
  637. (eq (org-element-property :type element) 'table.el)))))
  638. (defun org-at-table-hline-p ()
  639. "Non-nil when point is inside a hline in a table.
  640. Assume point is already in a table."
  641. (org-match-line org-table-hline-regexp))
  642. (defun org-table-check-inside-data-field (&optional noerror assume-table)
  643. "Non-nil when point is inside a table data field.
  644. Raise an error otherwise, unless NOERROR is non-nil. In that
  645. case, return nil if point is not inside a data field. When
  646. optional argument ASSUME-TABLE is non-nil, assume point is within
  647. a table."
  648. (cond ((and (or assume-table (org-at-table-p))
  649. (not (save-excursion (skip-chars-backward " \t") (bolp)))
  650. (not (org-at-table-hline-p))
  651. (not (looking-at-p "[ \t]*$"))))
  652. (noerror nil)
  653. (t (user-error "Not in table data field"))))
  654. ;;; Create, Import, and Convert Tables
  655. ;;;###autoload
  656. (defun org-table-create-with-table.el ()
  657. "Use the table.el package to insert a new table.
  658. If there is already a table at point, convert between Org tables
  659. and table.el tables."
  660. (interactive)
  661. (require 'table)
  662. (cond
  663. ((and (org-at-table.el-p)
  664. (y-or-n-p "Convert table to Org table? "))
  665. (org-table-convert))
  666. ((and (org-at-table-p)
  667. (y-or-n-p "Convert table to table.el table? "))
  668. (org-table-align)
  669. (org-table-convert))
  670. (t (call-interactively 'table-insert))))
  671. ;;;###autoload
  672. (defun org-table-create-or-convert-from-region (arg)
  673. "Convert region to table, or create an empty table.
  674. If there is an active region, convert it to a table, using the function
  675. `org-table-convert-region'. See the documentation of that function
  676. to learn how the prefix argument is interpreted to determine the field
  677. separator.
  678. If there is no such region, create an empty table with `org-table-create'."
  679. (interactive "P")
  680. (if (org-region-active-p)
  681. (org-table-convert-region (region-beginning) (region-end) arg)
  682. (org-table-create arg)))
  683. ;;;###autoload
  684. (defun org-table-create (&optional size)
  685. "Query for a size and insert a table skeleton.
  686. SIZE is a string Columns x Rows like for example \"3x2\"."
  687. (interactive "P")
  688. (unless size
  689. (setq size (read-string
  690. (concat "Table size Columns x Rows [e.g. "
  691. org-table-default-size "]: ")
  692. "" nil org-table-default-size)))
  693. (let* ((pos (point))
  694. (indent (make-string (current-column) ?\ ))
  695. (split (org-split-string size " *x *"))
  696. (rows (string-to-number (nth 1 split)))
  697. (columns (string-to-number (car split)))
  698. (line (concat (apply 'concat indent "|" (make-list columns " |"))
  699. "\n")))
  700. (if (string-match "^[ \t]*$" (buffer-substring-no-properties
  701. (point-at-bol) (point)))
  702. (beginning-of-line 1)
  703. (newline))
  704. ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
  705. (dotimes (_ rows) (insert line))
  706. (goto-char pos)
  707. (when (> rows 1)
  708. ;; Insert a hline after the first row.
  709. (end-of-line 1)
  710. (insert "\n|-")
  711. (goto-char pos))
  712. (org-table-align)))
  713. ;;;###autoload
  714. (defun org-table-convert-region (beg0 end0 &optional separator)
  715. "Convert region to a table.
  716. The region goes from BEG0 to END0, but these borders will be moved
  717. slightly, to make sure a beginning of line in the first line is included.
  718. SEPARATOR specifies the field separator in the lines. It can have the
  719. following values:
  720. (4) Use the comma as a field separator
  721. (16) Use a TAB as field separator
  722. (64) Prompt for a regular expression as field separator
  723. integer When a number, use that many spaces, or a TAB, as field separator
  724. regexp When a regular expression, use it to match the separator
  725. nil When nil, the command tries to be smart and figure out the
  726. separator in the following way:
  727. - when each line contains a TAB, assume TAB-separated material
  728. - when each line contains a comma, assume CSV material
  729. - else, assume one or more SPACE characters as separator."
  730. (interactive "r\nP")
  731. (let* ((beg (min beg0 end0))
  732. (end (max beg0 end0))
  733. re)
  734. (when (> (count-lines beg end) org-table-convert-region-max-lines)
  735. (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
  736. org-table-convert-region-max-lines))
  737. (when (equal separator '(64))
  738. (setq separator (read-regexp "Regexp for field separator")))
  739. (goto-char beg)
  740. (beginning-of-line 1)
  741. (setq beg (point-marker))
  742. (goto-char end)
  743. (if (bolp) (backward-char 1) (end-of-line 1))
  744. (setq end (point-marker))
  745. ;; Get the right field separator
  746. (unless separator
  747. (goto-char beg)
  748. (setq separator
  749. (cond
  750. ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
  751. ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
  752. (t 1))))
  753. (goto-char beg)
  754. (if (equal separator '(4))
  755. (while (< (point) end)
  756. ;; parse the csv stuff
  757. (cond
  758. ((looking-at "^") (insert "| "))
  759. ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
  760. ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
  761. (replace-match "\\1")
  762. (if (looking-at "\"") (insert "\"")))
  763. ((looking-at "[^,\n]+") (goto-char (match-end 0)))
  764. ((looking-at "[ \t]*,") (replace-match " | "))
  765. (t (beginning-of-line 2))))
  766. (setq re (cond
  767. ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
  768. ((equal separator '(16)) "^\\|\t")
  769. ((integerp separator)
  770. (if (< separator 1)
  771. (user-error "Number of spaces in separator must be >= 1")
  772. (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
  773. ((stringp separator)
  774. (format "^ *\\|%s" separator))
  775. (t (error "This should not happen"))))
  776. (while (re-search-forward re end t)
  777. (replace-match "| " t t)))
  778. (goto-char beg)
  779. (org-table-align)))
  780. ;;;###autoload
  781. (defun org-table-import (file separator)
  782. "Import FILE as a table.
  783. The command tries to be smart and figure out the separator in the
  784. following way:
  785. - when each line contains a TAB, assume TAB-separated material;
  786. - when each line contains a comma, assume CSV material;
  787. - else, assume one or more SPACE characters as separator.
  788. When non-nil, SEPARATOR specifies the field separator in the
  789. lines. It can have the following values:
  790. - (4) Use the comma as a field separator.
  791. - (16) Use a TAB as field separator.
  792. - (64) Prompt for a regular expression as field separator.
  793. - integer When a number, use that many spaces, or a TAB, as field separator.
  794. - regexp When a regular expression, use it to match the separator."
  795. (interactive "f\nP")
  796. (when (and (called-interactively-p 'any)
  797. (not (string-match-p (rx "." (or "txt" "tsv" "csv") eos) file))
  798. (not (yes-or-no-p "The file's extension is not .txt, .tsv or .csv. Import? ")))
  799. (user-error "Cannot import such file"))
  800. (unless (bolp) (insert "\n"))
  801. (let ((beg (point))
  802. (pm (point-max)))
  803. (insert-file-contents file)
  804. (org-table-convert-region beg (+ (point) (- (point-max) pm)) separator)))
  805. (defun org-table-convert ()
  806. "Convert from Org table to table.el and back.
  807. Obviously, this only works within limits. When an Org table is converted
  808. to table.el, all horizontal separator lines get lost, because table.el uses
  809. these as cell boundaries and has no notion of horizontal lines. A table.el
  810. table can be converted to an Org table only if it does not do row or column
  811. spanning. Multiline cells will become multiple cells. Beware, Org mode
  812. does not test if the table can be successfully converted - it blindly
  813. applies a recipe that works for simple tables."
  814. (interactive)
  815. (require 'table)
  816. (if (org-at-table.el-p)
  817. ;; convert to Org table
  818. (let ((beg (copy-marker (org-table-begin t)))
  819. (end (copy-marker (org-table-end t))))
  820. (table-unrecognize-region beg end)
  821. (goto-char beg)
  822. (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
  823. (replace-match ""))
  824. (goto-char beg))
  825. (if (org-at-table-p)
  826. ;; convert to table.el table
  827. (let ((beg (copy-marker (org-table-begin)))
  828. (end (copy-marker (org-table-end))))
  829. ;; first, get rid of all horizontal lines
  830. (goto-char beg)
  831. (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
  832. (replace-match ""))
  833. ;; insert a hline before first
  834. (goto-char beg)
  835. (org-table-insert-hline 'above)
  836. (beginning-of-line -1)
  837. ;; insert a hline after each line
  838. (while (progn (beginning-of-line 3) (< (point) end))
  839. (org-table-insert-hline))
  840. (goto-char beg)
  841. (setq end (move-marker end (org-table-end)))
  842. ;; replace "+" at beginning and ending of hlines
  843. (while (re-search-forward "^\\([ \t]*\\)|-" end t)
  844. (replace-match "\\1+-"))
  845. (goto-char beg)
  846. (while (re-search-forward "-|[ \t]*$" end t)
  847. (replace-match "-+"))
  848. (goto-char beg)))))
  849. ;;; Navigation and Structure Editing
  850. ;;;###autoload
  851. (defun org-table-begin (&optional table-type)
  852. "Find the beginning of the table and return its position.
  853. With a non-nil optional argument TABLE-TYPE, return the beginning
  854. of a table.el-type table. This function assumes point is on
  855. a table."
  856. (cond (table-type
  857. (org-element-property :post-affiliated (org-element-at-point)))
  858. ((save-excursion
  859. (and (re-search-backward org-table-border-regexp nil t)
  860. (line-beginning-position 2))))
  861. (t (point-min))))
  862. ;;;###autoload
  863. (defun org-table-end (&optional table-type)
  864. "Find the end of the table and return its position.
  865. With a non-nil optional argument TABLE-TYPE, return the end of
  866. a table.el-type table. This function assumes point is on
  867. a table."
  868. (save-excursion
  869. (cond (table-type
  870. (goto-char (org-element-property :end (org-element-at-point)))
  871. (skip-chars-backward " \t\n")
  872. (line-beginning-position 2))
  873. ((re-search-forward org-table-border-regexp nil t)
  874. (match-beginning 0))
  875. ;; When the line right after the table is the last line in
  876. ;; the buffer with trailing spaces but no final newline
  877. ;; character, be sure to catch the correct ending at its
  878. ;; beginning. In any other case, ending is expected to be
  879. ;; at point max.
  880. (t (goto-char (point-max))
  881. (skip-chars-backward " \t")
  882. (if (bolp) (point) (line-end-position))))))
  883. ;;;###autoload
  884. (defun org-table-next-field ()
  885. "Go to the next field in the current table, creating new lines as needed.
  886. Before doing so, re-align the table if necessary."
  887. (interactive)
  888. (org-table-maybe-eval-formula)
  889. (org-table-maybe-recalculate-line)
  890. (when (and org-table-automatic-realign
  891. org-table-may-need-update)
  892. (org-table-align))
  893. (let ((end (org-table-end)))
  894. (if (org-at-table-hline-p)
  895. (end-of-line 1))
  896. (condition-case nil
  897. (progn
  898. (re-search-forward "|" end)
  899. (if (looking-at "[ \t]*$")
  900. (re-search-forward "|" end))
  901. (if (and (looking-at "-")
  902. org-table-tab-jumps-over-hlines
  903. (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
  904. (goto-char (match-beginning 1)))
  905. (if (looking-at "-")
  906. (progn
  907. (beginning-of-line 0)
  908. (org-table-insert-row 'below))
  909. (if (looking-at " ") (forward-char 1))))
  910. (error
  911. (org-table-insert-row 'below)))))
  912. ;;;###autoload
  913. (defun org-table-previous-field ()
  914. "Go to the previous field in the table.
  915. Before doing so, re-align the table if necessary."
  916. (interactive)
  917. (org-table-justify-field-maybe)
  918. (org-table-maybe-recalculate-line)
  919. (when (and org-table-automatic-realign
  920. org-table-may-need-update)
  921. (org-table-align))
  922. (when (org-at-table-hline-p)
  923. (end-of-line))
  924. (let ((start (org-table-begin))
  925. (origin (point)))
  926. (condition-case nil
  927. (progn
  928. (search-backward "|" start nil 2)
  929. (while (looking-at-p "|\\(?:-\\|[ \t]*$\\)")
  930. (search-backward "|" start)))
  931. (error
  932. (goto-char origin)
  933. (user-error "Cannot move to previous table field"))))
  934. (when (looking-at "| ?")
  935. (goto-char (match-end 0))))
  936. (defun org-table-beginning-of-field (&optional n)
  937. "Move to the beginning of the current table field.
  938. If already at or before the beginning, move to the beginning of the
  939. previous field.
  940. With numeric argument N, move N-1 fields backward first."
  941. (interactive "p")
  942. (let ((pos (point)))
  943. (while (> n 1)
  944. (setq n (1- n))
  945. (org-table-previous-field))
  946. (if (not (re-search-backward "|" (point-at-bol 0) t))
  947. (user-error "No more table fields before the current")
  948. (goto-char (match-end 0))
  949. (and (looking-at " ") (forward-char 1)))
  950. (when (>= (point) pos) (org-table-beginning-of-field 2))))
  951. (defun org-table-end-of-field (&optional n)
  952. "Move to the end of the current table field.
  953. If already at or after the end, move to the end of the next table field.
  954. With numeric argument N, move N-1 fields forward first."
  955. (interactive "p")
  956. (let ((pos (point)))
  957. (while (> n 1)
  958. (setq n (1- n))
  959. (org-table-next-field))
  960. (when (re-search-forward "|" (point-at-eol 1) t)
  961. (backward-char 1)
  962. (skip-chars-backward " ")
  963. (when (and (equal (char-before (point)) ?|) (equal (char-after (point)) ?\s))
  964. (forward-char 1)))
  965. (when (<= (point) pos) (org-table-end-of-field 2))))
  966. ;;;###autoload
  967. (defun org-table-next-row ()
  968. "Go to the next row (same column) in the current table.
  969. Before doing so, re-align the table if necessary."
  970. (interactive)
  971. (org-table-maybe-eval-formula)
  972. (org-table-maybe-recalculate-line)
  973. (if (and org-table-automatic-realign
  974. org-table-may-need-update)
  975. (org-table-align))
  976. (let ((col (org-table-current-column)))
  977. (beginning-of-line 2)
  978. (unless (bolp) (insert "\n")) ;missing newline at eob
  979. (when (or (not (org-at-table-p))
  980. (org-at-table-hline-p))
  981. (beginning-of-line 0)
  982. (org-table-insert-row 'below))
  983. (org-table-goto-column col)
  984. (skip-chars-backward "^|\n\r")
  985. (when (looking-at " ") (forward-char))))
  986. (defun org-table-get (line column)
  987. "Get the field in table line LINE, column COLUMN.
  988. If LINE is larger than the number of data lines in the table, the function
  989. returns nil. However, if COLUMN is too large, we will simply return an
  990. empty string.
  991. If LINE is nil, use the current line.
  992. If COLUMN is nil, use the current column."
  993. (setq column (or column (org-table-current-column)))
  994. (save-excursion
  995. (and (or (not line) (org-table-goto-line line))
  996. (org-trim (org-table-get-field column)))))
  997. (defun org-table-put (line column value &optional align)
  998. "Put VALUE into line LINE, column COLUMN.
  999. When ALIGN is set, also realign the table."
  1000. (setq column (or column (org-table-current-column)))
  1001. (prog1 (save-excursion
  1002. (and (or (not line) (org-table-goto-line line))
  1003. (progn (org-table-goto-column column nil 'force) t)
  1004. (org-table-get-field column value)))
  1005. (and align (org-table-align))))
  1006. (defun org-table-current-line ()
  1007. "Return the index of the current data line."
  1008. (let ((pos (point)) (end (org-table-end)) (cnt 0))
  1009. (save-excursion
  1010. (goto-char (org-table-begin))
  1011. (while (and (re-search-forward org-table-dataline-regexp end t)
  1012. (setq cnt (1+ cnt))
  1013. (< (point-at-eol) pos))))
  1014. cnt))
  1015. (defun org-table-current-column ()
  1016. "Return current column number."
  1017. (interactive)
  1018. (save-excursion
  1019. (let ((pos (point)))
  1020. (beginning-of-line)
  1021. (if (not (search-forward "|" pos t)) 0
  1022. (let ((column 1)
  1023. (separator (if (org-at-table-hline-p) "[+|]" "|")))
  1024. (while (re-search-forward separator pos t) (cl-incf column))
  1025. column)))))
  1026. (defun org-table-current-dline ()
  1027. "Find out what table data line we are in.
  1028. Only data lines count for this."
  1029. (save-excursion
  1030. (let ((c 0)
  1031. (pos (line-beginning-position)))
  1032. (goto-char (org-table-begin))
  1033. (while (<= (point) pos)
  1034. (when (looking-at org-table-dataline-regexp) (cl-incf c))
  1035. (forward-line))
  1036. c)))
  1037. (defun org-table-goto-line (N)
  1038. "Go to the Nth data line in the current table.
  1039. Return t when the line exists, nil if it does not exist."
  1040. (goto-char (org-table-begin))
  1041. (let ((end (org-table-end)) (cnt 0))
  1042. (while (and (re-search-forward org-table-dataline-regexp end t)
  1043. (< (setq cnt (1+ cnt)) N)))
  1044. (= cnt N)))
  1045. ;;;###autoload
  1046. (defun org-table-blank-field ()
  1047. "Blank the current table field or active region."
  1048. (interactive)
  1049. (org-table-check-inside-data-field)
  1050. (if (and (called-interactively-p 'any) (org-region-active-p))
  1051. (let (org-table-clip)
  1052. (org-table-cut-region (region-beginning) (region-end)))
  1053. (skip-chars-backward "^|")
  1054. (backward-char 1)
  1055. (if (looking-at "|[^|\n]+")
  1056. (let* ((pos (match-beginning 0))
  1057. (match (match-string 0))
  1058. (len (org-string-width match)))
  1059. (replace-match (concat "|" (make-string (1- len) ?\ )))
  1060. (goto-char (+ 2 pos))
  1061. (substring match 1)))))
  1062. (defun org-table-get-field (&optional n replace)
  1063. "Return the value of the field in column N of current row.
  1064. N defaults to current column. If REPLACE is a string, replace
  1065. field with this value. The return value is always the old
  1066. value."
  1067. (when n (org-table-goto-column n))
  1068. (skip-chars-backward "^|\n")
  1069. (if (or (bolp) (looking-at-p "[ \t]*$"))
  1070. ;; Before first column or after last one.
  1071. ""
  1072. (looking-at "[^|\r\n]*")
  1073. (let* ((pos (match-beginning 0))
  1074. (val (buffer-substring pos (match-end 0))))
  1075. (when replace
  1076. (org-table-with-shrunk-field
  1077. (replace-match (if (equal replace "") " " replace) t t)))
  1078. (goto-char (min (line-end-position) (1+ pos)))
  1079. val)))
  1080. ;;;###autoload
  1081. (defun org-table-field-info (_arg)
  1082. "Show info about the current field, and highlight any reference at point."
  1083. (interactive "P")
  1084. (unless (org-at-table-p) (user-error "Not at a table"))
  1085. (org-table-analyze)
  1086. (save-excursion
  1087. (let* ((pos (point))
  1088. (col (org-table-current-column))
  1089. (cname (car (rassoc (number-to-string col) org-table-column-names)))
  1090. (name (car (rassoc (list (count-lines org-table-current-begin-pos
  1091. (line-beginning-position))
  1092. col)
  1093. org-table-named-field-locations)))
  1094. (eql (org-table-expand-lhs-ranges
  1095. (mapcar
  1096. (lambda (e)
  1097. (cons (org-table-formula-handle-first/last-rc (car e))
  1098. (cdr e)))
  1099. (org-table-get-stored-formulas))))
  1100. (dline (org-table-current-dline))
  1101. (ref (format "@%d$%d" dline col))
  1102. (ref1 (org-table-convert-refs-to-an ref))
  1103. ;; Prioritize field formulas over column formulas.
  1104. (fequation (or (assoc name eql) (assoc ref eql)))
  1105. (cequation (assoc (format "$%d" col) eql))
  1106. (eqn (or fequation cequation)))
  1107. (let ((p (and eqn (get-text-property 0 :orig-eqn (car eqn)))))
  1108. (when p (setq eqn p)))
  1109. (goto-char pos)
  1110. (ignore-errors (org-table-show-reference 'local))
  1111. (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
  1112. dline col
  1113. (if cname (concat " or $" cname) "")
  1114. dline col ref1
  1115. (if name (concat " or $" name) "")
  1116. ;; FIXME: formula info not correct if special table line
  1117. (if eqn
  1118. (concat ", formula: "
  1119. (org-table-formula-to-user
  1120. (concat
  1121. (if (or (string-prefix-p "$" (car eqn))
  1122. (string-prefix-p "@" (car eqn)))
  1123. ""
  1124. "$")
  1125. (car eqn) "=" (cdr eqn))))
  1126. "")))))
  1127. (defun org-table-goto-field (ref &optional create-column-p)
  1128. "Move point to a specific field in the current table.
  1129. REF is either the name of a field its absolute reference, as
  1130. a string. No column is created unless CREATE-COLUMN-P is
  1131. non-nil. If it is a function, it is called with the column
  1132. number as its argument as is used as a predicate to know if the
  1133. column can be created.
  1134. This function assumes the table is already analyzed (i.e., using
  1135. `org-table-analyze')."
  1136. (let* ((coordinates
  1137. (cond
  1138. ((cdr (assoc ref org-table-named-field-locations)))
  1139. ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
  1140. (list (condition-case nil
  1141. (aref org-table-dlines
  1142. (string-to-number (match-string 1 ref)))
  1143. (error (user-error "Invalid row number in %s" ref)))
  1144. (string-to-number (match-string 2 ref))))
  1145. (t (user-error "Unknown field: %s" ref))))
  1146. (line (car coordinates))
  1147. (column (nth 1 coordinates))
  1148. (create-new-column (if (functionp create-column-p)
  1149. (funcall create-column-p column)
  1150. create-column-p)))
  1151. (when coordinates
  1152. (goto-char org-table-current-begin-pos)
  1153. (forward-line line)
  1154. (org-table-goto-column column nil create-new-column))))
  1155. ;;;###autoload
  1156. (defun org-table-goto-column (n &optional on-delim force)
  1157. "Move the cursor to the Nth column in the current table line.
  1158. With optional argument ON-DELIM, stop with point before the left delimiter
  1159. of the field.
  1160. If there are less than N fields, just go to after the last delimiter.
  1161. However, when FORCE is non-nil, create new columns if necessary."
  1162. (interactive "p")
  1163. (beginning-of-line 1)
  1164. (when (> n 0)
  1165. (while (and (> (setq n (1- n)) -1)
  1166. (or (search-forward "|" (point-at-eol) t)
  1167. (and force
  1168. (progn (end-of-line 1)
  1169. (skip-chars-backward "^|")
  1170. (insert " | ")
  1171. t)))))
  1172. (when (and force (not (looking-at ".*|")))
  1173. (save-excursion (end-of-line 1) (insert " | ")))
  1174. (if on-delim
  1175. (backward-char 1)
  1176. (if (looking-at " ") (forward-char 1)))))
  1177. ;;;###autoload
  1178. (defun org-table-insert-column ()
  1179. "Insert a new column into the table."
  1180. (interactive)
  1181. (unless (org-at-table-p) (user-error "Not at a table"))
  1182. (org-table-find-dataline)
  1183. (let ((col (max 1 (org-table-current-column)))
  1184. (beg (org-table-begin))
  1185. (end (copy-marker (org-table-end)))
  1186. (shrunk-columns (org-table--list-shrunk-columns)))
  1187. (org-table-expand beg end)
  1188. (save-excursion
  1189. (goto-char beg)
  1190. (while (< (point) end)
  1191. (unless (org-at-table-hline-p)
  1192. (org-table-goto-column col t)
  1193. (insert "|"))
  1194. (forward-line)))
  1195. (org-table-goto-column col)
  1196. (org-table-align)
  1197. ;; Shift appropriately stored shrunk column numbers, then hide the
  1198. ;; columns again.
  1199. (org-table--shrink-columns (mapcar (lambda (c) (if (< c col) c (1+ c)))
  1200. shrunk-columns)
  1201. beg end)
  1202. (set-marker end nil)
  1203. ;; Fix TBLFM formulas, if desirable.
  1204. (when (or (not org-table-fix-formulas-confirm)
  1205. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1206. (org-table-fix-formulas "$" nil (1- col) 1))))
  1207. (defun org-table-find-dataline ()
  1208. "Find a data line in the current table, which is needed for column commands.
  1209. This function assumes point is in a table. Raise an error when
  1210. there is no data row below."
  1211. (or (not (org-at-table-hline-p))
  1212. (let ((col (current-column))
  1213. (end (org-table-end)))
  1214. (forward-line)
  1215. (while (and (< (point) end) (org-at-table-hline-p))
  1216. (forward-line))
  1217. (when (>= (point) end)
  1218. (user-error "Cannot find data row for column operation"))
  1219. (org-move-to-column col)
  1220. t)))
  1221. (defun org-table-line-to-dline (line &optional above)
  1222. "Turn a buffer line number into a data line number.
  1223. If there is no data line in this line, return nil.
  1224. If there is no matching dline (most likely the reference was
  1225. a hline), the first dline below it is used. When ABOVE is
  1226. non-nil, the one above is used."
  1227. (let ((min 1)
  1228. (max (1- (length org-table-dlines))))
  1229. (cond ((or (> (aref org-table-dlines min) line)
  1230. (< (aref org-table-dlines max) line))
  1231. nil)
  1232. ((= line (aref org-table-dlines max)) max)
  1233. (t (catch 'exit
  1234. (while (> (- max min) 1)
  1235. (let* ((mean (/ (+ max min) 2))
  1236. (v (aref org-table-dlines mean)))
  1237. (cond ((= v line) (throw 'exit mean))
  1238. ((> v line) (setq max mean))
  1239. (t (setq min mean)))))
  1240. (cond ((= line (aref org-table-dlines max)) max)
  1241. ((= line (aref org-table-dlines min)) min)
  1242. (above min)
  1243. (t max)))))))
  1244. (defun org-table--swap-cells (row1 col1 row2 col2)
  1245. "Swap two cells indicated by the coordinates provided.
  1246. ROW1, COL1, ROW2, COL2 are integers indicating the row/column
  1247. position of the two cells that will be swapped in the table."
  1248. (let ((content1 (org-table-get row1 col1))
  1249. (content2 (org-table-get row2 col2)))
  1250. (org-table-put row1 col1 content2)
  1251. (org-table-put row2 col2 content1)))
  1252. (defun org-table--move-cell (direction)
  1253. "Move the current cell in a cardinal direction.
  1254. DIRECTION is a symbol among `up', `down', `left', and `right'.
  1255. The contents the current cell are swapped with cell in the
  1256. indicated direction. Raise an error if the move cannot be done."
  1257. (let ((row-shift (pcase direction (`up -1) (`down 1) (_ 0)))
  1258. (column-shift (pcase direction (`left -1) (`right 1) (_ 0))))
  1259. (when (and (= 0 row-shift) (= 0 column-shift))
  1260. (error "Invalid direction: %S" direction))
  1261. ;; Initialize `org-table-current-ncol' and `org-table-dlines'.
  1262. (org-table-analyze)
  1263. (let* ((row (org-table-current-line))
  1264. (column (org-table-current-column))
  1265. (target-row (+ row row-shift))
  1266. (target-column (+ column column-shift))
  1267. (org-table-current-nrow (1- (length org-table-dlines))))
  1268. (when (or (< target-column 1)
  1269. (< target-row 1)
  1270. (> target-column org-table-current-ncol)
  1271. (> target-row org-table-current-nrow))
  1272. (user-error "Cannot move cell further"))
  1273. (org-table--swap-cells row column target-row target-column)
  1274. (org-table-goto-line target-row)
  1275. (org-table-goto-column target-column))))
  1276. ;;;###autoload
  1277. (defun org-table-move-cell-up ()
  1278. "Move a single cell up in a table.
  1279. Swap with anything in target cell."
  1280. (interactive)
  1281. (unless (org-table-check-inside-data-field)
  1282. (error "No table at point"))
  1283. (org-table--move-cell 'up)
  1284. (org-table-align))
  1285. ;;;###autoload
  1286. (defun org-table-move-cell-down ()
  1287. "Move a single cell down in a table.
  1288. Swap with anything in target cell."
  1289. (interactive)
  1290. (unless (org-table-check-inside-data-field)
  1291. (error "No table at point"))
  1292. (org-table--move-cell 'down)
  1293. (org-table-align))
  1294. ;;;###autoload
  1295. (defun org-table-move-cell-left ()
  1296. "Move a single cell left in a table.
  1297. Swap with anything in target cell."
  1298. (interactive)
  1299. (unless (org-table-check-inside-data-field)
  1300. (error "No table at point"))
  1301. (org-table--move-cell 'left)
  1302. (org-table-align))
  1303. ;;;###autoload
  1304. (defun org-table-move-cell-right ()
  1305. "Move a single cell right in a table.
  1306. Swap with anything in target cell."
  1307. (interactive)
  1308. (unless (org-table-check-inside-data-field)
  1309. (error "No table at point"))
  1310. (org-table--move-cell 'right)
  1311. (org-table-align))
  1312. ;;;###autoload
  1313. (defun org-table-delete-column ()
  1314. "Delete a column from the table."
  1315. (interactive)
  1316. (unless (org-at-table-p) (user-error "Not at a table"))
  1317. (org-table-find-dataline)
  1318. (when (save-excursion (skip-chars-forward " \t") (eolp))
  1319. (search-backward "|")) ;snap into last column
  1320. (org-table-check-inside-data-field nil t)
  1321. (let* ((col (org-table-current-column))
  1322. (beg (org-table-begin))
  1323. (end (copy-marker (org-table-end)))
  1324. (shrunk-columns (remq col (org-table--list-shrunk-columns))))
  1325. (org-table-expand beg end)
  1326. (org-table-save-field
  1327. (goto-char beg)
  1328. (while (< (point) end)
  1329. (if (org-at-table-hline-p)
  1330. nil
  1331. (org-table-goto-column col t)
  1332. (and (looking-at "|[^|\n]+|")
  1333. (replace-match "|")))
  1334. (forward-line)))
  1335. (org-table-align)
  1336. ;; Shift appropriately stored shrunk column numbers, then hide the
  1337. ;; columns again.
  1338. (org-table--shrink-columns (mapcar (lambda (c) (if (< c col) c (1- c)))
  1339. shrunk-columns)
  1340. beg end)
  1341. (set-marker end nil)
  1342. ;; Fix TBLFM formulas, if desirable.
  1343. (when (or (not org-table-fix-formulas-confirm)
  1344. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1345. (org-table-fix-formulas
  1346. "$" (list (cons (number-to-string col) "INVALID")) col -1 col))))
  1347. ;;;###autoload
  1348. (defun org-table-move-column-right ()
  1349. "Move column to the right."
  1350. (interactive)
  1351. (org-table-move-column nil))
  1352. ;;;###autoload
  1353. (defun org-table-move-column-left ()
  1354. "Move column to the left."
  1355. (interactive)
  1356. (org-table-move-column 'left))
  1357. ;;;###autoload
  1358. (defun org-table-move-column (&optional left)
  1359. "Move the current column to the right. With arg LEFT, move to the left."
  1360. (interactive "P")
  1361. (unless (org-at-table-p) (user-error "Not at a table"))
  1362. (org-table-find-dataline)
  1363. (org-table-check-inside-data-field nil t)
  1364. (let* ((col (org-table-current-column))
  1365. (col1 (if left (1- col) col))
  1366. (colpos (if left (1- col) (1+ col)))
  1367. (beg (org-table-begin))
  1368. (end (copy-marker (org-table-end))))
  1369. (when (and left (= col 1))
  1370. (user-error "Cannot move column further left"))
  1371. (when (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
  1372. (user-error "Cannot move column further right"))
  1373. (let ((shrunk-columns (org-table--list-shrunk-columns)))
  1374. (org-table-expand beg end)
  1375. (org-table-save-field
  1376. (goto-char beg)
  1377. (while (< (point) end)
  1378. (unless (org-at-table-hline-p)
  1379. (org-table-goto-column col1 t)
  1380. (when (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
  1381. (transpose-regions
  1382. (match-beginning 1) (match-end 1)
  1383. (match-beginning 2) (match-end 2))))
  1384. (forward-line)))
  1385. (org-table-goto-column colpos)
  1386. (org-table-align)
  1387. ;; Shift appropriately stored shrunk column numbers, then shrink
  1388. ;; the columns again.
  1389. (org-table--shrink-columns
  1390. (mapcar (lambda (c)
  1391. (cond ((and (= col c) left) (1- c))
  1392. ((= col c) (1+ c))
  1393. ((and (= col (1+ c)) left) (1+ c))
  1394. ((and (= col (1- c)) (not left) (1- c)))
  1395. (t c)))
  1396. shrunk-columns)
  1397. beg end)
  1398. (set-marker end nil)
  1399. ;; Fix TBLFM formulas, if desirable.
  1400. (when (or (not org-table-fix-formulas-confirm)
  1401. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1402. (org-table-fix-formulas
  1403. "$" (list (cons (number-to-string col) (number-to-string colpos))
  1404. (cons (number-to-string colpos) (number-to-string col))))))))
  1405. ;;;###autoload
  1406. (defun org-table-move-row-down ()
  1407. "Move table row down."
  1408. (interactive)
  1409. (org-table-move-row nil))
  1410. ;;;###autoload
  1411. (defun org-table-move-row-up ()
  1412. "Move table row up."
  1413. (interactive)
  1414. (org-table-move-row 'up))
  1415. ;;;###autoload
  1416. (defun org-table-move-row (&optional up)
  1417. "Move the current table line down. With arg UP, move it up."
  1418. (interactive "P")
  1419. (let* ((col (current-column))
  1420. (pos (point))
  1421. (hline1p (save-excursion (beginning-of-line 1)
  1422. (looking-at org-table-hline-regexp)))
  1423. (dline1 (org-table-current-dline))
  1424. (dline2 (+ dline1 (if up -1 1)))
  1425. (tonew (if up 0 2))
  1426. hline2p)
  1427. (when (and up (= (point-min) (line-beginning-position)))
  1428. (user-error "Cannot move row further"))
  1429. (beginning-of-line tonew)
  1430. (when (or (and (not up) (eobp)) (not (org-at-table-p)))
  1431. (goto-char pos)
  1432. (user-error "Cannot move row further"))
  1433. (org-table-with-shrunk-columns
  1434. (setq hline2p (looking-at org-table-hline-regexp))
  1435. (goto-char pos)
  1436. (let ((row (delete-and-extract-region (line-beginning-position)
  1437. (line-beginning-position 2))))
  1438. (beginning-of-line tonew)
  1439. (unless (bolp) (insert "\n")) ;at eob without a newline
  1440. (insert row)
  1441. (unless (bolp) (insert "\n")) ;missing final newline in ROW
  1442. (beginning-of-line 0)
  1443. (org-move-to-column col)
  1444. (unless (or hline1p hline2p
  1445. (not (or (not org-table-fix-formulas-confirm)
  1446. (funcall org-table-fix-formulas-confirm
  1447. "Fix formulas? "))))
  1448. (org-table-fix-formulas
  1449. "@" (list
  1450. (cons (number-to-string dline1) (number-to-string dline2))
  1451. (cons (number-to-string dline2) (number-to-string dline1)))))))))
  1452. ;;;###autoload
  1453. (defun org-table-insert-row (&optional arg)
  1454. "Insert a new row above the current line into the table.
  1455. With prefix ARG, insert below the current line."
  1456. (interactive "P")
  1457. (unless (org-at-table-p) (user-error "Not at a table"))
  1458. (org-table-with-shrunk-columns
  1459. (let* ((line (buffer-substring (line-beginning-position) (line-end-position)))
  1460. (new (org-table-clean-line line)))
  1461. ;; Fix the first field if necessary
  1462. (when (string-match "^[ \t]*| *[#*$] *|" line)
  1463. (setq new (replace-match (match-string 0 line) t t new)))
  1464. (beginning-of-line (if arg 2 1))
  1465. ;; Buffer may not end of a newline character, so ensure
  1466. ;; (beginning-of-line 2) moves point to a new line.
  1467. (unless (bolp) (insert "\n"))
  1468. (let (org-table-may-need-update) (insert-before-markers new "\n"))
  1469. (beginning-of-line 0)
  1470. (re-search-forward "| ?" (line-end-position) t)
  1471. (when (or org-table-may-need-update org-table-overlay-coordinates)
  1472. (org-table-align))
  1473. (when (or (not org-table-fix-formulas-confirm)
  1474. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1475. (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))))
  1476. ;;;###autoload
  1477. (defun org-table-insert-hline (&optional above)
  1478. "Insert a horizontal-line below the current line into the table.
  1479. With prefix ABOVE, insert above the current line."
  1480. (interactive "P")
  1481. (unless (org-at-table-p) (user-error "Not at a table"))
  1482. (when (eobp) (save-excursion (insert "\n")))
  1483. (unless (string-match-p "|[ \t]*$" (org-current-line-string))
  1484. (org-table-align))
  1485. (org-table-with-shrunk-columns
  1486. (let ((line (org-table-clean-line
  1487. (buffer-substring (point-at-bol) (point-at-eol))))
  1488. (col (current-column)))
  1489. (while (string-match "|\\( +\\)|" line)
  1490. (setq line (replace-match
  1491. (concat "+" (make-string (- (match-end 1) (match-beginning 1))
  1492. ?-) "|") t t line)))
  1493. (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
  1494. (beginning-of-line (if above 1 2))
  1495. (insert line "\n")
  1496. (beginning-of-line (if above 1 -1))
  1497. (org-move-to-column col)
  1498. (when org-table-overlay-coordinates (org-table-align)))))
  1499. ;;;###autoload
  1500. (defun org-table-hline-and-move (&optional same-column)
  1501. "Insert a hline and move to the row below that line."
  1502. (interactive "P")
  1503. (let ((col (org-table-current-column)))
  1504. (org-table-maybe-eval-formula)
  1505. (org-table-maybe-recalculate-line)
  1506. (org-table-insert-hline)
  1507. (end-of-line 2)
  1508. (if (looking-at "\n[ \t]*|-")
  1509. (progn (insert "\n|") (org-table-align))
  1510. (org-table-next-field))
  1511. (if same-column (org-table-goto-column col))))
  1512. (defun org-table-clean-line (s)
  1513. "Convert a table line S into a string with only \"|\" and space.
  1514. In particular, this does handle wide and invisible characters."
  1515. (if (string-match "^[ \t]*|-" s)
  1516. ;; It's a hline, just map the characters
  1517. (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
  1518. (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
  1519. (setq s (replace-match
  1520. (concat "|" (make-string (org-string-width (match-string 1 s))
  1521. ?\ ) "|")
  1522. t t s)))
  1523. s))
  1524. ;;;###autoload
  1525. (defun org-table-kill-row ()
  1526. "Delete the current row or horizontal line from the table."
  1527. (interactive)
  1528. (unless (org-at-table-p) (user-error "Not at a table"))
  1529. (let ((col (current-column))
  1530. (dline (and (not (org-match-line org-table-hline-regexp))
  1531. (org-table-current-dline))))
  1532. (org-table-with-shrunk-columns
  1533. (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
  1534. (if (not (org-at-table-p)) (beginning-of-line 0))
  1535. (org-move-to-column col)
  1536. (when (and dline
  1537. (or (not org-table-fix-formulas-confirm)
  1538. (funcall org-table-fix-formulas-confirm "Fix formulas? ")))
  1539. (org-table-fix-formulas
  1540. "@" (list (cons (number-to-string dline) "INVALID")) dline -1 dline)))))
  1541. ;;;###autoload
  1542. (defun org-table-cut-region (beg end)
  1543. "Copy region in table to the clipboard and blank all relevant fields.
  1544. If there is no active region, use just the field at point."
  1545. (interactive (list
  1546. (if (org-region-active-p) (region-beginning) (point))
  1547. (if (org-region-active-p) (region-end) (point))))
  1548. (org-table-copy-region beg end 'cut))
  1549. (defun org-table--increment-field (field previous)
  1550. "Increment string FIELD according to PREVIOUS field.
  1551. Increment FIELD only if it is a string representing a number, per
  1552. Emacs Lisp syntax, a timestamp, or is either prefixed or suffixed
  1553. with a number. In any other case, return FIELD as-is.
  1554. If PREVIOUS has the same structure as FIELD, e.g.,
  1555. a number-prefixed string with the same pattern, the increment
  1556. step is the difference between numbers (or timestamps, measured
  1557. in days) in PREVIOUS and FIELD. Otherwise, it uses
  1558. `org-table-copy-increment', if the variable contains a number, or
  1559. default to 1.
  1560. The function assumes `org-table-copy-increment' is non-nil."
  1561. (let* ((default-step (if (numberp org-table-copy-increment)
  1562. org-table-copy-increment
  1563. 1))
  1564. (number-regexp ;Lisp read syntax for numbers
  1565. (rx (and string-start
  1566. (opt (any "+-"))
  1567. (or (and (one-or-more digit) (opt "."))
  1568. (and (zero-or-more digit) "." (one-or-more digit)))
  1569. (opt (any "eE") (opt (opt (any "+-")) (one-or-more digit)))
  1570. string-end)))
  1571. (number-prefix-regexp (rx (and string-start (one-or-more digit))))
  1572. (number-suffix-regexp (rx (and (one-or-more digit) string-end)))
  1573. (analyze
  1574. (lambda (field)
  1575. ;; Analyze string FIELD and return information related to
  1576. ;; increment or nil. When non-nil, return value has the
  1577. ;; following scheme: (TYPE VALUE PATTERN) where
  1578. ;; - TYPE is a symbol among `number', `prefix', `suffix'
  1579. ;; and `timestamp',
  1580. ;; - VALUE is a timestamp if TYPE is `timestamp', or
  1581. ;; a number otherwise,
  1582. ;; - PATTERN is the field without its prefix, or suffix if
  1583. ;; TYPE is either `prefix' or `suffix' , or nil
  1584. ;; otherwise.
  1585. (cond ((not (org-string-nw-p field)) nil)
  1586. ((string-match-p number-regexp field)
  1587. (list 'number
  1588. (string-to-number field)
  1589. nil))
  1590. ((string-match number-prefix-regexp field)
  1591. (list 'prefix
  1592. (string-to-number (match-string 0 field))
  1593. (substring field (match-end 0))))
  1594. ((string-match number-suffix-regexp field)
  1595. (list 'suffix
  1596. (string-to-number (match-string 0 field))
  1597. (substring field 0 (match-beginning 0))))
  1598. ((string-match-p org-ts-regexp3 field)
  1599. (list 'timestamp field nil))
  1600. (t nil))))
  1601. (next-number-string
  1602. (lambda (n1 &optional n2)
  1603. ;; Increment number N1 and return it as a string. If N2
  1604. ;; is also a number, deduce increment step from the
  1605. ;; difference between N1 and N2. Otherwise, increment
  1606. ;; step is `default-step'.
  1607. (number-to-string (if n2 (+ n1 (- n1 n2)) (+ n1 default-step)))))
  1608. (shift-timestamp
  1609. (lambda (t1 &optional t2)
  1610. ;; Increment timestamp T1 and return it. If T2 is also
  1611. ;; a timestamp, deduce increment step from the difference,
  1612. ;; in days, between T1 and T2. Otherwise, increment by
  1613. ;; `default-step' days.
  1614. (with-temp-buffer
  1615. (insert t1)
  1616. (org-timestamp-up-day (if (not t2) default-step
  1617. (- (org-time-string-to-absolute t1)
  1618. (org-time-string-to-absolute t2))))
  1619. (buffer-string)))))
  1620. ;; Check if both PREVIOUS and FIELD have the same type. Also, if
  1621. ;; the case of prefixed or suffixed numbers, make sure their
  1622. ;; pattern, i.e., the part of the string without the prefix or the
  1623. ;; suffix, is the same.
  1624. (pcase (cons (funcall analyze field) (funcall analyze previous))
  1625. (`((number ,n1 ,_) . (number ,n2 ,_))
  1626. (funcall next-number-string n1 n2))
  1627. (`((number ,n ,_) . ,_)
  1628. (funcall next-number-string n))
  1629. (`((prefix ,n1 ,p1) . (prefix ,n2 ,p2))
  1630. (concat (funcall next-number-string n1 (and (equal p1 p2) n2)) p1))
  1631. (`((prefix ,n ,p) . ,_)
  1632. (concat (funcall next-number-string n) p))
  1633. (`((suffix ,n1 ,p1) . (suffix ,n2 ,p2))
  1634. (concat p1 (funcall next-number-string n1 (and (equal p1 p2) n2))))
  1635. (`((suffix ,n ,p) . ,_)
  1636. (concat p (funcall next-number-string n)))
  1637. (`((timestamp ,t1 ,_) . (timestamp ,t2 ,_))
  1638. (funcall shift-timestamp t1 t2))
  1639. (`((timestamp ,t1 ,_) . ,_)
  1640. (funcall shift-timestamp t1))
  1641. (_ field))))
  1642. ;;;###autoload
  1643. (defun org-table-copy-down (n)
  1644. "Copy the value of the current field one row below.
  1645. If the field at the cursor is empty, copy the content of the
  1646. nearest non-empty field above. With argument N, use the Nth
  1647. non-empty field.
  1648. If the current field is not empty, it is copied down to the next
  1649. row, and the cursor is moved with it. Therefore, repeating this
  1650. command causes the column to be filled row-by-row.
  1651. If the variable `org-table-copy-increment' is non-nil and the
  1652. field is a number, a timestamp, or is either prefixed or suffixed
  1653. with a number, it will be incremented while copying. By default,
  1654. increment by the difference between the value in the current
  1655. field and the one in the field above, if any. To increment using
  1656. a fixed integer, set `org-table-copy-increment' to a number. In
  1657. the case of a timestamp, increment by days.
  1658. However, when N is 0, do not increment the field at all."
  1659. (interactive "p")
  1660. (org-table-check-inside-data-field)
  1661. (let* ((beg (org-table-begin))
  1662. (column (org-table-current-column))
  1663. (initial-field (save-excursion
  1664. (let ((f (org-string-nw-p (org-table-get-field))))
  1665. (and f (org-trim f)))))
  1666. field field-above next-field)
  1667. (save-excursion
  1668. ;; Get reference field.
  1669. (if initial-field (setq field initial-field)
  1670. (beginning-of-line)
  1671. (setq field
  1672. (catch :exit
  1673. (while (re-search-backward org-table-dataline-regexp beg t)
  1674. (let ((f (org-string-nw-p (org-table-get-field column))))
  1675. (cond ((and (> n 1) f) (cl-decf n))
  1676. (f (throw :exit (org-trim f)))
  1677. (t nil))
  1678. (beginning-of-line)))
  1679. (user-error "No non-empty field found"))))
  1680. ;; Check if increment is appropriate, and how it should be done.
  1681. (when (and org-table-copy-increment (/= n 0))
  1682. ;; If increment step is not explicit, get non-empty field just
  1683. ;; above the field being incremented to guess it.
  1684. (unless (numberp org-table-copy-increment)
  1685. (setq field-above
  1686. (let ((f (unless (= beg (line-beginning-position))
  1687. (forward-line -1)
  1688. (not (org-at-table-hline-p))
  1689. (org-table-get-field column))))
  1690. (and (org-string-nw-p f)
  1691. (org-trim f)))))
  1692. ;; Compute next field.
  1693. (setq next-field (org-table--increment-field field field-above))))
  1694. ;; Since initial field in not empty, we modify row below instead.
  1695. ;; Skip alignment since we do it at the end of the process anyway.
  1696. (when initial-field
  1697. (let ((org-table-may-need-update nil)) (org-table-next-row))
  1698. (org-table-blank-field))
  1699. ;; Insert the new field. NEW-FIELD may be nil if
  1700. ;; `org-table-increment' is nil, or N = 0. In that case, copy
  1701. ;; FIELD.
  1702. (insert (or next-field field))
  1703. (org-table-maybe-recalculate-line)
  1704. (org-table-align)))
  1705. ;;;###autoload
  1706. (defun org-table-copy-region (beg end &optional cut)
  1707. "Copy rectangular region in table to clipboard.
  1708. A special clipboard is used which can only be accessed with
  1709. `org-table-paste-rectangle'. Return the region copied, as a list
  1710. of lists of fields."
  1711. (interactive (list
  1712. (if (org-region-active-p) (region-beginning) (point))
  1713. (if (org-region-active-p) (region-end) (point))
  1714. current-prefix-arg))
  1715. (goto-char (min beg end))
  1716. (org-table-check-inside-data-field)
  1717. (let ((beg (line-beginning-position))
  1718. (c01 (org-table-current-column))
  1719. region)
  1720. (goto-char (max beg end))
  1721. (org-table-check-inside-data-field nil t)
  1722. (let* ((end (copy-marker (line-end-position)))
  1723. (c02 (org-table-current-column))
  1724. (column-start (min c01 c02))
  1725. (column-end (max c01 c02))
  1726. (column-number (1+ (- column-end column-start)))
  1727. (rpl (and cut " ")))
  1728. (goto-char beg)
  1729. (while (< (point) end)
  1730. (unless (org-at-table-hline-p)
  1731. ;; Collect every cell between COLUMN-START and COLUMN-END.
  1732. (let (cols)
  1733. (dotimes (c column-number)
  1734. (push (org-table-get-field (+ c column-start) rpl) cols))
  1735. (push (nreverse cols) region)))
  1736. (forward-line))
  1737. (set-marker end nil))
  1738. (when cut (org-table-align))
  1739. (when (called-interactively-p 'any)
  1740. (message (substitute-command-keys "Cells in the region copied, use \
  1741. \\[org-table-paste-rectangle] to paste them in a table.")))
  1742. (setq org-table-clip (nreverse region))))
  1743. ;;;###autoload
  1744. (defun org-table-paste-rectangle ()
  1745. "Paste a rectangular region into a table.
  1746. The upper right corner ends up in the current field. All involved fields
  1747. will be overwritten. If the rectangle does not fit into the present table,
  1748. the table is enlarged as needed. The process ignores horizontal separator
  1749. lines."
  1750. (interactive)
  1751. (unless (consp org-table-clip)
  1752. (user-error "First cut/copy a region to paste!"))
  1753. (org-table-check-inside-data-field)
  1754. (let* ((column (org-table-current-column))
  1755. (org-table-automatic-realign nil))
  1756. (org-table-save-field
  1757. (dolist (row org-table-clip)
  1758. (while (org-at-table-hline-p) (forward-line))
  1759. ;; If we left the table, create a new row.
  1760. (when (and (bolp) (not (looking-at "[ \t]*|")))
  1761. (end-of-line 0)
  1762. (org-table-next-field))
  1763. (let ((c column))
  1764. (dolist (field row)
  1765. (org-table-goto-column c nil 'force)
  1766. (org-table-get-field nil field)
  1767. (cl-incf c)))
  1768. (forward-line)))
  1769. (org-table-align)))
  1770. ;;; Follow Field minor mode
  1771. (define-minor-mode org-table-follow-field-mode
  1772. "Minor mode to make the table field editor window follow the cursor.
  1773. When this mode is active, the field editor window will always show the
  1774. current field. The mode exits automatically when the cursor leaves the
  1775. table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
  1776. :lighter " TblFollow"
  1777. (if org-table-follow-field-mode
  1778. (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
  1779. 'append 'local)
  1780. (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
  1781. (let* ((buf (get-buffer "*Org Table Edit Field*"))
  1782. (win (and buf (get-buffer-window buf))))
  1783. (when win (delete-window win))
  1784. (when buf
  1785. (with-current-buffer buf
  1786. (move-marker org-field-marker nil))
  1787. (kill-buffer buf)))))
  1788. ;;;###autoload
  1789. (defun org-table-edit-field (arg)
  1790. "Edit table field in a different window.
  1791. This is mainly useful for fields that contain hidden parts.
  1792. When called with a `\\[universal-argument]' prefix, just make the full field
  1793. visible so that it can be edited in place.
  1794. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  1795. toggle `org-table-follow-field-mode'."
  1796. (interactive "P")
  1797. (unless (org-at-table-p) (user-error "Not at a table"))
  1798. (cond
  1799. ((equal arg '(16))
  1800. (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
  1801. (arg
  1802. (let ((b (save-excursion (skip-chars-backward "^|") (point)))
  1803. (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
  1804. (remove-text-properties b e '(invisible t intangible t))
  1805. (if font-lock-mode
  1806. (font-lock-fontify-block))))
  1807. (t
  1808. (let ((pos (point-marker))
  1809. (coord
  1810. (if (eq org-table-use-standard-references t)
  1811. (concat (org-number-to-letters (org-table-current-column))
  1812. (number-to-string (org-table-current-dline)))
  1813. (concat "@" (number-to-string (org-table-current-dline))
  1814. "$" (number-to-string (org-table-current-column)))))
  1815. (field (org-table-get-field))
  1816. (cw (current-window-configuration))
  1817. p)
  1818. (goto-char pos)
  1819. (org-switch-to-buffer-other-window "*Org Table Edit Field*")
  1820. (when (and (local-variable-p 'org-field-marker)
  1821. (markerp org-field-marker))
  1822. (move-marker org-field-marker nil))
  1823. (erase-buffer)
  1824. (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
  1825. (let ((org-inhibit-startup t)) (org-mode))
  1826. (auto-fill-mode -1)
  1827. (setq truncate-lines nil)
  1828. (setq word-wrap t)
  1829. (goto-char (setq p (point-max)))
  1830. (insert (org-trim field))
  1831. (remove-text-properties p (point-max) '(invisible t intangible t))
  1832. (goto-char p)
  1833. (setq-local org-finish-function 'org-table-finish-edit-field)
  1834. (setq-local org-window-configuration cw)
  1835. (setq-local org-field-marker pos)
  1836. (message "Edit and finish with C-c C-c")))))
  1837. (defun org-table-follow-fields-with-editor ()
  1838. (if (and org-table-exit-follow-field-mode-when-leaving-table
  1839. (not (org-at-table-p)))
  1840. ;; We have left the table, exit the follow mode
  1841. (org-table-follow-field-mode -1)
  1842. (when (org-table-check-inside-data-field 'noerror)
  1843. (let ((win (selected-window)))
  1844. (org-table-edit-field nil)
  1845. (org-fit-window-to-buffer)
  1846. (select-window win)))))
  1847. (defun org-table-finish-edit-field ()
  1848. "Finish editing a table data field.
  1849. Remove all newline characters, insert the result into the table, realign
  1850. the table and kill the editing buffer."
  1851. (let ((pos org-field-marker)
  1852. (cw org-window-configuration)
  1853. (cb (current-buffer))
  1854. text)
  1855. (goto-char (point-min))
  1856. (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
  1857. (while (re-search-forward "[ \t]*\n[ \t\n]*" nil t)
  1858. (replace-match " "))
  1859. (setq text (org-trim (buffer-string)))
  1860. (set-window-configuration cw)
  1861. (kill-buffer cb)
  1862. (select-window (get-buffer-window (marker-buffer pos)))
  1863. (goto-char pos)
  1864. (move-marker pos nil)
  1865. (org-table-check-inside-data-field)
  1866. (org-table-get-field nil text)
  1867. (org-table-align)
  1868. (message "New field value inserted")))
  1869. ;;; Formulas
  1870. (defun org-table-current-field-formula (&optional key noerror)
  1871. "Return the formula active for the current field.
  1872. Assumes that table is already analyzed. If KEY is given, return
  1873. the key to this formula. Otherwise return the formula preceded
  1874. with \"=\" or \":=\"."
  1875. (let* ((line (count-lines org-table-current-begin-pos
  1876. (line-beginning-position)))
  1877. (row (org-table-line-to-dline line)))
  1878. (cond
  1879. (row
  1880. (let* ((col (org-table-current-column))
  1881. (name (car (rassoc (list line col)
  1882. org-table-named-field-locations)))
  1883. (scol (format "$%d" col))
  1884. (ref (format "@%d$%d" (org-table-current-dline) col))
  1885. (stored-list (org-table-get-stored-formulas noerror))
  1886. (ass (or (assoc name stored-list)
  1887. (assoc ref stored-list)
  1888. (assoc scol stored-list))))
  1889. (cond (key (car ass))
  1890. (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
  1891. (cdr ass))))))
  1892. (noerror nil)
  1893. (t (error "No formula active for the current field")))))
  1894. (defun org-table-get-formula (&optional equation named)
  1895. "Read a formula from the minibuffer, offer stored formula as default.
  1896. When NAMED is non-nil, look for a named equation."
  1897. (let* ((stored-list (org-table-get-stored-formulas))
  1898. (name (car (rassoc (list (count-lines org-table-current-begin-pos
  1899. (line-beginning-position))
  1900. (org-table-current-column))
  1901. org-table-named-field-locations)))
  1902. (ref (format "@%d$%d"
  1903. (org-table-current-dline)
  1904. (org-table-current-column)))
  1905. (scol (cond
  1906. ((not named) (format "$%d" (org-table-current-column)))
  1907. (name)
  1908. (t ref)))
  1909. (name (or name ref))
  1910. (org-table-may-need-update nil)
  1911. (stored (cdr (assoc scol stored-list)))
  1912. (eq (cond
  1913. ((and stored equation (string-match-p "^ *=? *$" equation))
  1914. stored)
  1915. ((stringp equation) equation)
  1916. (t
  1917. (org-table-formula-from-user
  1918. (read-string
  1919. (org-table-formula-to-user
  1920. (format "%s formula %s=" (if named "Field" "Column") scol))
  1921. (if stored (org-table-formula-to-user stored) "")
  1922. 'org-table-formula-history)))))
  1923. mustsave)
  1924. (unless (org-string-nw-p eq)
  1925. ;; Remove formula.
  1926. (setq stored-list (delq (assoc scol stored-list) stored-list))
  1927. (org-table-store-formulas stored-list)
  1928. (user-error "Formula removed"))
  1929. (when (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  1930. (when (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  1931. (when (and name (not named))
  1932. ;; We set the column equation, delete the named one.
  1933. (setq stored-list (delq (assoc name stored-list) stored-list)
  1934. mustsave t))
  1935. (if stored
  1936. (setcdr (assoc scol stored-list) eq)
  1937. (setq stored-list (cons (cons scol eq) stored-list)))
  1938. (when (or mustsave (not (equal stored eq)))
  1939. (org-table-store-formulas stored-list))
  1940. eq))
  1941. (defun org-table-store-formulas (alist &optional location)
  1942. "Store the list of formulas below the current table.
  1943. If optional argument LOCATION is a buffer position, insert it at
  1944. LOCATION instead."
  1945. (save-excursion
  1946. (if location
  1947. (progn (goto-char location) (beginning-of-line))
  1948. (goto-char (org-table-end)))
  1949. (let ((case-fold-search t))
  1950. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
  1951. (progn
  1952. ;; Don't overwrite TBLFM, we might use text properties to
  1953. ;; store stuff.
  1954. (goto-char (match-beginning 3))
  1955. (delete-region (match-beginning 3) (match-end 0)))
  1956. (org-indent-line)
  1957. (insert "#+TBLFM:"))
  1958. (insert " "
  1959. (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
  1960. (sort alist #'org-table-formula-less-p)
  1961. "::")
  1962. "\n"))))
  1963. (defsubst org-table-formula-make-cmp-string (a)
  1964. (when (string-match "\\`\\$[<>]" a)
  1965. (let ((arrow (string-to-char (substring a 1))))
  1966. ;; Fake a high number to make sure this is sorted at the end.
  1967. (setq a (org-table-formula-handle-first/last-rc a))
  1968. (setq a (format "$%d" (+ 10000
  1969. (if (= arrow ?<) -1000 0)
  1970. (string-to-number (substring a 1)))))))
  1971. (when (string-match
  1972. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  1973. a)
  1974. (concat
  1975. (if (match-end 2)
  1976. (format "@%05d" (string-to-number (match-string 2 a))) "")
  1977. (if (match-end 4)
  1978. (format "$%05d" (string-to-number (match-string 4 a))) "")
  1979. (if (match-end 5)
  1980. (concat "@@" (match-string 5 a))))))
  1981. (defun org-table-formula-less-p (a b)
  1982. "Compare two formulas for sorting."
  1983. (let ((as (org-table-formula-make-cmp-string (car a)))
  1984. (bs (org-table-formula-make-cmp-string (car b))))
  1985. (and as bs (string< as bs))))
  1986. ;;;###autoload
  1987. (defun org-table-get-stored-formulas (&optional noerror location)
  1988. "Return an alist with the stored formulas directly after current table.
  1989. By default, only return active formulas, i.e., formulas located
  1990. on the first line after the table. However, if optional argument
  1991. LOCATION is a buffer position, consider the formulas there."
  1992. (save-excursion
  1993. (if location
  1994. (progn (goto-char location) (beginning-of-line))
  1995. (goto-char (org-table-end)))
  1996. (let ((case-fold-search t))
  1997. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
  1998. (let ((strings (org-split-string (match-string-no-properties 2)
  1999. " *:: *"))
  2000. eq-alist seen)
  2001. (dolist (string strings (nreverse eq-alist))
  2002. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
  2003. \[<>]+\\)\\) *= *\\(.*[^ \t]\\)"
  2004. string)
  2005. (let ((lhs
  2006. (let ((m (match-string 1 string)))
  2007. (cond
  2008. ((not (match-end 2)) m)
  2009. ;; Is it a column reference?
  2010. ((string-match-p "\\`\\$\\([0-9]+\\|[<>]+\\)\\'" m) m)
  2011. ;; Since named columns are not possible in
  2012. ;; LHS, assume this is a named field.
  2013. (t (match-string 2 string)))))
  2014. (rhs (match-string 3 string)))
  2015. (push (cons lhs rhs) eq-alist)
  2016. (cond
  2017. ((not (member lhs seen)) (push lhs seen))
  2018. (noerror
  2019. (message
  2020. "Double definition `%s=' in TBLFM line, please fix by hand"
  2021. lhs)
  2022. (ding)
  2023. (sit-for 2))
  2024. (t
  2025. (user-error
  2026. "Double definition `%s=' in TBLFM line, please fix by hand"
  2027. lhs)))))))))))
  2028. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2029. "Modify the equations after the table structure has been edited.
  2030. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2031. For all numbers larger than LIMIT, shift them by DELTA."
  2032. (save-excursion
  2033. (goto-char (org-table-end))
  2034. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2035. (let ((re (concat key "\\([0-9]+\\)"))
  2036. (re2
  2037. (when remove
  2038. (if (equal key "$")
  2039. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2040. (regexp-quote key) remove)
  2041. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2042. s n a)
  2043. (when remove
  2044. (while (re-search-forward re2 (point-at-eol) t)
  2045. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2046. (if (equal (char-before (match-beginning 0)) ?.)
  2047. (user-error
  2048. "Change makes TBLFM term %s invalid, use undo to recover"
  2049. (match-string 0))
  2050. (replace-match "")))))
  2051. (while (re-search-forward re (point-at-eol) t)
  2052. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2053. (setq s (match-string 1) n (string-to-number s))
  2054. (cond
  2055. ((setq a (assoc s replace))
  2056. (replace-match (concat key (cdr a)) t t))
  2057. ((and limit (> n limit))
  2058. (replace-match (concat key (number-to-string (+ n delta))) t t)))))
  2059. (message "The formulas in #+TBLFM have been updated"))
  2060. (forward-line))))
  2061. ;;;###autoload
  2062. (defun org-table-maybe-eval-formula ()
  2063. "Check if the current field starts with \"=\" or \":=\".
  2064. If yes, store the formula and apply it."
  2065. ;; We already know we are in a table. Get field will only return a formula
  2066. ;; when appropriate. It might return a separator line, but no problem.
  2067. (when org-table-formula-evaluate-inline
  2068. (let* ((field (org-trim (or (org-table-get-field) "")))
  2069. named eq)
  2070. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2071. (setq named (equal (string-to-char field) ?:)
  2072. eq (match-string 1 field))
  2073. (org-table-eval-formula (and named '(4))
  2074. (org-table-formula-from-user eq))))))
  2075. ;;;###autoload
  2076. (defun org-table-rotate-recalc-marks (&optional newchar)
  2077. "Rotate the recalculation mark in the first column.
  2078. If in any row, the first field is not consistent with a mark,
  2079. insert a new column for the markers.
  2080. When there is an active region, change all the lines in the region,
  2081. after prompting for the marking character.
  2082. After each change, a message will be displayed indicating the meaning
  2083. of the new mark."
  2084. (interactive)
  2085. (unless (org-at-table-p) (user-error "Not at a table"))
  2086. (let* ((region (org-region-active-p))
  2087. (l1 (and region
  2088. (save-excursion (goto-char (region-beginning))
  2089. (copy-marker (line-beginning-position)))))
  2090. (l2 (and region
  2091. (save-excursion (goto-char (region-end))
  2092. (copy-marker (line-beginning-position)))))
  2093. (l (copy-marker (line-beginning-position)))
  2094. (col (org-table-current-column))
  2095. (newchar (if region
  2096. (char-to-string
  2097. (read-char-exclusive
  2098. "Change region to what mark? Type # * ! $ or SPC: "))
  2099. newchar))
  2100. (no-special-column
  2101. (save-excursion
  2102. (goto-char (org-table-begin))
  2103. (re-search-forward
  2104. "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
  2105. (when (and newchar (not (assoc newchar org-recalc-marks)))
  2106. (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
  2107. newchar))
  2108. (when l1 (goto-char l1))
  2109. (save-excursion
  2110. (beginning-of-line)
  2111. (unless (looking-at org-table-dataline-regexp)
  2112. (user-error "Not at a table data line")))
  2113. (when no-special-column
  2114. (org-table-goto-column 1)
  2115. (org-table-insert-column))
  2116. (let ((previous-line-end (line-end-position))
  2117. (newchar
  2118. (save-excursion
  2119. (beginning-of-line)
  2120. (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
  2121. (newchar)
  2122. (t (cadr (member (match-string 1)
  2123. (append (mapcar #'car org-recalc-marks)
  2124. '(" ")))))))))
  2125. ;; Rotate mark in first row.
  2126. (org-table-get-field 1 (format " %s " newchar))
  2127. ;; Rotate marks in additional rows if a region is active.
  2128. (when region
  2129. (save-excursion
  2130. (forward-line)
  2131. (while (<= (point) l2)
  2132. (when (looking-at org-table-dataline-regexp)
  2133. (org-table-get-field 1 (format " %s " newchar)))
  2134. (forward-line))))
  2135. ;; Only align if rotation actually changed lines' length.
  2136. (when (/= previous-line-end (line-end-position)) (org-table-align)))
  2137. (goto-char l)
  2138. (org-table-goto-column (if no-special-column (1+ col) col))
  2139. (when l1 (set-marker l1 nil))
  2140. (when l2 (set-marker l2 nil))
  2141. (set-marker l nil)
  2142. (when (called-interactively-p 'interactive)
  2143. (message "%s" (cdr (assoc newchar org-recalc-marks))))))
  2144. ;;;###autoload
  2145. (defun org-table-maybe-recalculate-line ()
  2146. "Recompute the current line if marked for it, and if we haven't just done it."
  2147. (interactive)
  2148. (and org-table-allow-automatic-line-recalculation
  2149. (not (and (memq last-command org-recalc-commands)
  2150. (eq org-last-recalc-line (line-beginning-position))))
  2151. (save-excursion (beginning-of-line 1)
  2152. (looking-at org-table-auto-recalculate-regexp))
  2153. (org-table-recalculate) t))
  2154. ;;;###autoload
  2155. (defun org-table-eval-formula (&optional arg equation
  2156. suppress-align suppress-const
  2157. suppress-store suppress-analysis)
  2158. "Replace the table field value at the cursor by the result of a calculation.
  2159. In a table, this command replaces the value in the current field with the
  2160. result of a formula. It also installs the formula as the \"current\" column
  2161. formula, by storing it in a special line below the table. When called
  2162. with a `\\[universal-argument]' prefix the formula is installed as a \
  2163. field formula.
  2164. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  2165. insert the active equation for the field
  2166. back into the current field, so that it can be edited there. This is \
  2167. useful
  2168. in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
  2169. check the referenced fields.
  2170. When called, the command first prompts for a formula, which is read in
  2171. the minibuffer. Previously entered formulas are available through the
  2172. history list, and the last used formula is offered as a default.
  2173. These stored formulas are adapted correctly when moving, inserting, or
  2174. deleting columns with the corresponding commands.
  2175. The formula can be any algebraic expression understood by the Calc package.
  2176. For details, see the Org mode manual.
  2177. This function can also be called from Lisp programs and offers
  2178. additional arguments: EQUATION can be the formula to apply. If this
  2179. argument is given, the user will not be prompted.
  2180. SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
  2181. unnecessary aligns.
  2182. SUPPRESS-CONST suppresses the interpretation of constants in the
  2183. formula, assuming that this has been done already outside the
  2184. function.
  2185. SUPPRESS-STORE means the formula should not be stored, either
  2186. because it is already stored, or because it is a modified
  2187. equation that should not overwrite the stored one.
  2188. SUPPRESS-ANALYSIS prevents analyzing the table and checking
  2189. location of point."
  2190. (interactive "P")
  2191. (unless suppress-analysis
  2192. (org-table-check-inside-data-field nil t)
  2193. (org-table-analyze))
  2194. (if (equal arg '(16))
  2195. (let ((eq (org-table-current-field-formula)))
  2196. (org-table-get-field nil eq)
  2197. (org-table-align)
  2198. (setq org-table-may-need-update t))
  2199. (let* (fields
  2200. (ndown (if (integerp arg) arg 1))
  2201. (org-table-automatic-realign nil)
  2202. (case-fold-search nil)
  2203. (down (> ndown 1))
  2204. (formula (if (and equation suppress-store)
  2205. equation
  2206. (org-table-get-formula equation (equal arg '(4)))))
  2207. (n0 (org-table-current-column))
  2208. (calc-modes (copy-sequence org-calc-default-modes))
  2209. (numbers nil) ; was a variable, now fixed default
  2210. (keep-empty nil)
  2211. form form0 formrpl formrg bw fmt ev orig lispp literal
  2212. duration duration-output-format)
  2213. ;; Parse the format string. Since we have a lot of modes, this is
  2214. ;; a lot of work. However, I think calc still uses most of the time.
  2215. (if (string-match "\\(.*\\);\\(.*\\)" formula)
  2216. (progn
  2217. (setq fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2218. (match-string-no-properties 2 formula)))
  2219. (setq formula (match-string-no-properties 1 formula))
  2220. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2221. (let ((c (string-to-char (match-string 1 fmt)))
  2222. (n (string-to-number (match-string 2 fmt))))
  2223. (cl-case c
  2224. (?p (setf (cl-getf calc-modes 'calc-internal-prec) n))
  2225. (?n (setf (cl-getf calc-modes 'calc-float-format) (list 'float n)))
  2226. (?f (setf (cl-getf calc-modes 'calc-float-format) (list 'fix n)))
  2227. (?s (setf (cl-getf calc-modes 'calc-float-format) (list 'sci n)))
  2228. (?e (setf (cl-getf calc-modes 'calc-float-format) (list 'eng n)))))
  2229. ;; Remove matched flags from the mode string.
  2230. (setq fmt (replace-match "" t t fmt)))
  2231. (while (string-match "\\([tTUNLEDRFSu]\\)" fmt)
  2232. (let ((c (string-to-char (match-string 1 fmt))))
  2233. (cl-case c
  2234. (?t (setq duration t numbers t
  2235. duration-output-format org-table-duration-custom-format))
  2236. (?T (setq duration t numbers t duration-output-format nil))
  2237. (?U (setq duration t numbers t duration-output-format 'hh:mm))
  2238. (?N (setq numbers t))
  2239. (?L (setq literal t))
  2240. (?E (setq keep-empty t))
  2241. (?D (setf (cl-getf calc-modes 'calc-angle-mode) 'deg))
  2242. (?R (setf (cl-getf calc-modes 'calc-angle-mode) 'rad))
  2243. (?F (setf (cl-getf calc-modes 'calc-prefer-frac) t))
  2244. (?S (setf (cl-getf calc-modes 'calc-symbolic-mode) t))
  2245. (?u (setf (cl-getf calc-modes 'calc-simplify-mode) 'units))))
  2246. ;; Remove matched flags from the mode string.
  2247. (setq fmt (replace-match "" t t fmt)))
  2248. (unless (string-match "\\S-" fmt)
  2249. (setq fmt nil))))
  2250. (when (and (not suppress-const) org-table-formula-use-constants)
  2251. (setq formula (org-table-formula-substitute-names formula)))
  2252. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2253. (setq formula (org-table-formula-handle-first/last-rc formula))
  2254. (while (> ndown 0)
  2255. (setq fields (org-split-string
  2256. (org-trim
  2257. (buffer-substring-no-properties
  2258. (line-beginning-position) (line-end-position)))
  2259. " *| *"))
  2260. ;; replace fields with duration values if relevant
  2261. (if duration
  2262. (setq fields
  2263. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2264. fields)))
  2265. (if (eq numbers t)
  2266. (setq fields (mapcar
  2267. (lambda (x)
  2268. (if (string-match "\\S-" x)
  2269. (number-to-string (string-to-number x))
  2270. x))
  2271. fields)))
  2272. (setq ndown (1- ndown))
  2273. (setq form (copy-sequence formula)
  2274. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2275. (if (and lispp literal) (setq lispp 'literal))
  2276. ;; Insert row and column number of formula result field
  2277. (while (string-match "[@$]#" form)
  2278. (setq form
  2279. (replace-match
  2280. (format "%d"
  2281. (save-match-data
  2282. (if (equal (substring form (match-beginning 0)
  2283. (1+ (match-beginning 0)))
  2284. "@")
  2285. (org-table-current-dline)
  2286. (org-table-current-column))))
  2287. t t form)))
  2288. ;; Check for old vertical references
  2289. (org-table--error-on-old-row-references form)
  2290. ;; Insert remote references
  2291. (setq form (org-table-remote-reference-indirection form))
  2292. (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2293. (setq form
  2294. (replace-match
  2295. (save-match-data
  2296. (org-table-make-reference
  2297. (let ((rmtrng (org-table-get-remote-range
  2298. (match-string 1 form) (match-string 2 form))))
  2299. (if duration
  2300. (if (listp rmtrng)
  2301. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2302. (org-table-time-string-to-seconds rmtrng))
  2303. rmtrng))
  2304. keep-empty numbers lispp))
  2305. t t form)))
  2306. ;; Insert complex ranges
  2307. (while (and (string-match org-table-range-regexp form)
  2308. (> (length (match-string 0 form)) 1))
  2309. (setq formrg
  2310. (save-match-data
  2311. (org-table-get-range
  2312. (match-string 0 form) org-table-current-begin-pos n0)))
  2313. (setq formrpl
  2314. (save-match-data
  2315. (org-table-make-reference
  2316. ;; possibly handle durations
  2317. (if duration
  2318. (if (listp formrg)
  2319. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2320. (org-table-time-string-to-seconds formrg))
  2321. formrg)
  2322. keep-empty numbers lispp)))
  2323. (if (not (save-match-data
  2324. (string-match (regexp-quote form) formrpl)))
  2325. (setq form (replace-match formrpl t t form))
  2326. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2327. ;; Insert simple ranges, i.e. included in the current row.
  2328. (while (string-match
  2329. "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
  2330. form)
  2331. (setq form
  2332. (replace-match
  2333. (save-match-data
  2334. (org-table-make-reference
  2335. (cl-subseq fields
  2336. (+ (if (match-end 2) n0 0)
  2337. (string-to-number (match-string 1 form))
  2338. -1)
  2339. (+ (if (match-end 4) n0 0)
  2340. (string-to-number (match-string 3 form))))
  2341. keep-empty numbers lispp))
  2342. t t form)))
  2343. (setq form0 form)
  2344. ;; Insert the references to fields in same row
  2345. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2346. (let* ((n (+ (string-to-number (match-string 1 form))
  2347. (if (match-end 2) n0 0)))
  2348. (x (nth (1- (if (= n 0) n0 (max n 1))) fields)))
  2349. (setq formrpl (save-match-data
  2350. (org-table-make-reference
  2351. x keep-empty numbers lispp)))
  2352. (when (or (not x)
  2353. (save-match-data
  2354. (string-match (regexp-quote formula) formrpl)))
  2355. (user-error "Invalid field specifier \"%s\""
  2356. (match-string 0 form))))
  2357. (setq form (replace-match formrpl t t form)))
  2358. (if lispp
  2359. (setq ev (condition-case nil
  2360. (eval (eval (read form)))
  2361. (error "#ERROR"))
  2362. ev (if (numberp ev) (number-to-string ev) ev)
  2363. ev (if duration (org-table-time-seconds-to-string
  2364. (string-to-number ev)
  2365. duration-output-format)
  2366. ev))
  2367. ;; Use <...> time-stamps so that Calc can handle them.
  2368. (setq form
  2369. (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
  2370. ;; Internationalize local time-stamps by setting locale to
  2371. ;; "C".
  2372. (setq form
  2373. (replace-regexp-in-string
  2374. org-ts-regexp
  2375. (lambda (ts)
  2376. (let ((system-time-locale "C"))
  2377. (format-time-string
  2378. (org-time-stamp-format
  2379. (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2380. (apply #'encode-time
  2381. (save-match-data (org-parse-time-string ts))))))
  2382. form t t))
  2383. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2384. form
  2385. (calc-eval (cons form calc-modes)
  2386. (when (and (not keep-empty) numbers) 'num)))
  2387. ev (if duration (org-table-time-seconds-to-string
  2388. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2389. (string-to-number (org-table-time-string-to-seconds ev))
  2390. (string-to-number ev))
  2391. duration-output-format)
  2392. ev)))
  2393. (when org-table-formula-debug
  2394. (let ((wcf (current-window-configuration)))
  2395. (with-output-to-temp-buffer "*Substitution History*"
  2396. (princ (format "Substitution history of formula
  2397. Orig: %s
  2398. $xyz-> %s
  2399. @r$c-> %s
  2400. $1-> %s\n" orig formula form0 form))
  2401. (if (consp ev)
  2402. (princ (format " %s^\nError: %s"
  2403. (make-string (car ev) ?\-) (nth 1 ev)))
  2404. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2405. ev (or fmt "NONE")
  2406. (if fmt (format fmt (string-to-number ev)) ev)))))
  2407. (setq bw (get-buffer-window "*Substitution History*"))
  2408. (org-fit-window-to-buffer bw)
  2409. (unless (and (called-interactively-p 'any) (not ndown))
  2410. (unless (let (inhibit-redisplay)
  2411. (y-or-n-p "Debugging Formula. Continue to next? "))
  2412. (org-table-align)
  2413. (user-error "Abort"))
  2414. (delete-window bw)
  2415. (message "")
  2416. (set-window-configuration wcf))))
  2417. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2418. (org-table-justify-field-maybe
  2419. (format org-table-formula-field-format
  2420. (cond
  2421. ((not (stringp ev)) ev)
  2422. (fmt (format fmt (string-to-number ev)))
  2423. ;; Replace any active time stamp in the result with
  2424. ;; an inactive one. Dates in tables are likely
  2425. ;; piece of regular data, not meant to appear in the
  2426. ;; agenda.
  2427. (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev)))))
  2428. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2429. (call-interactively 'org-return)
  2430. (setq ndown 0)))
  2431. (and down (org-table-maybe-recalculate-line))
  2432. (or suppress-align (and org-table-may-need-update
  2433. (org-table-align))))))
  2434. (defun org-table-put-field-property (prop value)
  2435. (save-excursion
  2436. (put-text-property (progn (skip-chars-backward "^|") (point))
  2437. (progn (skip-chars-forward "^|") (point))
  2438. prop value)))
  2439. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2440. "Get a calc vector from a column, according to descriptor DESC.
  2441. Optional arguments TBEG and COL can give the beginning of the table and
  2442. the current column, to avoid unnecessary parsing.
  2443. HIGHLIGHT means just highlight the range.
  2444. When CORNERS-ONLY is set, only return the corners of the range as
  2445. a list (line1 column1 line2 column2) where line1 and line2 are
  2446. line numbers relative to beginning of table, or TBEG, and column1
  2447. and column2 are table column numbers."
  2448. (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
  2449. (replace-regexp-in-string "\\$" "@0$" desc)
  2450. desc))
  2451. (col (or col (org-table-current-column)))
  2452. (tbeg (or tbeg (org-table-begin)))
  2453. (thisline (count-lines tbeg (line-beginning-position))))
  2454. (unless (string-match org-table-range-regexp desc)
  2455. (user-error "Invalid table range specifier `%s'" desc))
  2456. (let ((rangep (match-end 3))
  2457. (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
  2458. (or (save-match-data
  2459. (and (org-string-nw-p r)
  2460. (org-table--descriptor-line r thisline)))
  2461. thisline)))
  2462. (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
  2463. (or (save-match-data
  2464. (and (org-string-nw-p r)
  2465. (org-table--descriptor-line r thisline)))
  2466. thisline)))
  2467. (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
  2468. (if (or (not c) (= (string-to-number c) 0)) col
  2469. (+ (string-to-number c)
  2470. (if (memq (string-to-char c) '(?- ?+)) col 0)))))
  2471. (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
  2472. (if (or (not c) (= (string-to-number c) 0)) col
  2473. (+ (string-to-number c)
  2474. (if (memq (string-to-char c) '(?- ?+)) col 0))))))
  2475. (save-excursion
  2476. (if (and (not corners-only)
  2477. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2478. ;; Just one field.
  2479. (progn
  2480. (forward-line (- r1 thisline))
  2481. (while (not (looking-at org-table-dataline-regexp))
  2482. (forward-line))
  2483. (prog1 (org-trim (org-table-get-field c1))
  2484. (when highlight (org-table-highlight-rectangle))))
  2485. ;; A range, return a vector. First sort the numbers to get
  2486. ;; a regular rectangle.
  2487. (let ((first-row (min r1 r2))
  2488. (last-row (max r1 r2))
  2489. (first-column (min c1 c2))
  2490. (last-column (max c1 c2)))
  2491. (if corners-only (list first-row first-column last-row last-column)
  2492. ;; Copy the range values into a list.
  2493. (forward-line (- first-row thisline))
  2494. (while (not (looking-at org-table-dataline-regexp))
  2495. (forward-line)
  2496. (cl-incf first-row))
  2497. (org-table-goto-column first-column)
  2498. (let ((beg (point)))
  2499. (forward-line (- last-row first-row))
  2500. (while (not (looking-at org-table-dataline-regexp))
  2501. (forward-line -1))
  2502. (org-table-goto-column last-column)
  2503. (let ((end (point)))
  2504. (when highlight
  2505. (org-table-highlight-rectangle
  2506. beg (progn (skip-chars-forward "^|\n") (point))))
  2507. ;; Return string representation of calc vector.
  2508. (mapcar #'org-trim
  2509. (apply #'append
  2510. (org-table-copy-region beg end))))))))))))
  2511. (defun org-table--descriptor-line (desc cline)
  2512. "Return relative line number corresponding to descriptor DESC.
  2513. The cursor is currently in relative line number CLINE."
  2514. (if (string-match "\\`[0-9]+\\'" desc)
  2515. (aref org-table-dlines (string-to-number desc))
  2516. (when (or (not (string-match
  2517. "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
  2518. ;; 1 2 3 4 5 6
  2519. desc))
  2520. (and (not (match-end 3)) (not (match-end 6)))
  2521. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2522. (user-error "Invalid row descriptor `%s'" desc))
  2523. (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
  2524. (hdir (match-string 2 desc))
  2525. (odir (match-string 5 desc))
  2526. (on (and (match-end 6) (string-to-number (match-string 6 desc))))
  2527. (rel (and (match-end 6)
  2528. (or (and (match-end 1) (not (match-end 3)))
  2529. (match-end 5)))))
  2530. (when (and hn (not hdir))
  2531. (setq cline 0)
  2532. (setq hdir "+")
  2533. (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
  2534. (when (and (not hn) on (not odir)) (user-error "Should never happen"))
  2535. (when hn
  2536. (setq cline
  2537. (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
  2538. (when on
  2539. (setq cline
  2540. (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
  2541. cline)))
  2542. (defun org-table--row-type (type n i backwards relative desc)
  2543. "Return relative line of Nth row with type TYPE.
  2544. Search starts from relative line I. When BACKWARDS in non-nil,
  2545. look before I. When RELATIVE is non-nil, the reference is
  2546. relative. DESC is the original descriptor that started the
  2547. search, as a string."
  2548. (let ((l (length org-table-current-line-types)))
  2549. (catch :exit
  2550. (dotimes (_ n)
  2551. (while (and (cl-incf i (if backwards -1 1))
  2552. (>= i 0)
  2553. (< i l)
  2554. (not (eq (aref org-table-current-line-types i) type))
  2555. ;; We are going to cross a hline. Check if this is
  2556. ;; an authorized move.
  2557. (cond
  2558. ((not relative))
  2559. ((not (eq (aref org-table-current-line-types i) 'hline)))
  2560. ((eq org-table-relative-ref-may-cross-hline t))
  2561. ((eq org-table-relative-ref-may-cross-hline 'error)
  2562. (user-error "Row descriptor %s crosses hline" desc))
  2563. (t (cl-decf i (if backwards -1 1)) ; Step back.
  2564. (throw :exit nil)))))))
  2565. (cond ((or (< i 0) (>= i l))
  2566. (user-error "Row descriptor %s leads outside table" desc))
  2567. ;; The last hline doesn't exist. Instead, point to last row
  2568. ;; in table.
  2569. ((= i (1- l)) (1- i))
  2570. (t i))))
  2571. (defun org-table--error-on-old-row-references (s)
  2572. (when (string-match "&[-+0-9I]" s)
  2573. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2574. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2575. "Convert list ELEMENTS to something appropriate to insert into formula.
  2576. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2577. NUMBERS indicates that everything should be converted to numbers.
  2578. LISPP non-nil means to return something appropriate for a Lisp
  2579. list, `literal' is for the format specifier L."
  2580. ;; Calc nan (not a number) is used for the conversion of the empty
  2581. ;; field to a reference for several reasons: (i) It is accepted in a
  2582. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2583. ;; (ii) In a single field (not in range) it can be distinguished
  2584. ;; from "(nan)" which is the reference made from a single field
  2585. ;; containing "nan".
  2586. (if (stringp elements)
  2587. ;; field reference
  2588. (if lispp
  2589. (if (eq lispp 'literal)
  2590. elements
  2591. (if (and (eq elements "") (not keep-empty))
  2592. ""
  2593. (prin1-to-string
  2594. (if numbers (string-to-number elements) elements))))
  2595. (if (string-match "\\S-" elements)
  2596. (progn
  2597. (when numbers (setq elements (number-to-string
  2598. (string-to-number elements))))
  2599. (concat "(" elements ")"))
  2600. (if (or (not keep-empty) numbers) "(0)" "nan")))
  2601. ;; range reference
  2602. (unless keep-empty
  2603. (setq elements
  2604. (delq nil
  2605. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2606. elements))))
  2607. (setq elements (or elements '())) ; if delq returns nil then we need '()
  2608. (if lispp
  2609. (mapconcat
  2610. (lambda (x)
  2611. (if (eq lispp 'literal)
  2612. x
  2613. (prin1-to-string (if numbers (string-to-number x) x))))
  2614. elements " ")
  2615. (concat "[" (mapconcat
  2616. (lambda (x)
  2617. (if (string-match "\\S-" x)
  2618. (if numbers
  2619. (number-to-string (string-to-number x))
  2620. x)
  2621. (if (or (not keep-empty) numbers) "0" "nan")))
  2622. elements
  2623. ",") "]"))))
  2624. (defun org-table-message-once-per-second (t1 &rest args)
  2625. "If there has been more than one second since T1, display message.
  2626. ARGS are passed as arguments to the `message' function. Returns
  2627. current time if a message is printed, otherwise returns T1. If
  2628. T1 is nil, always messages."
  2629. (let ((curtime (current-time)))
  2630. (if (or (not t1) (time-less-p 1 (time-subtract curtime t1)))
  2631. (progn (apply 'message args)
  2632. curtime)
  2633. t1)))
  2634. ;;;###autoload
  2635. (defun org-table-recalculate (&optional all noalign)
  2636. "Recalculate the current table line by applying all stored formulas.
  2637. With prefix arg ALL, do this for all lines in the table.
  2638. When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
  2639. if ALL is the symbol `iterate',
  2640. recompute the table until it no longer changes.
  2641. If NOALIGN is not nil, do not re-align the table after the computations
  2642. are done. This is typically used internally to save time, if it is
  2643. known that the table will be realigned a little later anyway."
  2644. (interactive "P")
  2645. (unless (memq this-command org-recalc-commands)
  2646. (push this-command org-recalc-commands))
  2647. (unless (org-at-table-p) (user-error "Not at a table"))
  2648. (if (or (eq all 'iterate) (equal all '(16)))
  2649. (org-table-iterate)
  2650. (org-table-analyze)
  2651. (let* ((eqlist (sort (org-table-get-stored-formulas)
  2652. (lambda (a b) (string< (car a) (car b)))))
  2653. (inhibit-redisplay (not debug-on-error))
  2654. (line-re org-table-dataline-regexp)
  2655. (log-first-time (current-time))
  2656. (log-last-time log-first-time)
  2657. (cnt 0)
  2658. beg end eqlcol eqlfield)
  2659. ;; Insert constants in all formulas.
  2660. (when eqlist
  2661. (org-table-with-shrunk-columns
  2662. (org-table-save-field
  2663. ;; Expand equations, then split the equation list between
  2664. ;; column formulas and field formulas.
  2665. (dolist (eq eqlist)
  2666. (let* ((rhs (org-table-formula-substitute-names
  2667. (org-table-formula-handle-first/last-rc (cdr eq))))
  2668. (old-lhs (car eq))
  2669. (lhs
  2670. (org-table-formula-handle-first/last-rc
  2671. (cond
  2672. ((string-match "\\`@-?I+" old-lhs)
  2673. (user-error "Can't assign to hline relative reference"))
  2674. ((string-match "\\`\\$[<>]" old-lhs)
  2675. (let ((new (org-table-formula-handle-first/last-rc
  2676. old-lhs)))
  2677. (when (assoc new eqlist)
  2678. (user-error "\"%s=\" formula tries to overwrite \
  2679. existing formula for column %s"
  2680. old-lhs
  2681. new))
  2682. new))
  2683. (t old-lhs)))))
  2684. (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
  2685. (push (cons lhs rhs) eqlcol)
  2686. (push (cons lhs rhs) eqlfield))))
  2687. (setq eqlcol (nreverse eqlcol))
  2688. ;; Expand ranges in lhs of formulas
  2689. (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
  2690. ;; Get the correct line range to process.
  2691. (if all
  2692. (progn
  2693. (setq end (copy-marker (org-table-end)))
  2694. (goto-char (setq beg org-table-current-begin-pos))
  2695. (cond
  2696. ((re-search-forward org-table-calculate-mark-regexp end t)
  2697. ;; This is a table with marked lines, compute selected
  2698. ;; lines.
  2699. (setq line-re org-table-recalculate-regexp))
  2700. ;; Move forward to the first non-header line.
  2701. ((and (re-search-forward org-table-dataline-regexp end t)
  2702. (re-search-forward org-table-hline-regexp end t)
  2703. (re-search-forward org-table-dataline-regexp end t))
  2704. (setq beg (match-beginning 0)))
  2705. ;; Just leave BEG at the start of the table.
  2706. (t nil)))
  2707. (setq beg (line-beginning-position)
  2708. end (copy-marker (line-beginning-position 2))))
  2709. (goto-char beg)
  2710. ;; Mark named fields untouchable. Also check if several
  2711. ;; field/range formulas try to set the same field.
  2712. (remove-text-properties beg end '(:org-untouchable t))
  2713. (let ((current-line (count-lines org-table-current-begin-pos
  2714. (line-beginning-position)))
  2715. seen-fields)
  2716. (dolist (eq eqlfield)
  2717. (let* ((name (car eq))
  2718. (location (assoc name org-table-named-field-locations))
  2719. (eq-line (or (nth 1 location)
  2720. (and (string-match "\\`@\\([0-9]+\\)" name)
  2721. (aref org-table-dlines
  2722. (string-to-number
  2723. (match-string 1 name))))))
  2724. (reference
  2725. (if location
  2726. ;; Turn field coordinates associated to NAME
  2727. ;; into an absolute reference.
  2728. (format "@%d$%d"
  2729. (org-table-line-to-dline eq-line)
  2730. (nth 2 location))
  2731. name)))
  2732. (when (member reference seen-fields)
  2733. (user-error "Several field/range formulas try to set %s"
  2734. reference))
  2735. (push reference seen-fields)
  2736. (when (or all (eq eq-line current-line))
  2737. (org-table-goto-field name)
  2738. (org-table-put-field-property :org-untouchable t)))))
  2739. ;; Evaluate the column formulas, but skip fields covered by
  2740. ;; field formulas.
  2741. (goto-char beg)
  2742. (while (re-search-forward line-re end t)
  2743. (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
  2744. ;; Unprotected line, recalculate.
  2745. (cl-incf cnt)
  2746. (when all
  2747. (setq log-last-time
  2748. (org-table-message-once-per-second
  2749. log-last-time
  2750. "Re-applying formulas to full table...(line %d)" cnt)))
  2751. (if (markerp org-last-recalc-line)
  2752. (move-marker org-last-recalc-line (line-beginning-position))
  2753. (setq org-last-recalc-line
  2754. (copy-marker (line-beginning-position))))
  2755. (dolist (entry eqlcol)
  2756. (goto-char org-last-recalc-line)
  2757. (org-table-goto-column
  2758. (string-to-number (substring (car entry) 1)) nil 'force)
  2759. (unless (get-text-property (point) :org-untouchable)
  2760. (org-table-eval-formula
  2761. nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
  2762. ;; Evaluate the field formulas.
  2763. (dolist (eq eqlfield)
  2764. (let ((reference (car eq))
  2765. (formula (cdr eq)))
  2766. (setq log-last-time
  2767. (org-table-message-once-per-second
  2768. (and all log-last-time)
  2769. "Re-applying formula to field: %s" (car eq)))
  2770. (org-table-goto-field
  2771. reference
  2772. ;; Possibly create a new column, as long as
  2773. ;; `org-table-formula-create-columns' allows it.
  2774. (let ((column-count (progn (end-of-line)
  2775. (1- (org-table-current-column)))))
  2776. (lambda (column)
  2777. (when (> column 1000)
  2778. (user-error "Formula column target too large"))
  2779. (and (> column column-count)
  2780. (or (eq org-table-formula-create-columns t)
  2781. (and (eq org-table-formula-create-columns 'warn)
  2782. (progn
  2783. (org-display-warning
  2784. "Out-of-bounds formula added columns")
  2785. t))
  2786. (and (eq org-table-formula-create-columns 'prompt)
  2787. (yes-or-no-p
  2788. "Out-of-bounds formula. Add columns? "))
  2789. (user-error
  2790. "Missing columns in the table. Aborting"))))))
  2791. (org-table-eval-formula nil formula t t t t)))
  2792. ;; Clean up marker.
  2793. (set-marker end nil)))
  2794. (unless noalign
  2795. (when org-table-may-need-update (org-table-align))
  2796. (when all
  2797. (org-table-message-once-per-second
  2798. log-first-time "Re-applying formulas to %d lines... done" cnt)))
  2799. (org-table-message-once-per-second
  2800. (and all log-first-time) "Re-applying formulas... done")))))
  2801. ;;;###autoload
  2802. (defun org-table-iterate (&optional arg)
  2803. "Recalculate the table until it does not change anymore.
  2804. The maximum number of iterations is 10, but you can choose a different value
  2805. with the prefix ARG."
  2806. (interactive "P")
  2807. (let ((imax (if arg (prefix-numeric-value arg) 10))
  2808. (i 0)
  2809. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  2810. thistbl)
  2811. (catch 'exit
  2812. (while (< i imax)
  2813. (setq i (1+ i))
  2814. (org-table-recalculate 'all)
  2815. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  2816. (if (not (string= lasttbl thistbl))
  2817. (setq lasttbl thistbl)
  2818. (if (> i 1)
  2819. (message "Convergence after %d iterations" i)
  2820. (message "Table was already stable"))
  2821. (throw 'exit t)))
  2822. (user-error "No convergence after %d iterations" i))))
  2823. ;;;###autoload
  2824. (defun org-table-recalculate-buffer-tables ()
  2825. "Recalculate all tables in the current buffer."
  2826. (interactive)
  2827. (org-with-wide-buffer
  2828. (org-table-map-tables
  2829. (lambda ()
  2830. ;; Reason for separate `org-table-align': When repeating
  2831. ;; (org-table-recalculate t) `org-table-may-need-update' gets in
  2832. ;; the way.
  2833. (org-table-recalculate t t)
  2834. (org-table-align))
  2835. t)))
  2836. ;;;###autoload
  2837. (defun org-table-iterate-buffer-tables ()
  2838. "Iterate all tables in the buffer, to converge inter-table dependencies."
  2839. (interactive)
  2840. (let* ((imax 10)
  2841. (i imax)
  2842. (checksum (md5 (buffer-string)))
  2843. c1)
  2844. (org-with-wide-buffer
  2845. (catch 'exit
  2846. (while (> i 0)
  2847. (setq i (1- i))
  2848. (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
  2849. (if (equal checksum (setq c1 (md5 (buffer-string))))
  2850. (progn
  2851. (org-table-map-tables #'org-table-align t)
  2852. (message "Convergence after %d iterations" (- imax i))
  2853. (throw 'exit t))
  2854. (setq checksum c1)))
  2855. (org-table-map-tables #'org-table-align t)
  2856. (user-error "No convergence after %d iterations" imax)))))
  2857. (defun org-table-calc-current-TBLFM (&optional arg)
  2858. "Apply the #+TBLFM in the line at point to the table."
  2859. (interactive "P")
  2860. (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
  2861. (let ((formula (buffer-substring
  2862. (line-beginning-position)
  2863. (line-end-position))))
  2864. (save-excursion
  2865. ;; Insert a temporary formula at right after the table
  2866. (goto-char (org-table-TBLFM-begin))
  2867. (let ((s (point-marker)))
  2868. (insert formula "\n")
  2869. (let ((e (point-marker)))
  2870. ;; Recalculate the table.
  2871. (beginning-of-line 0) ; move to the inserted line
  2872. (skip-chars-backward " \r\n\t")
  2873. (unwind-protect
  2874. (org-call-with-arg #'org-table-recalculate (or arg t))
  2875. ;; Delete the formula inserted temporarily.
  2876. (delete-region s e)
  2877. (set-marker s nil)
  2878. (set-marker e nil)))))))
  2879. (defun org-table-TBLFM-begin ()
  2880. "Find the beginning of the TBLFM lines and return its position.
  2881. Return nil when the beginning of TBLFM line was not found."
  2882. (save-excursion
  2883. (when (progn (forward-line 1)
  2884. (re-search-backward org-table-TBLFM-begin-regexp nil t))
  2885. (line-beginning-position 2))))
  2886. (defun org-table-expand-lhs-ranges (equations)
  2887. "Expand list of formulas.
  2888. If some of the RHS in the formulas are ranges or a row reference,
  2889. expand them to individual field equations for each field. This
  2890. function assumes the table is already analyzed (i.e., using
  2891. `org-table-analyze')."
  2892. (let (res)
  2893. (dolist (e equations (nreverse res))
  2894. (let ((lhs (car e))
  2895. (rhs (cdr e)))
  2896. (cond
  2897. ((string-match-p "\\`@[-+0-9]+\\$-?[0-9]+\\'" lhs)
  2898. ;; This just refers to one fixed field.
  2899. (push e res))
  2900. ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
  2901. ;; This just refers to one fixed named field.
  2902. (push e res))
  2903. ((string-match-p "\\`\\$[0-9]+\\'" lhs)
  2904. ;; Column formulas are treated specially and are not
  2905. ;; expanded.
  2906. (push e res))
  2907. ((string-match "\\`@[0-9]+\\'" lhs)
  2908. (dotimes (ic org-table-current-ncol)
  2909. (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
  2910. rhs)
  2911. res)))
  2912. (t
  2913. (let* ((range (org-table-get-range
  2914. lhs org-table-current-begin-pos 1 nil 'corners))
  2915. (r1 (org-table-line-to-dline (nth 0 range)))
  2916. (c1 (nth 1 range))
  2917. (r2 (org-table-line-to-dline (nth 2 range) 'above))
  2918. (c2 (nth 3 range)))
  2919. (cl-loop for ir from r1 to r2 do
  2920. (cl-loop for ic from c1 to c2 do
  2921. (push (cons (propertize
  2922. (format "@%d$%d" ir ic) :orig-eqn e)
  2923. rhs)
  2924. res))))))))))
  2925. (defun org-table-formula-handle-first/last-rc (s)
  2926. "Replace @<, @>, $<, $> with first/last row/column of the table.
  2927. So @< and $< will always be replaced with @1 and $1, respectively.
  2928. The advantage of these special markers are that structure editing of
  2929. the table will not change them, while @1 and $1 will be modified
  2930. when a line/row is swapped out of that privileged position. So for
  2931. formulas that use a range of rows or columns, it may often be better
  2932. to anchor the formula with \"I\" row markers, or to offset from the
  2933. borders of the table using the @< @> $< $> makers."
  2934. (let (n nmax len char (start 0))
  2935. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
  2936. s start)
  2937. (if (match-end 3)
  2938. (setq start (match-end 3))
  2939. (setq nmax (if (equal (match-string 1 s) "@")
  2940. (1- (length org-table-dlines))
  2941. org-table-current-ncol)
  2942. len (- (match-end 2) (match-beginning 2))
  2943. char (string-to-char (match-string 2 s))
  2944. n (if (= char ?<)
  2945. len
  2946. (- nmax len -1)))
  2947. (if (or (< n 1) (> n nmax))
  2948. (user-error "Reference \"%s\" in expression \"%s\" points outside table"
  2949. (match-string 0 s) s))
  2950. (setq start (match-beginning 0))
  2951. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
  2952. s)
  2953. (defun org-table-formula-substitute-names (f)
  2954. "Replace $const with values in string F."
  2955. (let ((start 0)
  2956. (pp (/= (string-to-char f) ?'))
  2957. (duration (string-match-p ";.*[Tt].*\\'" f))
  2958. (new (replace-regexp-in-string ; Check for column names.
  2959. org-table-column-name-regexp
  2960. (lambda (m)
  2961. (concat "$" (cdr (assoc (match-string 1 m)
  2962. org-table-column-names))))
  2963. f t t)))
  2964. ;; Parameters and constants.
  2965. (while (setq start
  2966. (string-match
  2967. "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
  2968. new start))
  2969. (if (match-end 2) (setq start (match-end 2))
  2970. (cl-incf start)
  2971. ;; When a duration is expected, convert value on the fly.
  2972. (let ((value
  2973. (save-match-data
  2974. (let ((v (org-table-get-constant (match-string 1 new))))
  2975. (if (and (org-string-nw-p v) duration)
  2976. (org-table-time-string-to-seconds v)
  2977. v)))))
  2978. (when value
  2979. (setq new (replace-match
  2980. (concat (and pp "(") value (and pp ")")) t t new))))))
  2981. (if org-table-formula-debug (propertize new :orig-formula f) new)))
  2982. (defun org-table-get-constant (const)
  2983. "Find the value for a parameter or constant in a formula.
  2984. Parameters get priority."
  2985. (or (cdr (assoc const org-table-local-parameters))
  2986. (cdr (assoc const org-table-formula-constants-local))
  2987. (cdr (assoc const org-table-formula-constants))
  2988. (and (fboundp 'constants-get) (constants-get const))
  2989. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  2990. (org-entry-get nil (substring const 5) 'inherit))
  2991. "#UNDEFINED_NAME"))
  2992. (defvar org-table-fedit-map
  2993. (let ((map (make-sparse-keymap)))
  2994. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  2995. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  2996. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  2997. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  2998. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  2999. (org-defkey map "\C-c?" 'org-table-show-reference)
  3000. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  3001. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  3002. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  3003. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  3004. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  3005. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  3006. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  3007. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  3008. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  3009. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  3010. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  3011. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  3012. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  3013. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  3014. map))
  3015. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu."
  3016. '("Edit-Formulas"
  3017. ["Finish and Install" org-table-fedit-finish t]
  3018. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  3019. ["Abort" org-table-fedit-abort t]
  3020. "--"
  3021. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  3022. ["Complete Lisp Symbol" lisp-complete-symbol t]
  3023. "--"
  3024. "Shift Reference at Point"
  3025. ["Up" org-table-fedit-ref-up t]
  3026. ["Down" org-table-fedit-ref-down t]
  3027. ["Left" org-table-fedit-ref-left t]
  3028. ["Right" org-table-fedit-ref-right t]
  3029. "-"
  3030. "Change Test Row for Column Formulas"
  3031. ["Up" org-table-fedit-line-up t]
  3032. ["Down" org-table-fedit-line-down t]
  3033. "--"
  3034. ["Scroll Table Window" org-table-fedit-scroll t]
  3035. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  3036. ["Show Table Grid" org-table-fedit-toggle-coordinates
  3037. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  3038. org-table-overlay-coordinates)]
  3039. "--"
  3040. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  3041. :style toggle :selected org-table-buffer-is-an]))
  3042. (defvar org-table--fedit-source nil
  3043. "Position of the TBLFM line being edited.")
  3044. ;;;###autoload
  3045. (defun org-table-edit-formulas ()
  3046. "Edit the formulas of the current table in a separate buffer."
  3047. (interactive)
  3048. (let ((at-tblfm (org-at-TBLFM-p)))
  3049. (unless (or at-tblfm (org-at-table-p))
  3050. (user-error "Not at a table"))
  3051. (save-excursion
  3052. ;; Move point within the table before analyzing it.
  3053. (when at-tblfm (re-search-backward "^[ \t]*|"))
  3054. (org-table-analyze))
  3055. (let ((key (org-table-current-field-formula 'key 'noerror))
  3056. (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
  3057. #'org-table-formula-less-p))
  3058. (pos (point-marker))
  3059. (source (copy-marker (line-beginning-position)))
  3060. (startline 1)
  3061. (wc (current-window-configuration))
  3062. (sel-win (selected-window))
  3063. (titles '((column . "# Column Formulas\n")
  3064. (field . "# Field and Range Formulas\n")
  3065. (named . "# Named Field Formulas\n"))))
  3066. (org-switch-to-buffer-other-window "*Edit Formulas*")
  3067. (erase-buffer)
  3068. ;; Keep global-font-lock-mode from turning on font-lock-mode
  3069. (let ((font-lock-global-modes '(not fundamental-mode)))
  3070. (fundamental-mode))
  3071. (setq-local font-lock-global-modes (list 'not major-mode))
  3072. (setq-local org-pos pos)
  3073. (setq-local org-table--fedit-source source)
  3074. (setq-local org-window-configuration wc)
  3075. (setq-local org-selected-window sel-win)
  3076. (use-local-map org-table-fedit-map)
  3077. (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
  3078. (setq startline (org-current-line))
  3079. (dolist (entry eql)
  3080. (let* ((type (cond
  3081. ((string-match "\\`\\$\\([0-9]+\\|[<>]+\\)\\'"
  3082. (car entry))
  3083. 'column)
  3084. ((equal (string-to-char (car entry)) ?@) 'field)
  3085. (t 'named)))
  3086. (title (assq type titles)))
  3087. (when title
  3088. (unless (bobp) (insert "\n"))
  3089. (insert
  3090. (org-add-props (cdr title) nil 'face font-lock-comment-face))
  3091. (setq titles (remove title titles)))
  3092. (when (equal key (car entry)) (setq startline (org-current-line)))
  3093. (let ((s (concat
  3094. (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
  3095. (car entry) " = " (cdr entry) "\n")))
  3096. (remove-text-properties 0 (length s) '(face nil) s)
  3097. (insert s))))
  3098. (when (eq org-table-use-standard-references t)
  3099. (org-table-fedit-toggle-ref-type))
  3100. (org-goto-line startline)
  3101. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  3102. Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
  3103. See menu for more commands.")))))
  3104. (defun org-table-fedit-post-command ()
  3105. (when (not (memq this-command '(lisp-complete-symbol)))
  3106. (let ((win (selected-window)))
  3107. (save-excursion
  3108. (ignore-errors (org-table-show-reference))
  3109. (select-window win)))))
  3110. (defun org-table-formula-to-user (s)
  3111. "Convert a formula from internal to user representation."
  3112. (if (eq org-table-use-standard-references t)
  3113. (org-table-convert-refs-to-an s)
  3114. s))
  3115. (defun org-table-formula-from-user (s)
  3116. "Convert a formula from user to internal representation."
  3117. (if org-table-use-standard-references
  3118. (org-table-convert-refs-to-rc s)
  3119. s))
  3120. (defun org-table-convert-refs-to-rc (s)
  3121. "Convert spreadsheet references from A7 to @7$28.
  3122. Works for single references, but also for entire formulas and even the
  3123. full TBLFM line."
  3124. (let ((start 0))
  3125. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
  3126. (cond
  3127. ((match-end 3)
  3128. ;; format match, just advance
  3129. (setq start (match-end 0)))
  3130. ((and (> (match-beginning 0) 0)
  3131. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  3132. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  3133. ;; 3.e5 or something like this.
  3134. (setq start (match-end 0)))
  3135. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  3136. ;; (member (match-string 1 s)
  3137. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  3138. )
  3139. ;; function name, just advance
  3140. (setq start (match-end 0)))
  3141. (t
  3142. (setq start (match-beginning 0)
  3143. s (replace-match
  3144. (if (equal (match-string 2 s) "&")
  3145. (format "$%d" (org-letters-to-number (match-string 1 s)))
  3146. (format "@%d$%d"
  3147. (string-to-number (match-string 2 s))
  3148. (org-letters-to-number (match-string 1 s))))
  3149. t t s)))))
  3150. s))
  3151. (defun org-table-convert-refs-to-an (s)
  3152. "Convert spreadsheet references from to @7$28 to AB7.
  3153. Works for single references, but also for entire formulas and even the
  3154. full TBLFM line."
  3155. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  3156. (setq s (replace-match
  3157. (format "%s%d"
  3158. (org-number-to-letters
  3159. (string-to-number (match-string 2 s)))
  3160. (string-to-number (match-string 1 s)))
  3161. t t s)))
  3162. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  3163. (setq s (replace-match (concat "\\1"
  3164. (org-number-to-letters
  3165. (string-to-number (match-string 2 s))) "&")
  3166. t nil s)))
  3167. s)
  3168. (defun org-letters-to-number (s)
  3169. "Convert a base 26 number represented by letters into an integer.
  3170. For example: AB -> 28."
  3171. (let ((n 0))
  3172. (setq s (upcase s))
  3173. (while (> (length s) 0)
  3174. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3175. s (substring s 1)))
  3176. n))
  3177. (defun org-number-to-letters (n)
  3178. "Convert an integer into a base 26 number represented by letters.
  3179. For example: 28 -> AB."
  3180. (let ((s ""))
  3181. (while (> n 0)
  3182. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3183. n (/ (1- n) 26)))
  3184. s))
  3185. (defun org-table-time-string-to-seconds (s)
  3186. "Convert a time string into numerical duration in seconds.
  3187. S can be a string matching either -?HH:MM:SS or -?HH:MM.
  3188. If S is a string representing a number, keep this number."
  3189. (if (equal s "")
  3190. s
  3191. (let (hour minus min sec res)
  3192. (cond
  3193. ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3194. (setq minus (< 0 (length (match-string 1 s)))
  3195. hour (string-to-number (match-string 2 s))
  3196. min (string-to-number (match-string 3 s))
  3197. sec (string-to-number (match-string 4 s)))
  3198. (if minus
  3199. (setq res (- (+ (* hour 3600) (* min 60) sec)))
  3200. (setq res (+ (* hour 3600) (* min 60) sec))))
  3201. ((and (not (string-match org-ts-regexp-both s))
  3202. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3203. (setq minus (< 0 (length (match-string 1 s)))
  3204. hour (string-to-number (match-string 2 s))
  3205. min (string-to-number (match-string 3 s)))
  3206. (if minus
  3207. (setq res (- (+ (* hour 3600) (* min 60))))
  3208. (setq res (+ (* hour 3600) (* min 60)))))
  3209. (t (setq res (string-to-number s))))
  3210. (number-to-string res))))
  3211. (defun org-table-time-seconds-to-string (secs &optional output-format)
  3212. "Convert a number of seconds to a time string.
  3213. If OUTPUT-FORMAT is non-nil, return a number of days, hours,
  3214. minutes or seconds."
  3215. (let* ((secs0 (abs secs))
  3216. (res
  3217. (cond ((eq output-format 'days)
  3218. (format "%.3f" (/ (float secs0) 86400)))
  3219. ((eq output-format 'hours)
  3220. (format "%.2f" (/ (float secs0) 3600)))
  3221. ((eq output-format 'minutes)
  3222. (format "%.1f" (/ (float secs0) 60)))
  3223. ((eq output-format 'seconds)
  3224. (format "%d" secs0))
  3225. ((eq output-format 'hh:mm)
  3226. ;; Ignore seconds
  3227. (substring (format-seconds
  3228. (if org-table-duration-hour-zero-padding
  3229. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3230. secs0)
  3231. 0 -3))
  3232. (t (format-seconds
  3233. (if org-table-duration-hour-zero-padding
  3234. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3235. secs0)))))
  3236. (if (< secs 0) (concat "-" res) res)))
  3237. (defun org-table-fedit-convert-buffer (function)
  3238. "Convert all references in this buffer, using FUNCTION."
  3239. (let ((origin (copy-marker (line-beginning-position))))
  3240. (goto-char (point-min))
  3241. (while (not (eobp))
  3242. (insert (funcall function (buffer-substring (point) (line-end-position))))
  3243. (delete-region (point) (line-end-position))
  3244. (forward-line))
  3245. (goto-char origin)
  3246. (set-marker origin nil)))
  3247. (defun org-table-fedit-toggle-ref-type ()
  3248. "Convert all references in the buffer from B3 to @3$2 and back."
  3249. (interactive)
  3250. (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
  3251. (org-table-fedit-convert-buffer
  3252. (if org-table-buffer-is-an
  3253. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3254. (message "Reference type switched to %s"
  3255. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3256. (defun org-table-fedit-ref-up ()
  3257. "Shift the reference at point one row/hline up."
  3258. (interactive)
  3259. (org-table-fedit-shift-reference 'up))
  3260. (defun org-table-fedit-ref-down ()
  3261. "Shift the reference at point one row/hline down."
  3262. (interactive)
  3263. (org-table-fedit-shift-reference 'down))
  3264. (defun org-table-fedit-ref-left ()
  3265. "Shift the reference at point one field to the left."
  3266. (interactive)
  3267. (org-table-fedit-shift-reference 'left))
  3268. (defun org-table-fedit-ref-right ()
  3269. "Shift the reference at point one field to the right."
  3270. (interactive)
  3271. (org-table-fedit-shift-reference 'right))
  3272. (defun org-table--rematch-and-replace (n &optional decr hline)
  3273. "Re-match the group N, and replace it with the shifted reference."
  3274. (or (match-end n) (user-error "Cannot shift reference in this direction"))
  3275. (goto-char (match-beginning n))
  3276. (and (looking-at (regexp-quote (match-string n)))
  3277. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  3278. t t)))
  3279. (defun org-table-fedit-shift-reference (dir)
  3280. (cond
  3281. ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
  3282. (if (memq dir '(left right))
  3283. (org-table--rematch-and-replace 1 (eq dir 'left))
  3284. (user-error "Cannot shift reference in this direction")))
  3285. ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3286. ;; A B3-like reference
  3287. (if (memq dir '(up down))
  3288. (org-table--rematch-and-replace 2 (eq dir 'up))
  3289. (org-table--rematch-and-replace 1 (eq dir 'left))))
  3290. ((org-in-regexp
  3291. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3292. ;; An internal reference
  3293. (if (memq dir '(up down))
  3294. (org-table--rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3295. (org-table--rematch-and-replace 5 (eq dir 'left))))))
  3296. (defun org-table-shift-refpart (ref &optional decr hline)
  3297. "Shift a reference part REF.
  3298. If DECR is set, decrease the references row/column, else increase.
  3299. If HLINE is set, this may be a hline reference, it certainly is not
  3300. a translation reference."
  3301. (save-match-data
  3302. (let* ((sign (string-match "^[-+]" ref)) n)
  3303. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  3304. (cond
  3305. ((and hline (string-match "^I+" ref))
  3306. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  3307. (setq n (+ n (if decr -1 1)))
  3308. (if (= n 0) (setq n (+ n (if decr -1 1))))
  3309. (if sign
  3310. (setq sign (if (< n 0) "-" "+") n (abs n))
  3311. (setq n (max 1 n)))
  3312. (concat sign (make-string n ?I)))
  3313. ((string-match "^[0-9]+" ref)
  3314. (setq n (string-to-number (concat sign ref)))
  3315. (setq n (+ n (if decr -1 1)))
  3316. (if sign
  3317. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  3318. (number-to-string (max 1 n))))
  3319. ((string-match "^[a-zA-Z]+" ref)
  3320. (org-number-to-letters
  3321. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  3322. (t (user-error "Cannot shift reference"))))))
  3323. (defun org-table-fedit-toggle-coordinates ()
  3324. "Toggle the display of coordinates in the referenced table."
  3325. (interactive)
  3326. (let ((pos (marker-position org-pos)))
  3327. (with-current-buffer (marker-buffer org-pos)
  3328. (save-excursion
  3329. (goto-char pos)
  3330. (org-table-toggle-coordinate-overlays)))))
  3331. (defun org-table-fedit-finish (&optional arg)
  3332. "Parse the buffer for formula definitions and install them.
  3333. With prefix ARG, apply the new formulas to the table."
  3334. (interactive "P")
  3335. (org-table-remove-rectangle-highlight)
  3336. (when org-table-use-standard-references
  3337. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  3338. (setq org-table-buffer-is-an nil))
  3339. (let ((pos org-pos)
  3340. (sel-win org-selected-window)
  3341. (source org-table--fedit-source)
  3342. eql)
  3343. (goto-char (point-min))
  3344. (while (re-search-forward
  3345. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  3346. nil t)
  3347. (let ((var (match-string 1))
  3348. (form (org-trim (match-string 3))))
  3349. (unless (equal form "")
  3350. (while (string-match "[ \t]*\n[ \t]*" form)
  3351. (setq form (replace-match " " t t form)))
  3352. (when (assoc var eql)
  3353. (user-error "Double formulas for %s" var))
  3354. (push (cons var form) eql))))
  3355. (set-window-configuration org-window-configuration)
  3356. (select-window sel-win)
  3357. (goto-char source)
  3358. (org-table-store-formulas eql)
  3359. (set-marker pos nil)
  3360. (set-marker source nil)
  3361. (kill-buffer "*Edit Formulas*")
  3362. (if arg
  3363. (org-table-recalculate 'all)
  3364. (message "New formulas installed - press C-u C-c C-c to apply."))))
  3365. (defun org-table-fedit-abort ()
  3366. "Abort editing formulas, without installing the changes."
  3367. (interactive)
  3368. (org-table-remove-rectangle-highlight)
  3369. (let ((pos org-pos) (sel-win org-selected-window))
  3370. (set-window-configuration org-window-configuration)
  3371. (select-window sel-win)
  3372. (goto-char pos)
  3373. (move-marker pos nil)
  3374. (message "Formula editing aborted without installing changes")))
  3375. (defun org-table-fedit-lisp-indent ()
  3376. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  3377. (interactive)
  3378. (let ((pos (point)) beg end ind)
  3379. (beginning-of-line 1)
  3380. (cond
  3381. ((looking-at "[ \t]")
  3382. (goto-char pos)
  3383. (call-interactively 'lisp-indent-line))
  3384. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  3385. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  3386. (goto-char (- (match-end 0) 2))
  3387. (setq beg (point))
  3388. (setq ind (make-string (current-column) ?\ ))
  3389. (condition-case nil (forward-sexp 1)
  3390. (error
  3391. (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  3392. (setq end (point))
  3393. (save-restriction
  3394. (narrow-to-region beg end)
  3395. (if (eq last-command this-command)
  3396. (progn
  3397. (goto-char (point-min))
  3398. (setq this-command nil)
  3399. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  3400. (replace-match " ")))
  3401. (pp-buffer)
  3402. (untabify (point-min) (point-max))
  3403. (goto-char (1+ (point-min)))
  3404. (while (re-search-forward "^." nil t)
  3405. (beginning-of-line 1)
  3406. (insert ind))
  3407. (goto-char (point-max))
  3408. (org-delete-backward-char 1)))
  3409. (goto-char beg))
  3410. (t nil))))
  3411. (defun org-table-fedit-line-up ()
  3412. "Move cursor one line up in the window showing the table."
  3413. (interactive)
  3414. (org-table-fedit-move 'previous-line))
  3415. (defun org-table-fedit-line-down ()
  3416. "Move cursor one line down in the window showing the table."
  3417. (interactive)
  3418. (org-table-fedit-move 'next-line))
  3419. (defun org-table-fedit-move (command)
  3420. "Move the cursor in the window showing the table.
  3421. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  3422. (let ((org-table-allow-automatic-line-recalculation nil)
  3423. (pos org-pos) (win (selected-window)) p)
  3424. (select-window (get-buffer-window (marker-buffer org-pos)))
  3425. (setq p (point))
  3426. (call-interactively command)
  3427. (while (and (org-at-table-p)
  3428. (org-at-table-hline-p))
  3429. (call-interactively command))
  3430. (or (org-at-table-p) (goto-char p))
  3431. (move-marker pos (point))
  3432. (select-window win)))
  3433. (defun org-table-fedit-scroll (N)
  3434. (interactive "p")
  3435. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  3436. (scroll-other-window N)))
  3437. (defun org-table-fedit-scroll-down (N)
  3438. (interactive "p")
  3439. (org-table-fedit-scroll (- N)))
  3440. (defun org-table-add-rectangle-overlay (beg end &optional face)
  3441. "Add a new overlay."
  3442. (let ((ov (make-overlay beg end)))
  3443. (overlay-put ov 'face (or face 'secondary-selection))
  3444. (push ov org-table-rectangle-overlays)))
  3445. (defun org-table-highlight-rectangle (&optional beg end face)
  3446. "Highlight rectangular region in a table.
  3447. When buffer positions BEG and END are provided, use them to
  3448. delimit the region to highlight. Otherwise, refer to point. Use
  3449. FACE, when non-nil, for the highlight."
  3450. (let* ((beg (or beg (point)))
  3451. (end (or end (point)))
  3452. (b (min beg end))
  3453. (e (max beg end))
  3454. (start-coordinates
  3455. (save-excursion
  3456. (goto-char b)
  3457. (cons (line-beginning-position) (org-table-current-column))))
  3458. (end-coordinates
  3459. (save-excursion
  3460. (goto-char e)
  3461. (cons (line-beginning-position) (org-table-current-column)))))
  3462. (when (boundp 'org-show-positions)
  3463. (setq org-show-positions (cons b (cons e org-show-positions))))
  3464. (goto-char (car start-coordinates))
  3465. (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
  3466. (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
  3467. (last-row (car end-coordinates)))
  3468. (while (<= (point) last-row)
  3469. (when (looking-at org-table-dataline-regexp)
  3470. (org-table-goto-column column-start)
  3471. (skip-chars-backward "^|\n")
  3472. (let ((p (point)))
  3473. (org-table-goto-column column-end)
  3474. (skip-chars-forward "^|\n")
  3475. (org-table-add-rectangle-overlay p (point) face)))
  3476. (forward-line)))
  3477. (goto-char (car start-coordinates)))
  3478. (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
  3479. (defun org-table-remove-rectangle-highlight (&rest _ignore)
  3480. "Remove the rectangle overlays."
  3481. (unless org-inhibit-highlight-removal
  3482. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  3483. (mapc 'delete-overlay org-table-rectangle-overlays)
  3484. (setq org-table-rectangle-overlays nil)))
  3485. (defvar-local org-table-coordinate-overlays nil
  3486. "Collects the coordinate grid overlays, so that they can be removed.")
  3487. (defun org-table-overlay-coordinates ()
  3488. "Add overlays to the table at point, to show row/column coordinates."
  3489. (interactive)
  3490. (mapc 'delete-overlay org-table-coordinate-overlays)
  3491. (setq org-table-coordinate-overlays nil)
  3492. (save-excursion
  3493. (let ((id 0) (ih 0) hline eol str ov)
  3494. (goto-char (org-table-begin))
  3495. (while (org-at-table-p)
  3496. (setq eol (point-at-eol))
  3497. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  3498. (push ov org-table-coordinate-overlays)
  3499. (setq hline (looking-at org-table-hline-regexp))
  3500. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  3501. (format "%4d" (setq id (1+ id)))))
  3502. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  3503. (when hline
  3504. (let ((ic 0))
  3505. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  3506. (cl-incf ic)
  3507. (let* ((beg (1+ (match-beginning 0)))
  3508. (s1 (format "$%d" ic))
  3509. (s2 (org-number-to-letters ic))
  3510. (str (if (eq t org-table-use-standard-references) s2 s1))
  3511. (ov (make-overlay beg (+ beg (length str)))))
  3512. (push ov org-table-coordinate-overlays)
  3513. (org-overlay-display ov str 'org-special-keyword 'evaporate)))))
  3514. (forward-line)))))
  3515. ;;;###autoload
  3516. (defun org-table-toggle-coordinate-overlays ()
  3517. "Toggle the display of Row/Column numbers in tables."
  3518. (interactive)
  3519. (if (not (org-at-table-p))
  3520. (user-error "Not on a table")
  3521. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  3522. (when (and (org-at-table-p) org-table-overlay-coordinates)
  3523. (org-table-align))
  3524. (unless org-table-overlay-coordinates
  3525. (mapc 'delete-overlay org-table-coordinate-overlays)
  3526. (setq org-table-coordinate-overlays nil))
  3527. (message "Tables Row/Column numbers display turned %s"
  3528. (if org-table-overlay-coordinates "on" "off"))))
  3529. ;;;###autoload
  3530. (defun org-table-toggle-formula-debugger ()
  3531. "Toggle the formula debugger in tables."
  3532. (interactive)
  3533. (setq org-table-formula-debug (not org-table-formula-debug))
  3534. (message "Formula debugging has been turned %s"
  3535. (if org-table-formula-debug "on" "off")))
  3536. ;;; Columns Shrinking
  3537. (defun org-table--shrunk-field ()
  3538. "Non-nil if current field is narrowed.
  3539. When non-nil, return the overlay narrowing the field."
  3540. (cl-some (lambda (o)
  3541. (and (eq 'table-column-hide (overlay-get o 'org-overlay-type))
  3542. o))
  3543. (overlays-at (save-excursion
  3544. (skip-chars-forward (if (org-at-table-hline-p) "^+|"
  3545. "^|")
  3546. (line-end-position))
  3547. (1- (point))))))
  3548. (defun org-table--list-shrunk-columns ()
  3549. "List currently shrunk columns in table at point."
  3550. (save-excursion
  3551. ;; We really check shrunk columns in current row only. It could
  3552. ;; be wrong if all rows do not contain the same number of columns
  3553. ;; (i.e. the table is not properly aligned). As a consequence,
  3554. ;; some columns may not be shrunk again upon aligning the table.
  3555. ;;
  3556. ;; For example, in the following table, cursor is on first row and
  3557. ;; "<>" indicates a shrunk column.
  3558. ;;
  3559. ;; | |
  3560. ;; | | <> |
  3561. ;;
  3562. ;; Aligning table from the first row will not shrink again the
  3563. ;; second row, which was not visible initially.
  3564. ;;
  3565. ;; However, fixing it requires to check every row, which may be
  3566. ;; slow on large tables. Moreover, the hindrance of this
  3567. ;; pathological case is very limited.
  3568. (beginning-of-line)
  3569. (search-forward "|")
  3570. (let ((separator (if (org-at-table-hline-p) "+" "|"))
  3571. (column 1)
  3572. (shrunk (and (org-table--shrunk-field) (list 1)))
  3573. (end (line-end-position)))
  3574. (while (search-forward separator end t)
  3575. (cl-incf column)
  3576. (when (org-table--shrunk-field) (push column shrunk)))
  3577. (nreverse shrunk))))
  3578. (defun org-table--make-shrinking-overlay (start end display field &optional pre)
  3579. "Create an overlay to shrink text between START and END.
  3580. Use string DISPLAY instead of the real text between the two
  3581. buffer positions. FIELD is the real contents of the field, as
  3582. a string, or nil. It is meant to be displayed upon moving the
  3583. mouse onto the overlay.
  3584. When optional argument PRE is non-nil, assume the overlay is
  3585. located at the beginning of the field, and prepend
  3586. `org-table-separator-space' to it. Otherwise, concatenate
  3587. `org-table-shrunk-column-indicator' at its end.
  3588. Return the overlay."
  3589. (let ((show-before-edit
  3590. (lambda (o &rest _)
  3591. ;; Removing one overlay removes all other overlays in the
  3592. ;; same column.
  3593. (mapc #'delete-overlay
  3594. (cdr (overlay-get o 'org-table-column-overlays)))))
  3595. (o (make-overlay start end)))
  3596. (overlay-put o 'insert-behind-hooks (list show-before-edit))
  3597. (overlay-put o 'insert-in-front-hooks (list show-before-edit))
  3598. (overlay-put o 'modification-hooks (list show-before-edit))
  3599. (overlay-put o 'org-overlay-type 'table-column-hide)
  3600. (when (stringp field) (overlay-put o 'help-echo field))
  3601. ;; Make sure overlays stays on top of table coordinates overlays.
  3602. ;; See `org-table-overlay-coordinates'.
  3603. (overlay-put o 'priority 1)
  3604. (let ((d (if pre (concat org-table-separator-space display)
  3605. (concat display org-table-shrunk-column-indicator))))
  3606. (org-overlay-display o d 'org-table t))
  3607. o))
  3608. (defun org-table--shrink-field (width align start end contents)
  3609. "Shrink a table field to a specified width.
  3610. WIDTH is an integer representing the number of characters to
  3611. display, in addition to `org-table-shrunk-column-indicator'.
  3612. ALIGN is the alignment of the current column, as either \"l\",
  3613. \"c\" or \"r\". START and END are, respectively, the beginning
  3614. and ending positions of the field. CONTENTS is its trimmed
  3615. contents, as a string, or `hline' for table rules.
  3616. Real field is hidden under one or two overlays. They have the
  3617. following properties:
  3618. `org-overlay-type'
  3619. Set to `table-column-hide'. Used to identify overlays
  3620. responsible for shrinking columns in a table.
  3621. `org-table-column-overlays'
  3622. It is a list with the pattern (siblings . COLUMN-OVERLAYS)
  3623. where COLUMN-OVERLAYS is the list of all overlays hiding the
  3624. same column.
  3625. Whenever the text behind or next to the overlay is modified, all
  3626. the overlays in the column are deleted, effectively displaying
  3627. the column again.
  3628. Return a list of overlays hiding the field, or nil if field is
  3629. already hidden."
  3630. (cond
  3631. ((= start end) nil) ;no field to narrow
  3632. ((org-table--shrunk-field) nil) ;already shrunk
  3633. ((= 0 width) ;shrink to one character
  3634. (list (org-table--make-shrinking-overlay
  3635. start end "" (if (eq 'hline contents) "" contents))))
  3636. ((eq contents 'hline)
  3637. (list (org-table--make-shrinking-overlay
  3638. start end (make-string (1+ width) ?-) "")))
  3639. ((equal contents "") ;no contents to hide
  3640. (list
  3641. (let ((w (org-string-width (buffer-substring start end)))
  3642. ;; We really want WIDTH + 2 whitespace, to include blanks
  3643. ;; around fields.
  3644. (full (+ 2 width)))
  3645. (if (<= w full)
  3646. (org-table--make-shrinking-overlay
  3647. (1- end) end (make-string (- full w) ?\s) "")
  3648. (org-table--make-shrinking-overlay (- end (- w full) 1) end "" "")))))
  3649. (t
  3650. ;; If the field is not empty, display exactly WIDTH characters.
  3651. ;; It can mean to partly hide the field, or extend it with virtual
  3652. ;; blanks. To that effect, we use one or two overlays. The
  3653. ;; first, optional, one may add or hide white spaces before the
  3654. ;; contents of the field. The other, mandatory, one cuts the
  3655. ;; field or displays white spaces at the end of the field. It
  3656. ;; also always displays `org-table-shrunk-column-indicator'.
  3657. (let* ((lead (org-with-point-at start (skip-chars-forward " ")))
  3658. (trail (org-with-point-at end (abs (skip-chars-backward " "))))
  3659. (contents-width (org-string-width
  3660. (buffer-substring (+ start lead) (- end trail)))))
  3661. (cond
  3662. ;; Contents are too large to fit in WIDTH character. Limit, if
  3663. ;; possible, blanks at the beginning of the field to a single
  3664. ;; white space, and cut the field at an appropriate location.
  3665. ((<= width contents-width)
  3666. (let ((pre
  3667. (and (> lead 0)
  3668. (org-table--make-shrinking-overlay
  3669. start (+ start lead) "" contents t)))
  3670. (post
  3671. (org-table--make-shrinking-overlay
  3672. ;; Find cut location so that WIDTH characters are
  3673. ;; visible using dichotomy.
  3674. (let* ((begin (+ start lead))
  3675. (lower begin)
  3676. (upper (1- end))
  3677. ;; Compensate the absence of leading space,
  3678. ;; thus preserving alignment.
  3679. (width (if (= lead 0) (1+ width) width)))
  3680. (catch :exit
  3681. (while (> (- upper lower) 1)
  3682. (let ((mean (+ (ash lower -1)
  3683. (ash upper -1)
  3684. (logand lower upper 1))))
  3685. (pcase (org-string-width (buffer-substring begin mean))
  3686. ((pred (= width)) (throw :exit mean))
  3687. ((pred (< width)) (setq upper mean))
  3688. (_ (setq lower mean)))))
  3689. upper))
  3690. end "" contents)))
  3691. (if pre (list pre post) (list post))))
  3692. ;; Contents fit it WIDTH characters. First compute number of
  3693. ;; white spaces needed on each side of contents, then expand or
  3694. ;; compact blanks on each side of the field in order to
  3695. ;; preserve width and obey to alignment constraints.
  3696. (t
  3697. (let* ((required (- width contents-width))
  3698. (before
  3699. (pcase align
  3700. ;; Compensate the absence of leading space, thus
  3701. ;; preserving alignment.
  3702. ((guard (= lead 0)) -1)
  3703. ("l" 0)
  3704. ("r" required)
  3705. ("c" (/ required 2))))
  3706. (after (- required before))
  3707. (pre
  3708. (pcase (1- lead)
  3709. ((or (guard (= lead 0)) (pred (= before))) nil)
  3710. ((pred (< before))
  3711. (org-table--make-shrinking-overlay
  3712. start (+ start (- lead before)) "" contents t))
  3713. (_
  3714. (org-table--make-shrinking-overlay
  3715. start (1+ start)
  3716. (make-string (- before (1- lead)) ?\s)
  3717. contents t))))
  3718. (post
  3719. (pcase (1- trail)
  3720. ((pred (= after))
  3721. (org-table--make-shrinking-overlay (1- end) end "" contents))
  3722. ((pred (< after))
  3723. (org-table--make-shrinking-overlay
  3724. (+ after (- end trail)) end "" contents))
  3725. (_
  3726. (org-table--make-shrinking-overlay
  3727. (1- end) end
  3728. (make-string (- after (1- trail)) ?\s)
  3729. contents)))))
  3730. (if pre (list pre post) (list post)))))))))
  3731. (defun org-table--read-column-selection (select max)
  3732. "Read column selection select as a list of numbers.
  3733. SELECT is a string containing column ranges, separated by white
  3734. space characters, see `org-table-hide-column' for details. MAX
  3735. is the maximum column number.
  3736. Return value is a sorted list of numbers. Ignore any number
  3737. outside of the [1;MAX] range."
  3738. (catch :all
  3739. (sort
  3740. (delete-dups
  3741. (cl-mapcan
  3742. (lambda (s)
  3743. (cond
  3744. ((member s '("-" "1-")) (throw :all (number-sequence 1 max)))
  3745. ((string-match-p "\\`[0-9]+\\'" s)
  3746. (let ((n (string-to-number s)))
  3747. (and (> n 0) (<= n max) (list n))))
  3748. ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s)
  3749. (let ((n (match-string 1 s))
  3750. (m (match-string 2 s)))
  3751. (number-sequence (if n (max 1 (string-to-number n))
  3752. 1)
  3753. (if m (min max (string-to-number m))
  3754. max))))
  3755. (t nil))) ;invalid specification
  3756. (split-string select)))
  3757. #'<)))
  3758. (defun org-table--shrink-columns (columns beg end)
  3759. "Shrink COLUMNS in a table.
  3760. COLUMNS is a sorted list of column numbers. BEG and END are,
  3761. respectively, the beginning position and the end position of the
  3762. table."
  3763. (org-with-wide-buffer
  3764. (org-font-lock-ensure beg end)
  3765. (dolist (c columns)
  3766. (goto-char beg)
  3767. (let ((align nil)
  3768. (width nil)
  3769. (fields nil))
  3770. (while (< (point) end)
  3771. (catch :continue
  3772. (let* ((hline? (org-at-table-hline-p))
  3773. (separator (if hline? "+" "|")))
  3774. ;; Move to COLUMN.
  3775. (search-forward "|")
  3776. (or (= c 1) ;already there
  3777. (search-forward separator (line-end-position) t (1- c))
  3778. (throw :continue nil)) ;skip invalid columns
  3779. ;; Extract boundaries and contents from current field.
  3780. ;; Also set the column's width if we encounter a width
  3781. ;; cookie for the first time.
  3782. (let* ((start (point))
  3783. (end (progn
  3784. (skip-chars-forward (concat "^|" separator)
  3785. (line-end-position))
  3786. (point)))
  3787. (contents (if hline? 'hline
  3788. (org-trim (buffer-substring start end)))))
  3789. (push (list start end contents) fields)
  3790. (when (and (not hline?)
  3791. (string-match "\\`<\\([lrc]\\)?\\([0-9]+\\)>\\'"
  3792. contents))
  3793. (unless align (setq align (match-string 1 contents)))
  3794. (unless width
  3795. (setq width (string-to-number (match-string 2 contents))))))))
  3796. (forward-line))
  3797. ;; Link overlays for current field to the other overlays in the
  3798. ;; same column.
  3799. (let ((chain (list 'siblings)))
  3800. (dolist (field fields)
  3801. (dolist (new (apply #'org-table--shrink-field
  3802. (or width 0) (or align "l") field))
  3803. (push new (cdr chain))
  3804. (overlay-put new 'org-table-column-overlays chain))))))))
  3805. ;;;###autoload
  3806. (defun org-table-toggle-column-width (&optional arg)
  3807. "Shrink or expand current column in an Org table.
  3808. If a width cookie specifies a width W for the column, the first
  3809. W visible characters are displayed. Otherwise, the column is
  3810. shrunk to a single character.
  3811. When point is before the first column or after the last one, ask
  3812. for the columns to shrink or expand, as a list of ranges.
  3813. A column range can be one of the following patterns:
  3814. N column N only
  3815. N-M every column between N and M (both inclusive)
  3816. N- every column between N (inclusive) and the last column
  3817. -M every column between the first one and M (inclusive)
  3818. - every column
  3819. When optional argument ARG is a string, use it as white space
  3820. separated list of column ranges.
  3821. When called with `\\[universal-argument]' prefix, call \
  3822. `org-table-shrink', i.e.,
  3823. shrink columns with a width cookie and expand the others.
  3824. When called with `\\[universal-argument] \\[universal-argument]' \
  3825. prefix, expand all columns."
  3826. (interactive "P")
  3827. (unless (org-at-table-p) (user-error "Not in a table"))
  3828. (let* ((begin (org-table-begin))
  3829. (end (org-table-end))
  3830. ;; Compute an upper bound for the number of columns.
  3831. ;; Nonexistent columns are ignored anyway.
  3832. (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
  3833. (shrunk (org-table--list-shrunk-columns))
  3834. (columns
  3835. (pcase arg
  3836. (`nil
  3837. (if (save-excursion
  3838. (skip-chars-backward "^|" (line-beginning-position))
  3839. (or (bolp) (looking-at-p "[ \t]*$")))
  3840. ;; Point is either before first column or past last
  3841. ;; one. Ask for columns to operate on.
  3842. (org-table--read-column-selection
  3843. (read-string "Column ranges (e.g. 2-4 6-): ")
  3844. max-columns)
  3845. (list (org-table-current-column))))
  3846. ((pred stringp) (org-table--read-column-selection arg max-columns))
  3847. ((or `(4) `(16)) nil)
  3848. (_ (user-error "Invalid argument: %S" arg)))))
  3849. (pcase arg
  3850. (`(4) (org-table-shrink begin end))
  3851. (`(16) (org-table-expand begin end))
  3852. (_
  3853. (org-table-expand begin end)
  3854. (org-table--shrink-columns
  3855. (cl-set-exclusive-or columns shrunk) begin end)))))
  3856. ;;;###autoload
  3857. (defun org-table-shrink (&optional begin end)
  3858. "Shrink all columns with a width cookie in the table at point.
  3859. Columns without a width cookie are expanded.
  3860. Optional arguments BEGIN and END, when non-nil, specify the
  3861. beginning and end position of the current table."
  3862. (interactive)
  3863. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3864. (org-with-wide-buffer
  3865. (let ((begin (or begin (org-table-begin)))
  3866. (end (or end (org-table-end)))
  3867. (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
  3868. (columns))
  3869. (goto-char begin)
  3870. (while (re-search-forward regexp end t)
  3871. (goto-char (match-beginning 1))
  3872. (cl-pushnew (org-table-current-column) columns))
  3873. (org-table-expand begin end)
  3874. ;; Make sure invisible characters in the table are at the right
  3875. ;; place since column widths take them into account.
  3876. (org-font-lock-ensure begin end)
  3877. (org-table--shrink-columns (sort columns #'<) begin end))))
  3878. ;;;###autoload
  3879. (defun org-table-expand (&optional begin end)
  3880. "Expand all columns in the table at point.
  3881. Optional arguments BEGIN and END, when non-nil, specify the
  3882. beginning and end position of the current table."
  3883. (interactive)
  3884. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3885. (org-with-wide-buffer
  3886. (let ((begin (or begin (org-table-begin)))
  3887. (end (or end (org-table-end))))
  3888. (remove-overlays begin end 'org-overlay-type 'table-column-hide))))
  3889. ;;; Generic Tools
  3890. ;;;###autoload
  3891. (defun org-table-map-tables (f &optional quietly)
  3892. "Apply function F to the start of all tables in the buffer."
  3893. (org-with-point-at 1
  3894. (while (re-search-forward org-table-line-regexp nil t)
  3895. (let ((table (org-element-lineage (org-element-at-point) '(table) t)))
  3896. (when table
  3897. (unless quietly
  3898. (message "Mapping tables: %d%%"
  3899. (floor (* 100.0 (point)) (buffer-size))))
  3900. (goto-char (org-element-property :post-affiliated table))
  3901. (let ((end (copy-marker (org-element-property :end table))))
  3902. (unwind-protect
  3903. (progn (funcall f) (goto-char end))
  3904. (set-marker end nil)))))))
  3905. (unless quietly (message "Mapping tables: done")))
  3906. ;;;###autoload
  3907. (defun org-table-export (&optional file format)
  3908. "Export table to a file, with configurable format.
  3909. Such a file can be imported into usual spreadsheet programs.
  3910. FILE can be the output file name. If not given, it will be taken
  3911. from a TABLE_EXPORT_FILE property in the current entry or higher
  3912. up in the hierarchy, or the user will be prompted for a file
  3913. name. FORMAT can be an export format, of the same kind as it
  3914. used when `-mode' sends a table in a different format.
  3915. The command suggests a format depending on TABLE_EXPORT_FORMAT,
  3916. whether it is set locally or up in the hierarchy, then on the
  3917. extension of the given file name, and finally on the variable
  3918. `org-table-export-default-format'."
  3919. (interactive)
  3920. (unless (org-at-table-p) (user-error "No table at point"))
  3921. (org-table-align) ; Make sure we have everything we need.
  3922. (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
  3923. (unless file
  3924. (setq file (read-file-name "Export table to: "))
  3925. (unless (or (not (file-exists-p file))
  3926. (y-or-n-p (format "Overwrite file %s? " file)))
  3927. (user-error "File not written")))
  3928. (when (file-directory-p file)
  3929. (user-error "This is a directory path, not a file"))
  3930. (when (and (buffer-file-name (buffer-base-buffer))
  3931. (file-equal-p
  3932. (file-truename file)
  3933. (file-truename (buffer-file-name (buffer-base-buffer)))))
  3934. (user-error "Please specify a file name that is different from current"))
  3935. (let ((fileext (concat (file-name-extension file) "$"))
  3936. (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
  3937. (unless format
  3938. (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
  3939. "orgtbl-to-html" "orgtbl-to-generic"
  3940. "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
  3941. "orgtbl-to-unicode"))
  3942. (deffmt-readable
  3943. (replace-regexp-in-string
  3944. "\t" "\\t"
  3945. (replace-regexp-in-string
  3946. "\n" "\\n"
  3947. (or (car (delq nil
  3948. (mapcar
  3949. (lambda (f)
  3950. (and (string-match-p fileext f) f))
  3951. formats)))
  3952. org-table-export-default-format)
  3953. t t)
  3954. t t)))
  3955. (setq format
  3956. (org-completing-read
  3957. "Format: " formats nil nil deffmt-readable))))
  3958. (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
  3959. (let ((transform (intern (match-string 1 format)))
  3960. (params (and (match-end 2)
  3961. (read (concat "(" (match-string 2 format) ")"))))
  3962. (table (org-table-to-lisp)))
  3963. (unless (fboundp transform)
  3964. (user-error "No such transformation function %s" transform))
  3965. (let (buf)
  3966. (with-current-buffer (find-file-noselect file)
  3967. (setq buf (current-buffer))
  3968. (erase-buffer)
  3969. (fundamental-mode)
  3970. (insert (funcall transform table params) "\n")
  3971. (save-buffer))
  3972. (kill-buffer buf))
  3973. (message "Export done."))
  3974. (user-error "TABLE_EXPORT_FORMAT invalid")))))
  3975. ;;;###autoload
  3976. (defun org-table--align-field (field width align)
  3977. "Format FIELD according to column WIDTH and alignment ALIGN.
  3978. FIELD is a string. WIDTH is a number. ALIGN is either \"c\",
  3979. \"l\" or\"r\"."
  3980. (let* ((spaces (- width (org-string-width field)))
  3981. (prefix (pcase align
  3982. ("l" "")
  3983. ("r" (make-string spaces ?\s))
  3984. ("c" (make-string (/ spaces 2) ?\s))))
  3985. (suffix (make-string (- spaces (length prefix)) ?\s)))
  3986. (concat org-table-separator-space
  3987. prefix
  3988. field
  3989. suffix
  3990. org-table-separator-space)))
  3991. (defun org-table-align ()
  3992. "Align the table at point by aligning all vertical bars."
  3993. (interactive)
  3994. (let ((beg (org-table-begin))
  3995. (end (copy-marker (org-table-end))))
  3996. (org-table-save-field
  3997. ;; Make sure invisible characters in the table are at the right
  3998. ;; place since column widths take them into account.
  3999. (org-font-lock-ensure beg end)
  4000. (move-marker org-table-aligned-begin-marker beg)
  4001. (move-marker org-table-aligned-end-marker end)
  4002. (goto-char beg)
  4003. (org-table-with-shrunk-columns
  4004. (let* ((table (org-table-to-lisp))
  4005. (rows (remq 'hline table))
  4006. (widths nil)
  4007. (alignments nil)
  4008. (columns-number 1))
  4009. (if (null rows)
  4010. ;; Table contains only horizontal rules. Compute the
  4011. ;; number of columns anyway, and choose an arbitrary width
  4012. ;; and alignment.
  4013. (let ((end (line-end-position)))
  4014. (save-excursion
  4015. (while (search-forward "+" end t)
  4016. (cl-incf columns-number)))
  4017. (setq widths (make-list columns-number 1))
  4018. (setq alignments (make-list columns-number "l")))
  4019. ;; Compute alignment and width for each column.
  4020. (setq columns-number (apply #'max (mapcar #'length rows)))
  4021. (dotimes (i columns-number)
  4022. (let ((max-width 1)
  4023. (fixed-align? nil)
  4024. (numbers 0)
  4025. (non-empty 0))
  4026. (dolist (row rows)
  4027. (let ((cell (or (nth i row) "")))
  4028. (setq max-width (max max-width (org-string-width cell)))
  4029. (cond (fixed-align? nil)
  4030. ((equal cell "") nil)
  4031. ((string-match "\\`<\\([lrc]\\)[0-9]*>\\'" cell)
  4032. (setq fixed-align? (match-string 1 cell)))
  4033. (t
  4034. (cl-incf non-empty)
  4035. (when (string-match-p org-table-number-regexp cell)
  4036. (cl-incf numbers))))))
  4037. (push max-width widths)
  4038. (push (cond
  4039. (fixed-align?)
  4040. ((>= numbers (* org-table-number-fraction non-empty)) "r")
  4041. (t "l"))
  4042. alignments)))
  4043. (setq widths (nreverse widths))
  4044. (setq alignments (nreverse alignments)))
  4045. ;; Store alignment of this table, for later editing of single
  4046. ;; fields.
  4047. (setq org-table-last-alignment alignments)
  4048. (setq org-table-last-column-widths widths)
  4049. ;; Build new table rows. Only replace rows that actually
  4050. ;; changed.
  4051. (let ((rule (and (memq 'hline table)
  4052. (mapconcat (lambda (w) (make-string (+ 2 w) ?-))
  4053. widths
  4054. "+")))
  4055. (indent (progn (looking-at "[ \t]*|") (match-string 0))))
  4056. (dolist (row table)
  4057. (let ((previous (buffer-substring (point) (line-end-position)))
  4058. (new
  4059. (concat indent
  4060. (if (eq row 'hline) rule
  4061. (let* ((offset (- columns-number (length row)))
  4062. (fields (if (= 0 offset) row
  4063. ;; Add missing fields.
  4064. (append row
  4065. (make-list offset "")))))
  4066. (mapconcat #'identity
  4067. (cl-mapcar #'org-table--align-field
  4068. fields
  4069. widths
  4070. alignments)
  4071. "|")))
  4072. "|")))
  4073. (if (equal new previous)
  4074. (forward-line)
  4075. (insert new "\n")
  4076. (delete-region (point) (line-beginning-position 2))))))
  4077. (set-marker end nil)
  4078. (when org-table-overlay-coordinates (org-table-overlay-coordinates))
  4079. (setq org-table-may-need-update nil))))))
  4080. ;;;###autoload
  4081. (defun org-table-justify-field-maybe (&optional new)
  4082. "Justify the current field, text to left, number to right.
  4083. Optional argument NEW may specify text to replace the current field content."
  4084. (cond
  4085. ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
  4086. ((org-at-table-hline-p))
  4087. ((and (not new)
  4088. (or (not (eq (marker-buffer org-table-aligned-begin-marker)
  4089. (current-buffer)))
  4090. (< (point) org-table-aligned-begin-marker)
  4091. (>= (point) org-table-aligned-end-marker)))
  4092. ;; This is not the same table, force a full re-align.
  4093. (setq org-table-may-need-update t))
  4094. (t
  4095. ;; Realign the current field, based on previous full realign.
  4096. (let ((pos (point))
  4097. (col (org-table-current-column)))
  4098. (when (> col 0)
  4099. (skip-chars-backward "^|")
  4100. (if (not (looking-at " *\\(?:\\([^|\n]*?\\) *\\(|\\)\\|\\([^|\n]+?\\) *\\($\\)\\)"))
  4101. (setq org-table-may-need-update t)
  4102. (let* ((align (nth (1- col) org-table-last-alignment))
  4103. (width (nth (1- col) org-table-last-column-widths))
  4104. (cell (match-string 0))
  4105. (field (match-string 1))
  4106. (properly-closed? (/= (match-beginning 2) (match-end 2)))
  4107. (new-cell
  4108. (save-match-data
  4109. (cond (org-table-may-need-update
  4110. (format " %s |" (or new field)))
  4111. ((not properly-closed?)
  4112. (setq org-table-may-need-update t)
  4113. (format " %s |" (or new field)))
  4114. ((not new)
  4115. (concat (org-table--align-field field width align)
  4116. "|"))
  4117. ((and width (<= (org-string-width new) width))
  4118. (concat (org-table--align-field new width align)
  4119. "|"))
  4120. (t
  4121. (setq org-table-may-need-update t)
  4122. (format " %s |" new))))))
  4123. (unless (equal new-cell cell)
  4124. (let (org-table-may-need-update)
  4125. (replace-match new-cell t t)))
  4126. (goto-char pos))))))))
  4127. ;;;###autoload
  4128. (defun org-table-sort-lines
  4129. (&optional with-case sorting-type getkey-func compare-func interactive?)
  4130. "Sort table lines according to the column at point.
  4131. The position of point indicates the column to be used for
  4132. sorting, and the range of lines is the range between the nearest
  4133. horizontal separator lines, or the entire table of no such lines
  4134. exist. If point is before the first column, you will be prompted
  4135. for the sorting column. If there is an active region, the mark
  4136. specifies the first line and the sorting column, while point
  4137. should be in the last line to be included into the sorting.
  4138. The command then prompts for the sorting type which can be
  4139. alphabetically, numerically, or by time (as given in a time stamp
  4140. in the field, or as a HH:MM value). Sorting in reverse order is
  4141. also possible.
  4142. With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive
  4143. if the locale allows for it.
  4144. If SORTING-TYPE is specified when this function is called from a Lisp
  4145. program, no prompting will take place. SORTING-TYPE must be a character,
  4146. any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
  4147. sorting should be done in reverse order.
  4148. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
  4149. a function to be called to extract the key. It must return a value
  4150. that is compatible with COMPARE-FUNC, the function used to compare
  4151. entries.
  4152. A non-nil value for INTERACTIVE? is used to signal that this
  4153. function is being called interactively."
  4154. (interactive (list current-prefix-arg nil nil nil t))
  4155. (when (org-region-active-p) (goto-char (region-beginning)))
  4156. ;; Point must be either within a field or before a data line.
  4157. (save-excursion
  4158. (skip-chars-backward " \t")
  4159. (when (bolp) (search-forward "|" (line-end-position) t))
  4160. (org-table-check-inside-data-field))
  4161. ;; Set appropriate case sensitivity and column used for sorting.
  4162. (let ((column (let ((c (org-table-current-column)))
  4163. (cond ((> c 0) c)
  4164. (interactive?
  4165. (read-number "Use column N for sorting: "))
  4166. (t 1))))
  4167. (sorting-type
  4168. (or sorting-type
  4169. (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
  4170. \[t]ime, [f]unc. A/N/T/F means reversed: ")))
  4171. (start (org-table-begin))
  4172. (end (org-table-end)))
  4173. (save-restriction
  4174. ;; Narrow buffer to appropriate sorting area.
  4175. (if (org-region-active-p)
  4176. (progn (goto-char (region-beginning))
  4177. (narrow-to-region
  4178. (point)
  4179. (save-excursion (goto-char (region-end))
  4180. (line-beginning-position 2))))
  4181. (narrow-to-region
  4182. (save-excursion
  4183. (if (re-search-backward org-table-hline-regexp start t)
  4184. (line-beginning-position 2)
  4185. start))
  4186. (if (save-excursion (re-search-forward org-table-hline-regexp end t))
  4187. (match-beginning 0)
  4188. end)))
  4189. ;; Determine arguments for `sort-subr'. Also record original
  4190. ;; position. `org-table-save-field' cannot help here since
  4191. ;; sorting is too much destructive.
  4192. (let* ((coordinates
  4193. (cons (count-lines (point-min) (line-beginning-position))
  4194. (current-column)))
  4195. (extract-key-from-field
  4196. ;; Function to be called on the contents of the field
  4197. ;; used for sorting in the current row.
  4198. (cl-case sorting-type
  4199. ((?n ?N) #'string-to-number)
  4200. ((?a ?A) #'org-sort-remove-invisible)
  4201. ((?t ?T)
  4202. (lambda (f)
  4203. (cond ((string-match org-ts-regexp-both f)
  4204. (float-time
  4205. (org-time-string-to-time (match-string 0 f))))
  4206. ((org-duration-p f) (org-duration-to-minutes f))
  4207. ((string-match "\\<[0-9]+:[0-9]\\{2\\}\\>" f)
  4208. (org-duration-to-minutes (match-string 0 f)))
  4209. (t 0))))
  4210. ((?f ?F)
  4211. (or getkey-func
  4212. (and interactive?
  4213. (org-read-function "Function for extracting keys: "))
  4214. (error "Missing key extractor to sort rows")))
  4215. (t (user-error "Invalid sorting type `%c'" sorting-type))))
  4216. (predicate
  4217. (cl-case sorting-type
  4218. ((?n ?N ?t ?T) #'<)
  4219. ((?a ?A) (if with-case #'string-collate-lessp
  4220. (lambda (s1 s2) (string-collate-lessp s1 s2 nil t))))
  4221. ((?f ?F)
  4222. (or compare-func
  4223. (and interactive?
  4224. (org-read-function
  4225. "Function for comparing keys (empty for default \
  4226. `sort-subr' predicate): "
  4227. 'allow-empty))))))
  4228. (shrunk-columns (remq column (org-table--list-shrunk-columns))))
  4229. (goto-char (point-min))
  4230. (sort-subr (memq sorting-type '(?A ?N ?T ?F))
  4231. (lambda ()
  4232. (forward-line)
  4233. (while (and (not (eobp))
  4234. (not (looking-at org-table-dataline-regexp)))
  4235. (forward-line)))
  4236. #'end-of-line
  4237. (lambda ()
  4238. (funcall extract-key-from-field
  4239. (org-trim (org-table-get-field column))))
  4240. nil
  4241. predicate)
  4242. ;; Hide all columns but the one being sorted.
  4243. (org-table--shrink-columns shrunk-columns start end)
  4244. ;; Move back to initial field.
  4245. (forward-line (car coordinates))
  4246. (move-to-column (cdr coordinates))))))
  4247. (defun org-table-transpose-table-at-point ()
  4248. "Transpose Org table at point and eliminate hlines.
  4249. So a table like
  4250. | 1 | 2 | 4 | 5 |
  4251. |---+---+---+---|
  4252. | a | b | c | d |
  4253. | e | f | g | h |
  4254. will be transposed as
  4255. | 1 | a | e |
  4256. | 2 | b | f |
  4257. | 4 | c | g |
  4258. | 5 | d | h |
  4259. Note that horizontal lines disappear."
  4260. (interactive)
  4261. (let* ((table (delete 'hline (org-table-to-lisp)))
  4262. (dline_old (org-table-current-line))
  4263. (col_old (org-table-current-column))
  4264. (contents (mapcar (lambda (_)
  4265. (let ((tp table))
  4266. (mapcar
  4267. (lambda (_)
  4268. (prog1
  4269. (pop (car tp))
  4270. (setq tp (cdr tp))))
  4271. table)))
  4272. (car table))))
  4273. (goto-char (org-table-begin))
  4274. (re-search-forward "|")
  4275. (backward-char)
  4276. (delete-region (point) (org-table-end))
  4277. (insert (mapconcat
  4278. (lambda(x)
  4279. (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
  4280. contents ""))
  4281. (org-table-goto-line col_old)
  4282. (org-table-goto-column dline_old))
  4283. (org-table-align))
  4284. ;;;###autoload
  4285. (defun org-table-wrap-region (arg)
  4286. "Wrap several fields in a column like a paragraph.
  4287. This is useful if you'd like to spread the contents of a field over several
  4288. lines, in order to keep the table compact.
  4289. If there is an active region, and both point and mark are in the same column,
  4290. the text in the column is wrapped to minimum width for the given number of
  4291. lines. Generally, this makes the table more compact. A prefix ARG may be
  4292. used to change the number of desired lines. For example, \
  4293. `C-2 \\[org-table-wrap-region]'
  4294. formats the selected text to two lines. If the region was longer than two
  4295. lines, the remaining lines remain empty. A negative prefix argument reduces
  4296. the current number of lines by that amount. The wrapped text is pasted back
  4297. into the table. If you formatted it to more lines than it was before, fields
  4298. further down in the table get overwritten - so you might need to make space in
  4299. the table first.
  4300. If there is no region, the current field is split at the cursor position and
  4301. the text fragment to the right of the cursor is prepended to the field one
  4302. line down.
  4303. If there is no region, but you specify a prefix ARG, the current field gets
  4304. blank, and the content is appended to the field above."
  4305. (interactive "P")
  4306. (org-table-check-inside-data-field)
  4307. (if (org-region-active-p)
  4308. ;; There is a region: fill as a paragraph.
  4309. (let ((start (region-beginning)))
  4310. (save-restriction
  4311. (narrow-to-region
  4312. (save-excursion (goto-char start) (move-beginning-of-line 1))
  4313. (save-excursion (org-forward-paragraph) (point)))
  4314. (org-table-cut-region (region-beginning) (region-end))
  4315. (when (> (length (car org-table-clip)) 1)
  4316. (user-error "Region must be limited to single column"))
  4317. (let ((nlines (cond ((not arg) (length org-table-clip))
  4318. ((< arg 1) (+ (length org-table-clip) arg))
  4319. (t arg))))
  4320. (setq org-table-clip
  4321. (mapcar #'list
  4322. (org-wrap (mapconcat #'car org-table-clip " ")
  4323. nil
  4324. nlines))))
  4325. (goto-char start)
  4326. (org-table-paste-rectangle))
  4327. (org-table-align))
  4328. ;; No region, split the current field at point.
  4329. (unless (org-get-alist-option org-M-RET-may-split-line 'table)
  4330. (skip-chars-forward "^\r\n|"))
  4331. (cond
  4332. (arg ; Combine with field above.
  4333. (let ((s (org-table-blank-field))
  4334. (col (org-table-current-column)))
  4335. (forward-line -1)
  4336. (while (org-at-table-hline-p) (forward-line -1))
  4337. (org-table-goto-column col)
  4338. (skip-chars-forward "^|")
  4339. (skip-chars-backward " ")
  4340. (insert " " (org-trim s))
  4341. (org-table-align)))
  4342. ((looking-at "\\([^|]+\\)|") ; Split field.
  4343. (let ((s (match-string 1)))
  4344. (replace-match " |")
  4345. (goto-char (match-beginning 0))
  4346. (org-table-next-row)
  4347. (insert (org-trim s) " ")
  4348. (org-table-align)))
  4349. (t (org-table-next-row)))))
  4350. (defun org-table--number-for-summing (s)
  4351. (let (n)
  4352. (if (string-match "^ *|? *" s)
  4353. (setq s (replace-match "" nil nil s)))
  4354. (if (string-match " *|? *$" s)
  4355. (setq s (replace-match "" nil nil s)))
  4356. (setq n (string-to-number s))
  4357. (cond
  4358. ((and (string-match "0" s)
  4359. (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
  4360. ((string-match "\\`[ \t]+\\'" s) nil)
  4361. ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
  4362. (let ((h (string-to-number (or (match-string 1 s) "0")))
  4363. (m (string-to-number (or (match-string 2 s) "0")))
  4364. (s (string-to-number (or (match-string 4 s) "0"))))
  4365. (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
  4366. (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
  4367. ((equal n 0) nil)
  4368. (t n))))
  4369. ;;;###autoload
  4370. (defun org-table-sum (&optional beg end nlast)
  4371. "Sum numbers in region of current table column.
  4372. The result will be displayed in the echo area, and will be available
  4373. as kill to be inserted with \\[yank].
  4374. If there is an active region, it is interpreted as a rectangle and all
  4375. numbers in that rectangle will be summed. If there is no active
  4376. region and point is located in a table column, sum all numbers in that
  4377. column.
  4378. If at least one number looks like a time HH:MM or HH:MM:SS, all other
  4379. numbers are assumed to be times as well (in decimal hours) and the
  4380. numbers are added as such.
  4381. If NLAST is a number, only the NLAST fields will actually be summed."
  4382. (interactive)
  4383. (save-excursion
  4384. (let (col (org-timecnt 0) diff h m s org-table-clip)
  4385. (cond
  4386. ((and beg end)) ; beg and end given explicitly
  4387. ((org-region-active-p)
  4388. (setq beg (region-beginning) end (region-end)))
  4389. (t
  4390. (setq col (org-table-current-column))
  4391. (goto-char (org-table-begin))
  4392. (unless (re-search-forward "^[ \t]*|[^-]" nil t)
  4393. (user-error "No table data"))
  4394. (org-table-goto-column col)
  4395. (setq beg (point))
  4396. (goto-char (org-table-end))
  4397. (unless (re-search-backward "^[ \t]*|[^-]" nil t)
  4398. (user-error "No table data"))
  4399. (org-table-goto-column col)
  4400. (setq end (point))))
  4401. (let* ((items (apply 'append (org-table-copy-region beg end)))
  4402. (items1 (cond ((not nlast) items)
  4403. ((>= nlast (length items)) items)
  4404. (t (setq items (reverse items))
  4405. (setcdr (nthcdr (1- nlast) items) nil)
  4406. (nreverse items))))
  4407. (numbers (delq nil (mapcar #'org-table--number-for-summing
  4408. items1)))
  4409. (res (apply '+ numbers))
  4410. (sres (if (= org-timecnt 0)
  4411. (number-to-string res)
  4412. (setq diff (* 3600 res)
  4413. h (floor diff 3600) diff (mod diff 3600)
  4414. m (floor diff 60) diff (mod diff 60)
  4415. s diff)
  4416. (format "%.0f:%02.0f:%02.0f" h m s))))
  4417. (kill-new sres)
  4418. (when (called-interactively-p 'interactive)
  4419. (message (substitute-command-keys
  4420. (format "Sum of %d items: %-20s \
  4421. \(\\[yank] will insert result into buffer)"
  4422. (length numbers)
  4423. sres))))
  4424. sres))))
  4425. ;;;###autoload
  4426. (defun org-table-analyze ()
  4427. "Analyze table at point and store results.
  4428. This function sets up the following dynamically scoped variables:
  4429. `org-table-column-name-regexp',
  4430. `org-table-column-names',
  4431. `org-table-current-begin-pos',
  4432. `org-table-current-line-types',
  4433. `org-table-current-ncol',
  4434. `org-table-dlines',
  4435. `org-table-hlines',
  4436. `org-table-local-parameters',
  4437. `org-table-named-field-locations'."
  4438. (let ((beg (org-table-begin))
  4439. (end (org-table-end)))
  4440. (save-excursion
  4441. (goto-char beg)
  4442. ;; Extract column names.
  4443. (setq org-table-column-names nil)
  4444. (when (save-excursion
  4445. (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
  4446. (let ((c 1))
  4447. (dolist (name (org-split-string (match-string 1) " *| *"))
  4448. (cl-incf c)
  4449. (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
  4450. (push (cons name (number-to-string c)) org-table-column-names)))))
  4451. (setq org-table-column-names (nreverse org-table-column-names))
  4452. (setq org-table-column-name-regexp
  4453. (format "\\$\\(%s\\)\\>"
  4454. (regexp-opt (mapcar #'car org-table-column-names) t)))
  4455. ;; Extract local parameters.
  4456. (setq org-table-local-parameters nil)
  4457. (save-excursion
  4458. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  4459. (dolist (field (org-split-string (match-string 1) " *| *"))
  4460. (when (string-match
  4461. "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  4462. (push (cons (match-string 1 field) (match-string 2 field))
  4463. org-table-local-parameters)))))
  4464. ;; Update named fields locations. We minimize `count-lines'
  4465. ;; processing by storing last known number of lines in LAST.
  4466. (setq org-table-named-field-locations nil)
  4467. (save-excursion
  4468. (let ((last (cons (point) 0)))
  4469. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  4470. (let ((c (match-string 1))
  4471. (fields (org-split-string (match-string 2) " *| *")))
  4472. (save-excursion
  4473. (forward-line (if (equal c "_") 1 -1))
  4474. (let ((fields1
  4475. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  4476. (org-split-string (match-string 1) " *| *")))
  4477. (line (cl-incf (cdr last) (count-lines (car last) (point))))
  4478. (col 1))
  4479. (setcar last (point)) ; Update last known position.
  4480. (while (and fields fields1)
  4481. (let ((field (pop fields))
  4482. (v (pop fields1)))
  4483. (cl-incf col)
  4484. (when (and (stringp field)
  4485. (stringp v)
  4486. (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
  4487. field))
  4488. (push (cons field v) org-table-local-parameters)
  4489. (push (list field line col)
  4490. org-table-named-field-locations))))))))))
  4491. ;; Re-use existing markers when possible.
  4492. (if (markerp org-table-current-begin-pos)
  4493. (move-marker org-table-current-begin-pos (point))
  4494. (setq org-table-current-begin-pos (point-marker)))
  4495. ;; Analyze the line types.
  4496. (let ((l 0) hlines dlines types)
  4497. (while (looking-at "[ \t]*|\\(-\\)?")
  4498. (push (if (match-end 1) 'hline 'dline) types)
  4499. (if (match-end 1) (push l hlines) (push l dlines))
  4500. (forward-line)
  4501. (cl-incf l))
  4502. (push 'hline types) ; Add an imaginary extra hline to the end.
  4503. (setq org-table-current-line-types (apply #'vector (nreverse types)))
  4504. (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
  4505. (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
  4506. ;; Get the number of columns from the first data line in table.
  4507. (goto-char beg)
  4508. (forward-line (aref org-table-dlines 1))
  4509. (setq org-table-current-ncol
  4510. (length (org-split-string
  4511. (buffer-substring (line-beginning-position) (line-end-position))
  4512. "[ \t]*|[ \t]*"))))))
  4513. (defun org-table--force-dataline ()
  4514. "Move point to the closest data line in a table.
  4515. Raise an error if the table contains no data line. Preserve
  4516. column when moving point."
  4517. (unless (org-match-line org-table-dataline-regexp)
  4518. (let* ((re org-table-dataline-regexp)
  4519. (column (current-column))
  4520. (p1 (save-excursion (re-search-forward re (org-table-end) t)))
  4521. (p2 (save-excursion (re-search-backward re (org-table-begin) t))))
  4522. (cond ((and p1 p2)
  4523. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  4524. p1
  4525. p2)))
  4526. ((or p1 p2) (goto-char (or p1 p2)))
  4527. (t (user-error "No table data line around here")))
  4528. (org-move-to-column column))))
  4529. (defun org-table-show-reference (&optional local)
  4530. "Show the location/value of the $ expression at point.
  4531. When LOCAL is non-nil, show references for the table at point."
  4532. (interactive)
  4533. (org-table-remove-rectangle-highlight)
  4534. (when local (org-table-analyze))
  4535. (catch 'exit
  4536. (let ((pos (if local (point) org-pos))
  4537. (face2 'highlight)
  4538. (org-inhibit-highlight-removal t)
  4539. (win (selected-window))
  4540. (org-show-positions nil)
  4541. var name e what match dest)
  4542. (setq what (cond
  4543. ((org-in-regexp "^@[0-9]+[ \t=]")
  4544. (setq match (concat (substring (match-string 0) 0 -1)
  4545. "$1.."
  4546. (substring (match-string 0) 0 -1)
  4547. "$100"))
  4548. 'range)
  4549. ((or (org-in-regexp org-table-range-regexp2)
  4550. (org-in-regexp org-table-translate-regexp)
  4551. (org-in-regexp org-table-range-regexp))
  4552. (setq match
  4553. (save-match-data
  4554. (org-table-convert-refs-to-rc (match-string 0))))
  4555. 'range)
  4556. ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  4557. ((org-in-regexp "\\$[0-9]+") 'column)
  4558. ((not local) nil)
  4559. (t (user-error "No reference at point")))
  4560. match (and what (or match (match-string 0))))
  4561. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  4562. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  4563. 'secondary-selection))
  4564. (add-hook 'before-change-functions
  4565. #'org-table-remove-rectangle-highlight)
  4566. (when (eq what 'name) (setq var (substring match 1)))
  4567. (when (eq what 'range)
  4568. (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
  4569. (setq match (org-table-formula-substitute-names match)))
  4570. (unless local
  4571. (save-excursion
  4572. (end-of-line)
  4573. (re-search-backward "^\\S-" nil t)
  4574. (beginning-of-line)
  4575. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
  4576. \\([0-9]+\\|&\\)\\) *=")
  4577. (setq dest
  4578. (save-match-data
  4579. (org-table-convert-refs-to-rc (match-string 1))))
  4580. (org-table-add-rectangle-overlay
  4581. (match-beginning 1) (match-end 1) face2))))
  4582. (if (and (markerp pos) (marker-buffer pos))
  4583. (if (get-buffer-window (marker-buffer pos))
  4584. (select-window (get-buffer-window (marker-buffer pos)))
  4585. (org-switch-to-buffer-other-window (get-buffer-window
  4586. (marker-buffer pos)))))
  4587. (goto-char pos)
  4588. (org-table--force-dataline)
  4589. (let ((table-start
  4590. (if local org-table-current-begin-pos (org-table-begin))))
  4591. (when dest
  4592. (setq name (substring dest 1))
  4593. (cond
  4594. ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  4595. (org-table-goto-field dest))
  4596. ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
  4597. dest)
  4598. (org-table-goto-field dest))
  4599. (t (org-table-goto-column (string-to-number name))))
  4600. (move-marker pos (point))
  4601. (org-table-highlight-rectangle nil nil face2))
  4602. (cond
  4603. ((equal dest match))
  4604. ((not match))
  4605. ((eq what 'range)
  4606. (ignore-errors (org-table-get-range match table-start nil 'highlight)))
  4607. ((setq e (assoc var org-table-named-field-locations))
  4608. (org-table-goto-field var)
  4609. (org-table-highlight-rectangle)
  4610. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  4611. ((setq e (assoc var org-table-column-names))
  4612. (org-table-goto-column (string-to-number (cdr e)))
  4613. (org-table-highlight-rectangle)
  4614. (goto-char table-start)
  4615. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  4616. (org-table-end) t)
  4617. (progn
  4618. (goto-char (match-beginning 1))
  4619. (org-table-highlight-rectangle)
  4620. (message "Named column (column %s)" (cdr e)))
  4621. (user-error "Column name not found")))
  4622. ((eq what 'column)
  4623. ;; Column number.
  4624. (org-table-goto-column (string-to-number (substring match 1)))
  4625. (org-table-highlight-rectangle)
  4626. (message "Column %s" (substring match 1)))
  4627. ((setq e (assoc var org-table-local-parameters))
  4628. (goto-char table-start)
  4629. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  4630. (progn
  4631. (goto-char (match-beginning 1))
  4632. (org-table-highlight-rectangle)
  4633. (message "Local parameter."))
  4634. (user-error "Parameter not found")))
  4635. ((not var) (user-error "No reference at point"))
  4636. ((setq e (assoc var org-table-formula-constants-local))
  4637. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  4638. var (cdr e)))
  4639. ((setq e (assoc var org-table-formula-constants))
  4640. (message "Constant: $%s=%s in `org-table-formula-constants'."
  4641. var (cdr e)))
  4642. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  4643. (message "Constant: $%s=%s, from `constants.el'%s."
  4644. var e (format " (%s units)" constants-unit-system)))
  4645. (t (user-error "Undefined name $%s" var)))
  4646. (goto-char pos)
  4647. (when (and org-show-positions
  4648. (not (memq this-command '(org-table-fedit-scroll
  4649. org-table-fedit-scroll-down))))
  4650. (push pos org-show-positions)
  4651. (push table-start org-show-positions)
  4652. (let ((min (apply 'min org-show-positions))
  4653. (max (apply 'max org-show-positions)))
  4654. (set-window-start (selected-window) min)
  4655. (goto-char max)
  4656. (or (pos-visible-in-window-p max)
  4657. (set-window-start (selected-window) max)))))
  4658. (select-window win))))
  4659. ;;; The Orgtbl minor mode
  4660. ;; Define a minor mode which can be used in other modes in order to
  4661. ;; integrate the Org table editor.
  4662. ;; This is really a hack, because the Org table editor uses several
  4663. ;; keys which normally belong to the major mode, for example the TAB
  4664. ;; and RET keys. Here is how it works: The minor mode defines all the
  4665. ;; keys necessary to operate the table editor, but wraps the commands
  4666. ;; into a function which tests if the cursor is currently inside
  4667. ;; a table. If that is the case, the table editor command is
  4668. ;; executed. However, when any of those keys is used outside a table,
  4669. ;; the function uses `key-binding' to look up if the key has an
  4670. ;; associated command in another currently active keymap (minor modes,
  4671. ;; major mode, global), and executes that command. There might be
  4672. ;; problems if any of the keys used by the table editor is otherwise
  4673. ;; used as a prefix key.
  4674. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  4675. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  4676. ;; addresses this by checking explicitly for both bindings.
  4677. ;; The optimized version (see variable `orgtbl-optimized') takes over
  4678. ;; all keys which are bound to `self-insert-command' in the *global map*.
  4679. ;; Some modes bind other commands to simple characters, for example
  4680. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  4681. ;; active, this binding is ignored inside tables and replaced with a
  4682. ;; modified self-insert.
  4683. (defvar orgtbl-mode-map (make-keymap)
  4684. "Keymap for `orgtbl-mode'.")
  4685. (defvar org-old-auto-fill-inhibit-regexp nil
  4686. "Local variable used by `orgtbl-mode'.")
  4687. (defconst orgtbl-line-start-regexp
  4688. "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
  4689. "Matches a line belonging to an orgtbl.")
  4690. (defconst orgtbl-extra-font-lock-keywords
  4691. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  4692. 0 (quote 'org-table) 'prepend))
  4693. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  4694. ;;;###autoload
  4695. (defun turn-on-orgtbl ()
  4696. "Unconditionally turn on `orgtbl-mode'."
  4697. (require 'org-table)
  4698. (orgtbl-mode 1))
  4699. ;; Install it as a minor mode.
  4700. (put 'orgtbl-mode :included t)
  4701. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  4702. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu."
  4703. '("OrgTbl"
  4704. ["Create or convert" org-table-create-or-convert-from-region
  4705. :active (not (org-at-table-p)) :keys "C-c |" ]
  4706. "--"
  4707. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  4708. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  4709. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  4710. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  4711. "--"
  4712. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  4713. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  4714. ["Copy Field from Above"
  4715. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  4716. "--"
  4717. ("Column"
  4718. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  4719. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  4720. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  4721. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  4722. ("Row"
  4723. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  4724. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  4725. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  4726. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  4727. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  4728. "--"
  4729. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  4730. ("Rectangle"
  4731. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  4732. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  4733. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  4734. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  4735. "--"
  4736. ("Radio tables"
  4737. ["Insert table template" orgtbl-insert-radio-table
  4738. (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
  4739. ["Comment/uncomment table" orgtbl-toggle-comment t])
  4740. "--"
  4741. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  4742. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  4743. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  4744. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  4745. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  4746. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  4747. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  4748. ["Sum Column/Rectangle" org-table-sum
  4749. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  4750. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  4751. ["Debug Formulas"
  4752. org-table-toggle-formula-debugger :active (org-at-table-p)
  4753. :keys "C-c {"
  4754. :style toggle :selected org-table-formula-debug]
  4755. ["Show Col/Row Numbers"
  4756. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  4757. :keys "C-c }"
  4758. :style toggle :selected org-table-overlay-coordinates]
  4759. "--"
  4760. ("Plot"
  4761. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4762. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4763. ;;;###autoload
  4764. (define-minor-mode orgtbl-mode
  4765. "The Org mode table editor as a minor mode for use in other modes."
  4766. :lighter " OrgTbl"
  4767. (org-load-modules-maybe)
  4768. (cond
  4769. ((derived-mode-p 'org-mode)
  4770. ;; Exit without error, in case some hook functions calls this by
  4771. ;; accident in Org mode.
  4772. (message "Orgtbl mode is not useful in Org mode, command ignored"))
  4773. (orgtbl-mode
  4774. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  4775. ;; Make sure we are first in minor-mode-map-alist
  4776. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  4777. ;; FIXME: maybe it should use emulation-mode-map-alists?
  4778. (and c (setq minor-mode-map-alist
  4779. (cons c (delq c minor-mode-map-alist)))))
  4780. (setq-local org-table-may-need-update t)
  4781. (add-hook 'before-change-functions 'org-before-change-function
  4782. nil 'local)
  4783. (setq-local org-old-auto-fill-inhibit-regexp
  4784. auto-fill-inhibit-regexp)
  4785. (setq-local auto-fill-inhibit-regexp
  4786. (if auto-fill-inhibit-regexp
  4787. (concat orgtbl-line-start-regexp "\\|"
  4788. auto-fill-inhibit-regexp)
  4789. orgtbl-line-start-regexp))
  4790. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  4791. (org-restart-font-lock))
  4792. (t
  4793. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  4794. (remove-hook 'before-change-functions 'org-before-change-function t)
  4795. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  4796. (org-restart-font-lock)
  4797. (force-mode-line-update 'all))))
  4798. (defun orgtbl-make-binding (fun n &rest keys)
  4799. "Create a function for binding in the table minor mode.
  4800. FUN is the command to call inside a table. N is used to create a unique
  4801. command name. KEYS are keys that should be checked in for a command
  4802. to execute outside of tables."
  4803. (eval
  4804. (list 'defun
  4805. (intern (concat "orgtbl-hijacker-command-" (number-to-string n)))
  4806. '(arg)
  4807. (concat "In tables, run `" (symbol-name fun) "'.\n"
  4808. "Outside of tables, run the binding of `"
  4809. (mapconcat #'key-description keys "' or `")
  4810. "'.")
  4811. '(interactive "p")
  4812. (list 'if
  4813. '(org-at-table-p)
  4814. (list 'call-interactively (list 'quote fun))
  4815. (list 'let '(orgtbl-mode)
  4816. (list 'call-interactively
  4817. (append '(or)
  4818. (mapcar (lambda (k)
  4819. (list 'key-binding k))
  4820. keys)
  4821. '('orgtbl-error))))))))
  4822. (defun orgtbl-error ()
  4823. "Error when there is no default binding for a table key."
  4824. (interactive)
  4825. (user-error "This key has no function outside tables"))
  4826. (defun orgtbl-setup ()
  4827. "Setup orgtbl keymaps."
  4828. (let ((nfunc 0)
  4829. (bindings
  4830. '(([(meta shift left)] org-table-delete-column)
  4831. ([(meta left)] org-table-move-column-left)
  4832. ([(meta right)] org-table-move-column-right)
  4833. ([(meta shift right)] org-table-insert-column)
  4834. ([(meta shift up)] org-table-kill-row)
  4835. ([(meta shift down)] org-table-insert-row)
  4836. ([(meta up)] org-table-move-row-up)
  4837. ([(meta down)] org-table-move-row-down)
  4838. ("\C-c\C-w" org-table-cut-region)
  4839. ("\C-c\M-w" org-table-copy-region)
  4840. ("\C-c\C-y" org-table-paste-rectangle)
  4841. ("\C-c\C-w" org-table-wrap-region)
  4842. ("\C-c-" org-table-insert-hline)
  4843. ("\C-c}" org-table-toggle-coordinate-overlays)
  4844. ("\C-c{" org-table-toggle-formula-debugger)
  4845. ("\C-m" org-table-next-row)
  4846. ([(shift return)] org-table-copy-down)
  4847. ("\C-c?" org-table-field-info)
  4848. ("\C-c " org-table-blank-field)
  4849. ("\C-c+" org-table-sum)
  4850. ("\C-c=" org-table-eval-formula)
  4851. ("\C-c'" org-table-edit-formulas)
  4852. ("\C-c`" org-table-edit-field)
  4853. ("\C-c*" org-table-recalculate)
  4854. ("\C-c^" org-table-sort-lines)
  4855. ("\M-a" org-table-beginning-of-field)
  4856. ("\M-e" org-table-end-of-field)
  4857. ([(control ?#)] org-table-rotate-recalc-marks)))
  4858. elt key fun cmd)
  4859. (while (setq elt (pop bindings))
  4860. (setq nfunc (1+ nfunc))
  4861. (setq key (org-key (car elt))
  4862. fun (nth 1 elt)
  4863. cmd (orgtbl-make-binding fun nfunc key))
  4864. (org-defkey orgtbl-mode-map key cmd))
  4865. ;; Special treatment needed for TAB, RET and DEL
  4866. (org-defkey orgtbl-mode-map [(return)]
  4867. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  4868. (org-defkey orgtbl-mode-map "\C-m"
  4869. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  4870. (org-defkey orgtbl-mode-map [(tab)]
  4871. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  4872. (org-defkey orgtbl-mode-map "\C-i"
  4873. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  4874. (org-defkey orgtbl-mode-map [(shift tab)]
  4875. (orgtbl-make-binding 'org-table-previous-field 104
  4876. [(shift tab)] [(tab)] "\C-i"))
  4877. (org-defkey orgtbl-mode-map [backspace]
  4878. (orgtbl-make-binding 'org-delete-backward-char 109
  4879. [backspace] (kbd "DEL")))
  4880. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  4881. (orgtbl-make-binding 'org-table-previous-field 107
  4882. [S-iso-lefttab] [backtab] [(shift tab)]
  4883. [(tab)] "\C-i"))
  4884. (org-defkey orgtbl-mode-map [backtab]
  4885. (orgtbl-make-binding 'org-table-previous-field 108
  4886. [backtab] [S-iso-lefttab] [(shift tab)]
  4887. [(tab)] "\C-i"))
  4888. (org-defkey orgtbl-mode-map "\M-\C-m"
  4889. (orgtbl-make-binding 'org-table-wrap-region 105
  4890. "\M-\C-m" [(meta return)]))
  4891. (org-defkey orgtbl-mode-map [(meta return)]
  4892. (orgtbl-make-binding 'org-table-wrap-region 106
  4893. [(meta return)] "\M-\C-m"))
  4894. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  4895. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  4896. (when orgtbl-optimized
  4897. ;; If the user wants maximum table support, we need to hijack
  4898. ;; some standard editing functions
  4899. (org-remap orgtbl-mode-map
  4900. 'self-insert-command 'orgtbl-self-insert-command
  4901. 'delete-char 'org-delete-char
  4902. 'delete-forward-char 'org-delete-char
  4903. 'delete-backward-char 'org-delete-backward-char)
  4904. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  4905. t))
  4906. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4907. "If the cursor is inside a table, realign the table.
  4908. If it is a table to be sent away to a receiver, do it.
  4909. With prefix arg, also recompute table."
  4910. (interactive "P")
  4911. (let ((case-fold-search t) (pos (point)) action)
  4912. (save-excursion
  4913. (beginning-of-line 1)
  4914. (setq action (cond
  4915. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4916. ((looking-at "[ \t]*|") pos)
  4917. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4918. (cond
  4919. ((integerp action)
  4920. (goto-char action)
  4921. (org-table-maybe-eval-formula)
  4922. (if arg
  4923. (call-interactively 'org-table-recalculate)
  4924. (org-table-maybe-recalculate-line))
  4925. (call-interactively 'org-table-align)
  4926. (when (orgtbl-send-table 'maybe)
  4927. (run-hooks 'orgtbl-after-send-table-hook)))
  4928. ((eq action 'recalc)
  4929. (save-excursion
  4930. (beginning-of-line 1)
  4931. (skip-chars-backward " \r\n\t")
  4932. (if (org-at-table-p)
  4933. (org-call-with-arg 'org-table-recalculate t))))
  4934. (t (let (orgtbl-mode)
  4935. (call-interactively (key-binding "\C-c\C-c")))))))
  4936. (defun orgtbl-create-or-convert-from-region (_arg)
  4937. "Create table or convert region to table, if no conflicting binding.
  4938. This installs the table binding `C-c |', but only if there is no
  4939. conflicting binding to this key outside `orgtbl-mode'."
  4940. (interactive "P")
  4941. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4942. (if cmd
  4943. (call-interactively cmd)
  4944. (call-interactively 'org-table-create-or-convert-from-region))))
  4945. (defun orgtbl-tab (arg)
  4946. "Justification and field motion for `orgtbl-mode'."
  4947. (interactive "P")
  4948. (if arg (org-table-edit-field t)
  4949. (org-table-justify-field-maybe)
  4950. (org-table-next-field)))
  4951. (defun orgtbl-ret ()
  4952. "Justification and field motion for `orgtbl-mode'."
  4953. (interactive)
  4954. (if (bobp)
  4955. (newline)
  4956. (org-table-justify-field-maybe)
  4957. (org-table-next-row)))
  4958. (defun orgtbl-self-insert-command (N)
  4959. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4960. If the cursor is in a table looking at whitespace, the whitespace is
  4961. overwritten, and the table is not marked as requiring realignment."
  4962. (interactive "p")
  4963. (if (and (org-at-table-p)
  4964. (or
  4965. (and org-table-auto-blank-field
  4966. (member last-command
  4967. '(orgtbl-hijacker-command-100
  4968. orgtbl-hijacker-command-101
  4969. orgtbl-hijacker-command-102
  4970. orgtbl-hijacker-command-103
  4971. orgtbl-hijacker-command-104
  4972. orgtbl-hijacker-command-105
  4973. yas/expand))
  4974. (org-table-blank-field))
  4975. t)
  4976. (eq N 1)
  4977. (looking-at "[^|\n]* \\( \\)|"))
  4978. (let (org-table-may-need-update)
  4979. (delete-region (match-beginning 1) (match-end 1))
  4980. (self-insert-command N))
  4981. (setq org-table-may-need-update t)
  4982. (let* (orgtbl-mode
  4983. a
  4984. (cmd (or (key-binding
  4985. (or (and (listp function-key-map)
  4986. (setq a (assoc last-input-event function-key-map))
  4987. (cdr a))
  4988. (vector last-input-event)))
  4989. 'self-insert-command)))
  4990. (call-interactively cmd)
  4991. (if (and org-self-insert-cluster-for-undo
  4992. (eq cmd 'self-insert-command))
  4993. (if (not (eq last-command 'orgtbl-self-insert-command))
  4994. (setq org-self-insert-command-undo-counter 1)
  4995. (if (>= org-self-insert-command-undo-counter 20)
  4996. (setq org-self-insert-command-undo-counter 1)
  4997. (and (> org-self-insert-command-undo-counter 0)
  4998. buffer-undo-list
  4999. (not (cadr buffer-undo-list)) ; remove nil entry
  5000. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  5001. (setq org-self-insert-command-undo-counter
  5002. (1+ org-self-insert-command-undo-counter))))))))
  5003. ;;;###autoload
  5004. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  5005. "Regular expression matching exponentials as produced by calc.")
  5006. (defun orgtbl-gather-send-defs ()
  5007. "Gather a plist of :name, :transform, :params for each destination before
  5008. a radio table."
  5009. (save-excursion
  5010. (goto-char (org-table-begin))
  5011. (let (rtn)
  5012. (beginning-of-line 0)
  5013. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  5014. (let ((name (org-no-properties (match-string 1)))
  5015. (transform (intern (match-string 2)))
  5016. (params (if (match-end 3)
  5017. (read (concat "(" (match-string 3) ")")))))
  5018. (push (list :name name :transform transform :params params)
  5019. rtn)
  5020. (beginning-of-line 0)))
  5021. rtn)))
  5022. (defun orgtbl-send-replace-tbl (name text)
  5023. "Find and replace table NAME with TEXT."
  5024. (save-excursion
  5025. (goto-char (point-min))
  5026. (let* ((location-flag nil)
  5027. (name (regexp-quote name))
  5028. (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
  5029. (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
  5030. (while (re-search-forward begin-re nil t)
  5031. (unless location-flag (setq location-flag t))
  5032. (let ((beg (line-beginning-position 2)))
  5033. (unless (re-search-forward end-re nil t)
  5034. (user-error "Cannot find end of receiver location at %d" beg))
  5035. (beginning-of-line)
  5036. (delete-region beg (point))
  5037. (insert text "\n")))
  5038. (unless location-flag
  5039. (user-error "No valid receiver location found in the buffer")))))
  5040. ;;;###autoload
  5041. (defun org-table-to-lisp (&optional txt)
  5042. "Convert the table at point to a Lisp structure.
  5043. The structure will be a list. Each item is either the symbol `hline'
  5044. for a horizontal separator line, or a list of field values as strings.
  5045. The table is taken from the parameter TXT, or from the buffer at point."
  5046. (if txt
  5047. (with-temp-buffer
  5048. (insert txt)
  5049. (goto-char (point-min))
  5050. (org-table-to-lisp))
  5051. (save-excursion
  5052. (goto-char (org-table-begin))
  5053. (let ((table nil))
  5054. (while (re-search-forward "\\=[ \t]*|" nil t)
  5055. (let ((row nil))
  5056. (if (looking-at "-")
  5057. (push 'hline table)
  5058. (while (not (progn (skip-chars-forward " \t") (eolp)))
  5059. (push (buffer-substring
  5060. (point)
  5061. (progn (re-search-forward "[ \t]*\\(|\\|$\\)")
  5062. (match-beginning 0)))
  5063. row))
  5064. (push (nreverse row) table)))
  5065. (forward-line))
  5066. (nreverse table)))))
  5067. (defun org-table-collapse-header (table &optional separator max-header-lines)
  5068. "Collapse the lines before \\='hline into a single header.
  5069. The given TABLE is a list of lists as returned by `org-table-to-lisp'.
  5070. The leading lines before the first `hline' symbol are considered
  5071. forming the table header. This function collapses all leading header
  5072. lines into a single header line, followed by the `hline' symbol, and
  5073. the rest of the TABLE. Header cells are glued together with a space,
  5074. or the given SEPARATOR."
  5075. (while (eq (car table) 'hline) (pop table))
  5076. (let* ((separator (or separator " "))
  5077. (max-header-lines (or max-header-lines 4))
  5078. (trailer table)
  5079. (header-lines (cl-loop for line in table
  5080. until (eq 'hline line)
  5081. collect (pop trailer))))
  5082. (if (and trailer (<= (length header-lines) max-header-lines))
  5083. (cons (apply #'cl-mapcar
  5084. (lambda (&rest x)
  5085. (org-trim
  5086. (mapconcat #'identity x separator)))
  5087. header-lines)
  5088. trailer)
  5089. table)))
  5090. (defun orgtbl-send-table (&optional maybe)
  5091. "Send a transformed version of table at point to the receiver position.
  5092. With argument MAYBE, fail quietly if no transformation is defined
  5093. for this table."
  5094. (interactive)
  5095. (catch 'exit
  5096. (unless (org-at-table-p) (user-error "Not at a table"))
  5097. ;; when non-interactive, we assume align has just happened.
  5098. (when (called-interactively-p 'any) (org-table-align))
  5099. (let ((dests (orgtbl-gather-send-defs))
  5100. (table (org-table-to-lisp))
  5101. (ntbl 0))
  5102. (unless dests
  5103. (if maybe (throw 'exit nil)
  5104. (user-error "Don't know how to transform this table")))
  5105. (dolist (dest dests)
  5106. (let ((name (plist-get dest :name))
  5107. (transform (plist-get dest :transform))
  5108. (params (plist-get dest :params)))
  5109. (unless (fboundp transform)
  5110. (user-error "No such transformation function %s" transform))
  5111. (orgtbl-send-replace-tbl name (funcall transform table params)))
  5112. (cl-incf ntbl))
  5113. (message "Table converted and installed at %d receiver location%s"
  5114. ntbl (if (> ntbl 1) "s" ""))
  5115. (and (> ntbl 0) ntbl))))
  5116. (defun org-remove-by-index (list indices &optional i0)
  5117. "Remove the elements in LIST with indices in INDICES.
  5118. First element has index 0, or I0 if given."
  5119. (if (not indices)
  5120. list
  5121. (if (integerp indices) (setq indices (list indices)))
  5122. (setq i0 (1- (or i0 0)))
  5123. (delq :rm (mapcar (lambda (x)
  5124. (setq i0 (1+ i0))
  5125. (if (memq i0 indices) :rm x))
  5126. list))))
  5127. (defun orgtbl-toggle-comment ()
  5128. "Comment or uncomment the orgtbl at point."
  5129. (interactive)
  5130. (let* ((case-fold-search t)
  5131. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  5132. (re2 (concat "^" orgtbl-line-start-regexp))
  5133. (commented (save-excursion (beginning-of-line 1)
  5134. (cond ((looking-at re1) t)
  5135. ((looking-at re2) nil)
  5136. (t (user-error "Not at an org table")))))
  5137. (re (if commented re1 re2))
  5138. beg end)
  5139. (save-excursion
  5140. (beginning-of-line 1)
  5141. (while (and (not (eq (point) (point-min)))
  5142. (looking-at re))
  5143. (beginning-of-line 0))
  5144. (unless (eq (point) (point-min)) (beginning-of-line 2))
  5145. (setq beg (point))
  5146. (while (and (not (eq (point) (point-max)))
  5147. (looking-at re))
  5148. (beginning-of-line 2))
  5149. (setq end (point)))
  5150. (comment-region beg end (if commented '(4) nil))))
  5151. (defun orgtbl-insert-radio-table ()
  5152. "Insert a radio table template appropriate for this major mode."
  5153. (interactive)
  5154. (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
  5155. (txt (nth 1 e))
  5156. name pos)
  5157. (unless e (user-error "No radio table setup defined for %s" major-mode))
  5158. (setq name (read-string "Table name: "))
  5159. (while (string-match "%n" txt)
  5160. (setq txt (replace-match name t t txt)))
  5161. (or (bolp) (insert "\n"))
  5162. (setq pos (point))
  5163. (insert txt)
  5164. (goto-char pos)))
  5165. ;;;###autoload
  5166. (defun orgtbl-to-generic (table params)
  5167. "Convert the `orgtbl-mode' TABLE to some other format.
  5168. This generic routine can be used for many standard cases.
  5169. TABLE is a list, each entry either the symbol `hline' for
  5170. a horizontal separator line, or a list of fields for that
  5171. line. PARAMS is a property list of parameters that can
  5172. influence the conversion.
  5173. Valid parameters are:
  5174. :backend, :raw
  5175. Export back-end used as a basis to transcode elements of the
  5176. table, when no specific parameter applies to it. It is also
  5177. used to translate cells contents. You can prevent this by
  5178. setting :raw property to a non-nil value.
  5179. :splice
  5180. When non-nil, only convert rows, not the table itself. This is
  5181. equivalent to setting to the empty string both :tstart
  5182. and :tend, which see.
  5183. :skip
  5184. When set to an integer N, skip the first N lines of the table.
  5185. Horizontal separation lines do count for this parameter!
  5186. :skipcols
  5187. List of columns that should be skipped. If the table has
  5188. a column with calculation marks, that column is automatically
  5189. discarded beforehand.
  5190. :hline
  5191. String to be inserted on horizontal separation lines. May be
  5192. nil to ignore these lines altogether.
  5193. :sep
  5194. Separator between two fields, as a string.
  5195. Each in the following group may be either a string or a function
  5196. of no arguments returning a string:
  5197. :tstart, :tend
  5198. Strings to start and end the table. Ignored when :splice is t.
  5199. :lstart, :lend
  5200. Strings to start and end a new table line.
  5201. :llstart, :llend
  5202. Strings to start and end the last table line. Default,
  5203. respectively, to :lstart and :lend.
  5204. Each in the following group may be a string or a function of one
  5205. argument (either the cells in the current row, as a list of
  5206. strings, or the current cell) returning a string:
  5207. :lfmt
  5208. Format string for an entire row, with enough %s to capture all
  5209. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  5210. :llfmt
  5211. Format for the entire last line, defaults to :lfmt.
  5212. :fmt
  5213. A format to be used to wrap the field, should contain %s for
  5214. the original field value. For example, to wrap everything in
  5215. dollars, you could use :fmt \"$%s$\". This may also be
  5216. a property list with column numbers and format strings, or
  5217. functions, e.g.,
  5218. (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  5219. The format is ignored for empty fields. Use :raw t with non-nil
  5220. :backend option to force formatting empty fields.
  5221. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  5222. Same as above, specific for the header lines in the table.
  5223. All lines before the first hline are treated as header. If
  5224. any of these is not present, the data line value is used.
  5225. This may be either a string or a function of two arguments:
  5226. :efmt
  5227. Use this format to print numbers with exponential. The format
  5228. should have %s twice for inserting mantissa and exponent, for
  5229. example \"%s\\\\times10^{%s}\". This may also be a property
  5230. list with column numbers and format strings or functions.
  5231. :fmt will still be applied after :efmt."
  5232. ;; Make sure `org-export-create-backend' is available.
  5233. (require 'ox)
  5234. (let* ((backend (plist-get params :backend))
  5235. (custom-backend
  5236. ;; Build a custom back-end according to PARAMS. Before
  5237. ;; defining a translator, check if there is anything to do.
  5238. ;; When there isn't, let BACKEND handle the element.
  5239. (org-export-create-backend
  5240. :parent (or backend 'org)
  5241. :transcoders
  5242. `((table . ,(org-table--to-generic-table params))
  5243. (table-row . ,(org-table--to-generic-row params))
  5244. (table-cell . ,(org-table--to-generic-cell params))
  5245. ;; Macros are not going to be expanded. However, no
  5246. ;; regular back-end has a transcoder for them. We
  5247. ;; provide one so they are not ignored, but displayed
  5248. ;; as-is instead.
  5249. (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
  5250. data info)
  5251. ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
  5252. ;; Initialize communication channel in INFO.
  5253. (with-temp-buffer
  5254. (let ((org-inhibit-startup t)) (org-mode))
  5255. (let ((standard-output (current-buffer))
  5256. (org-element-use-cache nil))
  5257. (dolist (e table)
  5258. (cond ((eq e 'hline) (princ "|--\n"))
  5259. ((consp e)
  5260. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  5261. (princ "\n")))))
  5262. (org-element-cache-reset)
  5263. ;; Add back-end specific filters, but not user-defined ones. In
  5264. ;; particular, make sure to call parse-tree filters on the
  5265. ;; table.
  5266. (setq info
  5267. (let ((org-export-filters-alist nil))
  5268. (org-export-install-filters
  5269. (org-combine-plists
  5270. (org-export-get-environment backend nil params)
  5271. `(:back-end ,(org-export-get-backend backend))))))
  5272. (setq data
  5273. (org-export-filter-apply-functions
  5274. (plist-get info :filter-parse-tree)
  5275. (org-element-map (org-element-parse-buffer) 'table
  5276. #'identity nil t)
  5277. info)))
  5278. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  5279. (user-error "Unknown :backend value"))
  5280. (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
  5281. ;; Handle :skip parameter.
  5282. (let ((skip (plist-get info :skip)))
  5283. (when skip
  5284. (unless (wholenump skip) (user-error "Wrong :skip value"))
  5285. (let ((n 0))
  5286. (org-element-map data 'table-row
  5287. (lambda (row)
  5288. (if (>= n skip) t
  5289. (org-element-extract-element row)
  5290. (cl-incf n)
  5291. nil))
  5292. nil t))))
  5293. ;; Handle :skipcols parameter.
  5294. (let ((skipcols (plist-get info :skipcols)))
  5295. (when skipcols
  5296. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  5297. (org-element-map data 'table
  5298. (lambda (table)
  5299. (let ((specialp (org-export-table-has-special-column-p table)))
  5300. (dolist (row (org-element-contents table))
  5301. (when (eq (org-element-property :type row) 'standard)
  5302. (let ((c 1))
  5303. (dolist (cell (nthcdr (if specialp 1 0)
  5304. (org-element-contents row)))
  5305. (when (memq c skipcols)
  5306. (org-element-extract-element cell))
  5307. (cl-incf c))))))))))
  5308. ;; Since we are going to export using a low-level mechanism,
  5309. ;; ignore special column and special rows manually.
  5310. (let ((special? (org-export-table-has-special-column-p data))
  5311. ignore)
  5312. (org-element-map data (if special? '(table-cell table-row) 'table-row)
  5313. (lambda (datum)
  5314. (when (if (eq (org-element-type datum) 'table-row)
  5315. (org-export-table-row-is-special-p datum nil)
  5316. (org-export-first-sibling-p datum nil))
  5317. (push datum ignore))))
  5318. (setq info (plist-put info :ignore-list ignore)))
  5319. ;; We use a low-level mechanism to export DATA so as to skip all
  5320. ;; usual pre-processing and post-processing, i.e., hooks, Babel
  5321. ;; code evaluation, include keywords and macro expansion. Only
  5322. ;; back-end specific filters are retained.
  5323. (let ((output (org-export-data-with-backend data custom-backend info)))
  5324. ;; Remove final newline.
  5325. (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
  5326. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  5327. (cond ((null value) nil)
  5328. ((functionp value) `(funcall ',value ,@args))
  5329. ((stringp value)
  5330. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  5331. (args `(format ,value ,@args))
  5332. (t value)))
  5333. ((and with-cons (consp value))
  5334. `(let ((val (cadr (memq column ',value))))
  5335. (cond ((null val) contents)
  5336. ((stringp val) (format val ,@args))
  5337. ((functionp val) (funcall val ,@args))
  5338. (t (user-error "Wrong %s value" ,name)))))
  5339. (t (user-error "Wrong %s value" name))))
  5340. (defun org-table--to-generic-table (params)
  5341. "Return custom table transcoder according to PARAMS.
  5342. PARAMS is a plist. See `orgtbl-to-generic' for more
  5343. information."
  5344. (let ((backend (plist-get params :backend))
  5345. (splice (plist-get params :splice))
  5346. (tstart (plist-get params :tstart))
  5347. (tend (plist-get params :tend)))
  5348. `(lambda (table contents info)
  5349. (concat
  5350. ,(and tstart (not splice)
  5351. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  5352. ,(if (or (not backend) tstart tend splice) 'contents
  5353. `(org-export-with-backend ',backend table contents info))
  5354. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  5355. (defun org-table--to-generic-row (params)
  5356. "Return custom table row transcoder according to PARAMS.
  5357. PARAMS is a plist. See `orgtbl-to-generic' for more
  5358. information."
  5359. (let* ((backend (plist-get params :backend))
  5360. (lstart (plist-get params :lstart))
  5361. (llstart (plist-get params :llstart))
  5362. (hlstart (plist-get params :hlstart))
  5363. (hllstart (plist-get params :hllstart))
  5364. (lend (plist-get params :lend))
  5365. (llend (plist-get params :llend))
  5366. (hlend (plist-get params :hlend))
  5367. (hllend (plist-get params :hllend))
  5368. (lfmt (plist-get params :lfmt))
  5369. (llfmt (plist-get params :llfmt))
  5370. (hlfmt (plist-get params :hlfmt))
  5371. (hllfmt (plist-get params :hllfmt)))
  5372. `(lambda (row contents info)
  5373. (if (eq (org-element-property :type row) 'rule)
  5374. ,(cond
  5375. ((plist-member params :hline)
  5376. (org-table--generic-apply (plist-get params :hline) ":hline"))
  5377. (backend `(org-export-with-backend ',backend row nil info)))
  5378. (let ((headerp ,(and (or hlfmt hlstart hlend)
  5379. '(org-export-table-row-in-header-p row info)))
  5380. (last-header-p
  5381. ,(and (or hllfmt hllstart hllend)
  5382. '(org-export-table-row-ends-header-p row info)))
  5383. (lastp (not (org-export-get-next-element row info))))
  5384. (when contents
  5385. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  5386. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  5387. ;; `:lstart', `:lend' and their relatives.
  5388. ,(let ((cells
  5389. '(org-element-map row 'table-cell
  5390. (lambda (cell)
  5391. ;; Export all cells, without separators.
  5392. ;;
  5393. ;; Use `org-export-data-with-backend'
  5394. ;; instead of `org-export-data' to eschew
  5395. ;; cached values, which
  5396. ;; ignore :orgtbl-ignore-sep parameter.
  5397. (org-export-data-with-backend
  5398. cell
  5399. (plist-get info :back-end)
  5400. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  5401. info)))
  5402. `(cond
  5403. ,(and hllfmt
  5404. `(last-header-p ,(org-table--generic-apply
  5405. hllfmt ":hllfmt" nil cells)))
  5406. ,(and hlfmt
  5407. `(headerp ,(org-table--generic-apply
  5408. hlfmt ":hlfmt" nil cells)))
  5409. ,(and llfmt
  5410. `(lastp ,(org-table--generic-apply
  5411. llfmt ":llfmt" nil cells)))
  5412. (t
  5413. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  5414. `(concat
  5415. (cond
  5416. ,(and
  5417. (or hllstart hllend)
  5418. `(last-header-p
  5419. (concat
  5420. ,(org-table--generic-apply hllstart ":hllstart")
  5421. contents
  5422. ,(org-table--generic-apply hllend ":hllend"))))
  5423. ,(and
  5424. (or hlstart hlend)
  5425. `(headerp
  5426. (concat
  5427. ,(org-table--generic-apply hlstart ":hlstart")
  5428. contents
  5429. ,(org-table--generic-apply hlend ":hlend"))))
  5430. ,(and
  5431. (or llstart llend)
  5432. `(lastp
  5433. (concat
  5434. ,(org-table--generic-apply llstart ":llstart")
  5435. contents
  5436. ,(org-table--generic-apply llend ":llend"))))
  5437. (t
  5438. ,(cond
  5439. ((or lstart lend)
  5440. `(concat
  5441. ,(org-table--generic-apply lstart ":lstart")
  5442. contents
  5443. ,(org-table--generic-apply lend ":lend")))
  5444. (backend
  5445. `(org-export-with-backend
  5446. ',backend row contents info))
  5447. (t 'contents)))))))))))))))
  5448. (defun org-table--to-generic-cell (params)
  5449. "Return custom table cell transcoder according to PARAMS.
  5450. PARAMS is a plist. See `orgtbl-to-generic' for more
  5451. information."
  5452. (let* ((backend (plist-get params :backend))
  5453. (efmt (plist-get params :efmt))
  5454. (fmt (plist-get params :fmt))
  5455. (hfmt (plist-get params :hfmt))
  5456. (sep (plist-get params :sep))
  5457. (hsep (plist-get params :hsep)))
  5458. `(lambda (cell contents info)
  5459. ;; Make sure that contents are exported as Org data when :raw
  5460. ;; parameter is non-nil.
  5461. ,(when (and backend (plist-get params :raw))
  5462. `(setq contents
  5463. ;; Since we don't know what are the pseudo object
  5464. ;; types defined in backend, we cannot pass them to
  5465. ;; `org-element-interpret-data'. As a consequence,
  5466. ;; they will be treated as pseudo elements, and will
  5467. ;; have newlines appended instead of spaces.
  5468. ;; Therefore, we must make sure :post-blank value is
  5469. ;; really turned into spaces.
  5470. (replace-regexp-in-string
  5471. "\n" " "
  5472. (org-trim
  5473. (org-element-interpret-data
  5474. (org-element-contents cell))))))
  5475. (let ((headerp ,(and (or hfmt hsep)
  5476. '(org-export-table-row-in-header-p
  5477. (org-export-get-parent-element cell) info)))
  5478. (column
  5479. ;; Call costly `org-export-table-cell-address' only if
  5480. ;; absolutely necessary, i.e., if one
  5481. ;; of :fmt :efmt :hfmt has a "plist type" value.
  5482. ,(and (cl-some (lambda (v) (integerp (car-safe v)))
  5483. (list efmt hfmt fmt))
  5484. '(1+ (cdr (org-export-table-cell-address cell info))))))
  5485. (when contents
  5486. ;; Check if we can apply `:efmt' on CONTENTS.
  5487. ,(when efmt
  5488. `(when (string-match orgtbl-exp-regexp contents)
  5489. (let ((mantissa (match-string 1 contents))
  5490. (exponent (match-string 2 contents)))
  5491. (setq contents ,(org-table--generic-apply
  5492. efmt ":efmt" t 'mantissa 'exponent)))))
  5493. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  5494. (cond
  5495. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  5496. hfmt ":hfmt" t 'contents))))
  5497. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  5498. fmt ":fmt" t 'contents))))))
  5499. ;; If a separator is provided, use it instead of BACKEND's.
  5500. ;; Separators are ignored when LFMT (or equivalent) is
  5501. ;; provided.
  5502. ,(cond
  5503. ((or hsep sep)
  5504. `(if (or ,(and (not sep) '(not headerp))
  5505. (plist-get info :orgtbl-ignore-sep)
  5506. (not (org-export-get-next-element cell info)))
  5507. ,(if (not backend) 'contents
  5508. `(org-export-with-backend ',backend cell contents info))
  5509. (concat contents
  5510. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  5511. (or hsep sep)))))
  5512. (backend `(org-export-with-backend ',backend cell contents info))
  5513. (t 'contents))))))
  5514. ;;;###autoload
  5515. (defun orgtbl-to-tsv (table params)
  5516. "Convert the `orgtbl-mode' TABLE to TAB separated material."
  5517. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  5518. ;;;###autoload
  5519. (defun orgtbl-to-csv (table params)
  5520. "Convert the `orgtbl-mode' TABLE to CSV material.
  5521. This does take care of the proper quoting of fields with comma or quotes."
  5522. (orgtbl-to-generic table
  5523. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  5524. params)))
  5525. ;;;###autoload
  5526. (defun orgtbl-to-latex (table params)
  5527. "Convert the `orgtbl-mode' TABLE to LaTeX.
  5528. TABLE is a list, each entry either the symbol `hline' for
  5529. a horizontal separator line, or a list of fields for that line.
  5530. PARAMS is a property list of parameters that can influence the
  5531. conversion. All parameters from `orgtbl-to-generic' are
  5532. supported. It is also possible to use the following ones:
  5533. :booktabs
  5534. When non-nil, use formal \"booktabs\" style.
  5535. :environment
  5536. Specify environment to use, as a string. If you use
  5537. \"longtable\", you may also want to specify :language property,
  5538. as a string, to get proper continuation strings."
  5539. (require 'ox-latex)
  5540. (orgtbl-to-generic
  5541. table
  5542. (org-combine-plists
  5543. ;; Provide sane default values.
  5544. (list :backend 'latex
  5545. :latex-default-table-mode 'table
  5546. :latex-tables-centered nil
  5547. :latex-tables-booktabs (plist-get params :booktabs)
  5548. :latex-table-scientific-notation nil
  5549. :latex-default-table-environment
  5550. (or (plist-get params :environment) "tabular"))
  5551. params)))
  5552. ;;;###autoload
  5553. (defun orgtbl-to-html (table params)
  5554. "Convert the `orgtbl-mode' TABLE to HTML.
  5555. TABLE is a list, each entry either the symbol `hline' for
  5556. a horizontal separator line, or a list of fields for that line.
  5557. PARAMS is a property list of parameters that can influence the
  5558. conversion. All parameters from `orgtbl-to-generic' are
  5559. supported. It is also possible to use the following one:
  5560. :attributes
  5561. Attributes and values, as a plist, which will be used in
  5562. <table> tag."
  5563. (require 'ox-html)
  5564. (orgtbl-to-generic
  5565. table
  5566. (org-combine-plists
  5567. ;; Provide sane default values.
  5568. (list :backend 'html
  5569. :html-table-data-tags '("<td%s>" . "</td>")
  5570. :html-table-use-header-tags-for-first-column nil
  5571. :html-table-align-individual-fields t
  5572. :html-table-row-tags '("<tr>" . "</tr>")
  5573. :html-table-attributes
  5574. (if (plist-member params :attributes)
  5575. (plist-get params :attributes)
  5576. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  5577. :frame "hsides")))
  5578. params)))
  5579. ;;;###autoload
  5580. (defun orgtbl-to-texinfo (table params)
  5581. "Convert the `orgtbl-mode' TABLE to Texinfo.
  5582. TABLE is a list, each entry either the symbol `hline' for
  5583. a horizontal separator line, or a list of fields for that line.
  5584. PARAMS is a property list of parameters that can influence the
  5585. conversion. All parameters from `orgtbl-to-generic' are
  5586. supported. It is also possible to use the following one:
  5587. :columns
  5588. Column widths, as a string. When providing column fractions,
  5589. \"@columnfractions\" command can be omitted."
  5590. (require 'ox-texinfo)
  5591. (let ((output
  5592. (orgtbl-to-generic
  5593. table
  5594. (org-combine-plists
  5595. (list :backend 'texinfo
  5596. :texinfo-tables-verbatim nil
  5597. :texinfo-table-scientific-notation nil)
  5598. params)))
  5599. (columns (let ((w (plist-get params :columns)))
  5600. (cond ((not w) nil)
  5601. ((string-match-p "{\\|@columnfractions " w) w)
  5602. (t (concat "@columnfractions " w))))))
  5603. (if (not columns) output
  5604. (replace-regexp-in-string
  5605. "@multitable \\(.*\\)" columns output t nil 1))))
  5606. ;;;###autoload
  5607. (defun orgtbl-to-orgtbl (table params)
  5608. "Convert the `orgtbl-mode' TABLE into another orgtbl-mode table.
  5609. TABLE is a list, each entry either the symbol `hline' for
  5610. a horizontal separator line, or a list of fields for that line.
  5611. PARAMS is a property list of parameters that can influence the
  5612. conversion. All parameters from `orgtbl-to-generic' are
  5613. supported.
  5614. Useful when slicing one table into many. The :hline, :sep,
  5615. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  5616. be set to provide ORGTBL directives for the generated table."
  5617. (require 'ox-org)
  5618. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  5619. (defun orgtbl-to-table.el (table params)
  5620. "Convert the `orgtbl-mode' TABLE into a table.el table.
  5621. TABLE is a list, each entry either the symbol `hline' for
  5622. a horizontal separator line, or a list of fields for that line.
  5623. PARAMS is a property list of parameters that can influence the
  5624. conversion. All parameters from `orgtbl-to-generic' are
  5625. supported."
  5626. (with-temp-buffer
  5627. (insert (orgtbl-to-orgtbl table params))
  5628. (org-table-align)
  5629. (replace-regexp-in-string
  5630. "-|" "-+"
  5631. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  5632. (defun orgtbl-to-unicode (table params)
  5633. "Convert the `orgtbl-mode' TABLE into a table with unicode characters.
  5634. TABLE is a list, each entry either the symbol `hline' for
  5635. a horizontal separator line, or a list of fields for that line.
  5636. PARAMS is a property list of parameters that can influence the
  5637. conversion. All parameters from `orgtbl-to-generic' are
  5638. supported. It is also possible to use the following ones:
  5639. :ascii-art
  5640. When non-nil, use \"ascii-art-to-unicode\" package to translate
  5641. the table. You can download it here:
  5642. https://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  5643. :narrow
  5644. When non-nil, narrow columns width than provided width cookie,
  5645. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  5646. (require 'ox-ascii)
  5647. (orgtbl-to-generic
  5648. table
  5649. (org-combine-plists
  5650. (list :backend 'ascii
  5651. :ascii-charset 'utf-8
  5652. :ascii-table-widen-columns (not (plist-get params :narrow))
  5653. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  5654. params)))
  5655. ;; Put the cursor in a column containing numerical values
  5656. ;; of an Org table,
  5657. ;; type C-c " a
  5658. ;; A new column is added with a bar plot.
  5659. ;; When the table is refreshed (C-u C-c *),
  5660. ;; the plot is updated to reflect the new values.
  5661. (defun orgtbl-ascii-draw (value min max &optional width characters)
  5662. "Draw an ascii bar in a table.
  5663. VALUE is the value to plot, it determines the width of the bar to draw.
  5664. MIN is the value that will be displayed as empty (zero width bar).
  5665. MAX is the value that will draw a bar filling all the WIDTH.
  5666. WIDTH is the span in characters from MIN to MAX.
  5667. CHARACTERS is a string that will compose the bar, with shades of grey
  5668. from pure white to pure black. It defaults to a 10 characters string
  5669. of regular ascii characters."
  5670. (let* ((width (ceiling (or width 12)))
  5671. (characters (or characters " .:;c!lhVHW"))
  5672. (len (1- (length characters)))
  5673. (value (float (if (numberp value)
  5674. value (string-to-number value))))
  5675. (relative (/ (- value min) (- max min)))
  5676. (steps (round (* relative width len))))
  5677. (cond ((< steps 0) "too small")
  5678. ((> steps (* width len)) "too large")
  5679. (t (let* ((int-division (/ steps len))
  5680. (remainder (- steps (* int-division len))))
  5681. (concat (make-string int-division (elt characters len))
  5682. (string (elt characters remainder))))))))
  5683. ;;;###autoload
  5684. (defun orgtbl-ascii-plot (&optional ask)
  5685. "Draw an ASCII bar plot in a column.
  5686. With cursor in a column containing numerical values, this function
  5687. will draw a plot in a new column.
  5688. ASK, if given, is a numeric prefix to override the default 12
  5689. characters width of the plot. ASK may also be the `\\[universal-argument]' \
  5690. prefix,
  5691. which will prompt for the width."
  5692. (interactive "P")
  5693. (let ((col (org-table-current-column))
  5694. (min 1e999) ; 1e999 will be converted to infinity
  5695. (max -1e999) ; which is the desired result
  5696. (table (org-table-to-lisp))
  5697. (length
  5698. (cond ((consp ask)
  5699. (read-number "Length of column " 12))
  5700. ((numberp ask) ask)
  5701. (t 12))))
  5702. ;; Skip any hline a the top of table.
  5703. (while (eq (car table) 'hline) (pop table))
  5704. ;; Skip table header if any.
  5705. (dolist (x (or (cdr (memq 'hline table)) table))
  5706. (when (consp x)
  5707. (setq x (nth (1- col) x))
  5708. (when (string-match
  5709. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  5710. x)
  5711. (setq x (string-to-number x))
  5712. (when (> min x) (setq min x))
  5713. (when (< max x) (setq max x)))))
  5714. (org-table-insert-column)
  5715. (org-table-move-column-right)
  5716. (org-table-store-formulas
  5717. (cons
  5718. (cons
  5719. (concat "$" (number-to-string (1+ col)))
  5720. (format "'(%s $%s %s %s %s)"
  5721. "orgtbl-ascii-draw" col min max length))
  5722. (org-table-get-stored-formulas)))
  5723. (org-table-recalculate t)))
  5724. ;; Example of extension: unicode characters
  5725. ;; Here are two examples of different styles.
  5726. ;; Unicode block characters are used to give a smooth effect.
  5727. ;; See https://en.wikipedia.org/wiki/Block_Elements
  5728. ;; Use one of those drawing functions
  5729. ;; - orgtbl-ascii-draw (the default ascii)
  5730. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  5731. ;; - orgtbl-uc-draw-cont (smooth unicode)
  5732. ;; This is best viewed with the "DejaVu Sans Mono" font
  5733. ;; (use M-x set-frame-font).
  5734. (defun orgtbl-uc-draw-grid (value min max &optional width)
  5735. "Draw a bar in a table using block unicode characters.
  5736. It is a variant of `orgtbl-ascii-draw' with Unicode block
  5737. characters, for a smooth display. Bars appear as grids (to the
  5738. extent the font allows)."
  5739. ;; https://en.wikipedia.org/wiki/Block_Elements
  5740. ;; best viewed with the "DejaVu Sans Mono" font.
  5741. (orgtbl-ascii-draw value min max width
  5742. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  5743. (defun orgtbl-uc-draw-cont (value min max &optional width)
  5744. "Draw a bar in a table using block unicode characters.
  5745. It is a variant of `orgtbl-ascii-draw' with Unicode block
  5746. characters, for a smooth display. Bars are solid (to the extent
  5747. the font allows)."
  5748. (orgtbl-ascii-draw value min max width
  5749. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  5750. (defun org-table-get-remote-range (name-or-id form)
  5751. "Get a field value or a list of values in a range from table at ID.
  5752. NAME-OR-ID may be the name of a table in the current file as set
  5753. by a \"#+NAME:\" directive. The first table following this line
  5754. will then be used. Alternatively, it may be an ID referring to
  5755. any entry, also in a different file. In this case, the first
  5756. table in that entry will be referenced.
  5757. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  5758. \"@I$2..@II$2\". All the references must be absolute, not relative.
  5759. The return value is either a single string for a single field, or a
  5760. list of the fields in the rectangle."
  5761. (save-match-data
  5762. (let ((case-fold-search t) (id-loc nil)
  5763. ;; Protect a bunch of variables from being overwritten by
  5764. ;; the context of the remote table.
  5765. org-table-column-names org-table-column-name-regexp
  5766. org-table-local-parameters org-table-named-field-locations
  5767. org-table-current-line-types
  5768. org-table-current-begin-pos org-table-dlines
  5769. org-table-current-ncol
  5770. org-table-hlines
  5771. org-table-last-column-widths
  5772. org-table-last-alignment
  5773. buffer loc)
  5774. (setq form (org-table-convert-refs-to-rc form))
  5775. (org-with-wide-buffer
  5776. (goto-char (point-min))
  5777. (if (re-search-forward
  5778. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  5779. (regexp-quote name-or-id) "[ \t]*$")
  5780. nil t)
  5781. (setq buffer (current-buffer) loc (match-beginning 0))
  5782. (setq id-loc (org-id-find name-or-id 'marker))
  5783. (unless (and id-loc (markerp id-loc))
  5784. (user-error "Can't find remote table \"%s\"" name-or-id))
  5785. (setq buffer (marker-buffer id-loc)
  5786. loc (marker-position id-loc))
  5787. (move-marker id-loc nil))
  5788. (with-current-buffer buffer
  5789. (org-with-wide-buffer
  5790. (goto-char loc)
  5791. (forward-char 1)
  5792. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  5793. (not (match-beginning 1)))
  5794. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  5795. (org-table-analyze)
  5796. (setq form (org-table-formula-substitute-names
  5797. (org-table-formula-handle-first/last-rc form)))
  5798. (if (and (string-match org-table-range-regexp form)
  5799. (> (length (match-string 0 form)) 1))
  5800. (org-table-get-range
  5801. (match-string 0 form) org-table-current-begin-pos 1)
  5802. form)))))))
  5803. (defun org-table-remote-reference-indirection (form)
  5804. "Return formula with table remote references substituted by indirection.
  5805. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  5806. This indirection works only with the format @ROW$COLUMN. The
  5807. format \"B3\" is not supported because it can not be
  5808. distinguished from a plain table name or ID."
  5809. (let ((regexp
  5810. ;; Same as in `org-table-eval-formula'.
  5811. (concat "\\<remote([ \t]*\\("
  5812. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  5813. "[@$][^ \t,]+"
  5814. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
  5815. (replace-regexp-in-string
  5816. regexp
  5817. (lambda (m)
  5818. (save-match-data
  5819. (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
  5820. (org-table-get-range
  5821. (if (string-match-p "\\`\\$[0-9]+\\'" eq)
  5822. (concat "@0" eq)
  5823. eq)))))
  5824. form t t 1)))
  5825. (defmacro org-define-lookup-function (mode)
  5826. (let ((mode-str (symbol-name mode))
  5827. (first-p (eq mode 'first))
  5828. (all-p (eq mode 'all)))
  5829. (let ((plural-str (if all-p "s" "")))
  5830. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  5831. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  5832. If R-LIST is nil, return matching element%s of S-LIST.
  5833. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  5834. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  5835. This function is generated by a call to the macro `org-define-lookup-function'."
  5836. mode-str plural-str plural-str plural-str)
  5837. (let ,(let ((lvars '((p (or predicate 'equal))
  5838. (sl s-list)
  5839. (rl (or r-list s-list))
  5840. (ret nil))))
  5841. (if first-p (cons '(match-p nil) lvars) lvars))
  5842. (while ,(if first-p '(and (not match-p) sl) 'sl)
  5843. (when (funcall p val (car sl))
  5844. ,(when first-p '(setq match-p t))
  5845. (let ((rval (car rl)))
  5846. (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
  5847. (setq sl (cdr sl) rl (cdr rl)))
  5848. ret)))))
  5849. (org-define-lookup-function first)
  5850. (org-define-lookup-function last)
  5851. (org-define-lookup-function all)
  5852. (provide 'org-table)
  5853. ;; Local variables:
  5854. ;; generated-autoload-file: "org-loaddefs.el"
  5855. ;; End:
  5856. ;;; org-table.el ends here