org-table.el 216 KB

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