org-table.el 218 KB

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