org-table.el 220 KB

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