org-table.el 216 KB

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