org-table.el 233 KB

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