org-table.el 218 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917
  1. ;;; org-table.el --- The Table Editor for Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2018 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; Homepage: https://orgmode.org
  6. ;;
  7. ;; This file is part of GNU Emacs.
  8. ;;
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  20. ;;
  21. ;;; Commentary:
  22. ;; This file contains the table editor and spreadsheet for Org mode.
  23. ;; Watch out: Here we are talking about two different kind of tables.
  24. ;; Most of the code is for the tables created with the Org mode table editor.
  25. ;; Sometimes, we talk about tables created and edited with the table.el
  26. ;; Emacs package. We call the former org-type tables, and the latter
  27. ;; table.el-type tables.
  28. ;;; Code:
  29. (require 'cl-lib)
  30. (require 'org)
  31. (declare-function org-element-at-point "org-element" ())
  32. (declare-function org-element-contents "org-element" (element))
  33. (declare-function org-element-extract-element "org-element" (element))
  34. (declare-function org-element-interpret-data "org-element" (data))
  35. (declare-function org-element-lineage "org-element"
  36. (blob &optional types with-self))
  37. (declare-function org-element-map "org-element"
  38. (data types fun
  39. &optional info first-match no-recursion with-affiliated))
  40. (declare-function org-element-parse-buffer "org-element"
  41. (&optional granularity visible-only))
  42. (declare-function org-element-property "org-element" (property element))
  43. (declare-function org-element-type "org-element" (element))
  44. (declare-function org-export-create-backend "ox" (&rest rest) t)
  45. (declare-function org-export-data-with-backend "ox" (data backend info))
  46. (declare-function org-export-filter-apply-functions "ox"
  47. (filters value info))
  48. (declare-function org-export-first-sibling-p "ox" (blob info))
  49. (declare-function org-export-get-backend "ox" (name))
  50. (declare-function org-export-get-environment "ox"
  51. (&optional backend subtreep ext-plist))
  52. (declare-function org-export-install-filters "ox" (info))
  53. (declare-function org-export-table-has-special-column-p "ox" (table))
  54. (declare-function org-export-table-row-is-special-p "ox" (table-row info))
  55. (declare-function calc-eval "calc" (str &optional separator &rest args))
  56. (defvar constants-unit-system)
  57. (defvar org-element-use-cache)
  58. (defvar org-export-filters-alist)
  59. (defvar org-table-follow-field-mode)
  60. (defvar orgtbl-mode) ; defined below
  61. (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
  62. (defvar sort-fold-case)
  63. (defvar orgtbl-after-send-table-hook nil
  64. "Hook for functions attaching to `C-c C-c', if the table is sent.
  65. This can be used to add additional functionality after the table is sent
  66. to the receiver position, otherwise, if table is not sent, the functions
  67. are not run.")
  68. (defvar org-table-TBLFM-begin-regexp "^[ \t]*|.*\n[ \t]*#\\+TBLFM: ")
  69. (defcustom orgtbl-optimized t
  70. "Non-nil means use the optimized table editor version for `orgtbl-mode'.
  71. In the optimized version, the table editor takes over all simple keys that
  72. normally just insert a character. In tables, the characters are inserted
  73. in a way to minimize disturbing the table structure (i.e. in overwrite mode
  74. for empty fields). Outside tables, the correct binding of the keys is
  75. restored.
  76. Changing this variable requires a restart of Emacs to become
  77. effective."
  78. :group 'org-table
  79. :type 'boolean)
  80. (defcustom orgtbl-radio-table-templates
  81. '((latex-mode "% BEGIN RECEIVE ORGTBL %n
  82. % END RECEIVE ORGTBL %n
  83. \\begin{comment}
  84. #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
  85. | | |
  86. \\end{comment}\n")
  87. (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
  88. @c END RECEIVE ORGTBL %n
  89. @ignore
  90. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  91. | | |
  92. @end ignore\n")
  93. (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
  94. <!-- END RECEIVE ORGTBL %n -->
  95. <!--
  96. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  97. | | |
  98. -->\n")
  99. (org-mode "#+ BEGIN RECEIVE ORGTBL %n
  100. #+ END RECEIVE ORGTBL %n
  101. #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
  102. | | |
  103. "))
  104. "Templates for radio tables in different major modes.
  105. Each template must define lines that will be treated as a comment and that
  106. must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
  107. lines where \"%n\" will be replaced with the name of the table during
  108. insertion of the template. The transformed table will later be inserted
  109. between these lines.
  110. The template should also contain a minimal table in a multiline comment.
  111. If multiline comments are not possible in the buffer language,
  112. you can pack it into a string that will not be used when the code
  113. is compiled or executed. Above the table will you need a line with
  114. the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
  115. convert the table into a data structure useful in the
  116. language of the buffer. Check the manual for the section on
  117. \"Translator functions\", and more generally check out
  118. the Info node `(org)Tables in arbitrary syntax'.
  119. All occurrences of %n in a template will be replaced with the name of the
  120. table, obtained by prompting the user."
  121. :group 'org-table
  122. :type '(repeat
  123. (list (symbol :tag "Major mode")
  124. (string :tag "Format"))))
  125. (defgroup org-table-settings nil
  126. "Settings for tables in Org mode."
  127. :tag "Org Table Settings"
  128. :group 'org-table)
  129. (defcustom org-table-default-size "5x2"
  130. "The default size for newly created tables, Columns x Rows."
  131. :group 'org-table-settings
  132. :type 'string)
  133. (defcustom org-table-number-regexp
  134. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
  135. "Regular expression for recognizing numbers in table columns.
  136. If a table column contains mostly numbers, it will be aligned to the
  137. right. If not, it will be aligned to the left.
  138. The default value of this option is a regular expression which allows
  139. anything which looks remotely like a number as used in scientific
  140. context. For example, all of the following will be considered a
  141. number:
  142. 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
  143. Other options offered by the customize interface are more restrictive."
  144. :group 'org-table-settings
  145. :type '(choice
  146. (const :tag "Positive Integers"
  147. "^[0-9]+$")
  148. (const :tag "Integers"
  149. "^[-+]?[0-9]+$")
  150. (const :tag "Floating Point Numbers"
  151. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
  152. (const :tag "Floating Point Number or Integer"
  153. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
  154. (const :tag "Exponential, Floating point, Integer"
  155. "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
  156. (const :tag "Very General Number-Like, including hex and Calc radix"
  157. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  158. (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
  159. "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  160. (string :tag "Regexp:")))
  161. (defcustom org-table-number-fraction 0.5
  162. "Fraction of numbers in a column required to make the column align right.
  163. In a column all non-white fields are considered. If at least
  164. this fraction of fields is matched by `org-table-number-regexp',
  165. alignment to the right border applies."
  166. :group 'org-table-settings
  167. :type 'number)
  168. (defgroup org-table-editing nil
  169. "Behavior of tables during editing in Org mode."
  170. :tag "Org Table Editing"
  171. :group 'org-table)
  172. (defcustom org-table-automatic-realign t
  173. "Non-nil means automatically re-align table when pressing TAB or RETURN.
  174. When nil, aligning is only done with `\\[org-table-align]', or after column
  175. removal/insertion."
  176. :group 'org-table-editing
  177. :type 'boolean)
  178. (defcustom org-table-auto-blank-field t
  179. "Non-nil means automatically blank table field when starting to type into it.
  180. This only happens when typing immediately after a field motion
  181. command (TAB, S-TAB or RET)."
  182. :group 'org-table-editing
  183. :type 'boolean)
  184. (defcustom org-table-exit-follow-field-mode-when-leaving-table t
  185. "Non-nil means automatically exit the follow mode.
  186. When nil, the follow mode will stay on and be active in any table
  187. the cursor enters. Since the table follow filed mode messes with the
  188. window configuration, it is not recommended to set this variable to nil,
  189. except maybe locally in a special file that has mostly tables with long
  190. fields."
  191. :group 'org-table
  192. :version "24.1"
  193. :type 'boolean)
  194. (defcustom org-table-fix-formulas-confirm nil
  195. "Whether the user should confirm when Org fixes formulas."
  196. :group 'org-table-editing
  197. :version "24.1"
  198. :type '(choice
  199. (const :tag "with yes-or-no" yes-or-no-p)
  200. (const :tag "with y-or-n" y-or-n-p)
  201. (const :tag "no confirmation" nil)))
  202. (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 the locale allows for it.
  1574. If SORTING-TYPE is specified when this function is called from a Lisp
  1575. program, no prompting will take place. SORTING-TYPE must be a character,
  1576. any of (?a ?A ?n ?N ?t ?T ?f ?F) where the capital letters indicate that
  1577. sorting should be done in reverse order.
  1578. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies
  1579. a function to be called to extract the key. It must return a value
  1580. that is compatible with COMPARE-FUNC, the function used to compare
  1581. entries.
  1582. A non-nil value for INTERACTIVE? is used to signal that this
  1583. function is being called interactively."
  1584. (interactive (list current-prefix-arg nil nil nil t))
  1585. (when (org-region-active-p) (goto-char (region-beginning)))
  1586. ;; Point must be either within a field or before a data line.
  1587. (save-excursion
  1588. (skip-chars-backward " \t")
  1589. (when (bolp) (search-forward "|" (line-end-position) t))
  1590. (org-table-check-inside-data-field))
  1591. ;; Set appropriate case sensitivity and column used for sorting.
  1592. (let ((column (let ((c (org-table-current-column)))
  1593. (cond ((> c 0) c)
  1594. (interactive?
  1595. (read-number "Use column N for sorting: "))
  1596. (t 1))))
  1597. (sorting-type
  1598. (or sorting-type
  1599. (read-char-exclusive "Sort Table: [a]lphabetic, [n]umeric, \
  1600. \[t]ime, [f]unc. A/N/T/F means reversed: ")))
  1601. (start (org-table-begin))
  1602. (end (org-table-end)))
  1603. (save-restriction
  1604. ;; Narrow buffer to appropriate sorting area.
  1605. (if (org-region-active-p)
  1606. (progn (goto-char (region-beginning))
  1607. (narrow-to-region
  1608. (point)
  1609. (save-excursion (goto-char (region-end))
  1610. (line-beginning-position 2))))
  1611. (narrow-to-region
  1612. (save-excursion
  1613. (if (re-search-backward org-table-hline-regexp start t)
  1614. (line-beginning-position 2)
  1615. start))
  1616. (if (save-excursion (re-search-forward org-table-hline-regexp end t))
  1617. (match-beginning 0)
  1618. end)))
  1619. ;; Determine arguments for `sort-subr'. Also record original
  1620. ;; position. `org-table-save-field' cannot help here since
  1621. ;; sorting is too much destructive.
  1622. (let* ((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) (if with-case #'org-string-collate-lessp
  1650. (lambda (s1 s2) (org-string-collate-lessp s1 s2 nil t))))
  1651. ((?f ?F)
  1652. (or compare-func
  1653. (and interactive?
  1654. (org-read-function
  1655. "Function for comparing keys (empty for default \
  1656. `sort-subr' predicate): "
  1657. 'allow-empty))))))
  1658. (shrunk-columns (remq column (org-table--list-shrunk-columns))))
  1659. (goto-char (point-min))
  1660. (sort-subr (memq sorting-type '(?A ?N ?T ?F))
  1661. (lambda ()
  1662. (forward-line)
  1663. (while (and (not (eobp))
  1664. (not (looking-at org-table-dataline-regexp)))
  1665. (forward-line)))
  1666. #'end-of-line
  1667. (lambda ()
  1668. (funcall extract-key-from-field
  1669. (org-trim (org-table-get-field column))))
  1670. nil
  1671. predicate)
  1672. ;; Hide all columns but the one being sorted.
  1673. (org-table--shrink-columns shrunk-columns start end)
  1674. ;; Move back to initial field.
  1675. (forward-line (car coordinates))
  1676. (move-to-column (cdr coordinates))))))
  1677. ;;;###autoload
  1678. (defun org-table-cut-region (beg end)
  1679. "Copy region in table to the clipboard and blank all relevant fields.
  1680. If there is no active region, use just the field at point."
  1681. (interactive (list
  1682. (if (org-region-active-p) (region-beginning) (point))
  1683. (if (org-region-active-p) (region-end) (point))))
  1684. (org-table-copy-region beg end 'cut))
  1685. ;;;###autoload
  1686. (defun org-table-copy-region (beg end &optional cut)
  1687. "Copy rectangular region in table to clipboard.
  1688. A special clipboard is used which can only be accessed
  1689. with `org-table-paste-rectangle'."
  1690. (interactive (list
  1691. (if (org-region-active-p) (region-beginning) (point))
  1692. (if (org-region-active-p) (region-end) (point))
  1693. current-prefix-arg))
  1694. (goto-char (min beg end))
  1695. (org-table-check-inside-data-field)
  1696. (let ((beg (line-beginning-position))
  1697. (c01 (org-table-current-column))
  1698. region)
  1699. (goto-char (max beg end))
  1700. (org-table-check-inside-data-field nil t)
  1701. (let* ((end (copy-marker (line-end-position)))
  1702. (c02 (org-table-current-column))
  1703. (column-start (min c01 c02))
  1704. (column-end (max c01 c02))
  1705. (column-number (1+ (- column-end column-start)))
  1706. (rpl (and cut " ")))
  1707. (goto-char beg)
  1708. (while (< (point) end)
  1709. (unless (org-at-table-hline-p)
  1710. ;; Collect every cell between COLUMN-START and COLUMN-END.
  1711. (let (cols)
  1712. (dotimes (c column-number)
  1713. (push (org-table-get-field (+ c column-start) rpl) cols))
  1714. (push (nreverse cols) region)))
  1715. (forward-line))
  1716. (set-marker end nil))
  1717. (when cut (org-table-align))
  1718. (setq org-table-clip (nreverse region))
  1719. (message (substitute-command-keys "Cells in the region copied, use \\[org-table-paste-rectangle] to paste them in a table."))))
  1720. ;;;###autoload
  1721. (defun org-table-paste-rectangle ()
  1722. "Paste a rectangular region into a table.
  1723. The upper right corner ends up in the current field. All involved fields
  1724. will be overwritten. If the rectangle does not fit into the present table,
  1725. the table is enlarged as needed. The process ignores horizontal separator
  1726. lines."
  1727. (interactive)
  1728. (unless (consp org-table-clip)
  1729. (user-error "First cut/copy a region to paste!"))
  1730. (org-table-check-inside-data-field)
  1731. (let* ((column (org-table-current-column))
  1732. (org-table-automatic-realign nil))
  1733. (org-table-save-field
  1734. (dolist (row org-table-clip)
  1735. (while (org-at-table-hline-p) (forward-line))
  1736. ;; If we left the table, create a new row.
  1737. (when (and (bolp) (not (looking-at "[ \t]*|")))
  1738. (end-of-line 0)
  1739. (org-table-next-field))
  1740. (let ((c column))
  1741. (dolist (field row)
  1742. (org-table-goto-column c nil 'force)
  1743. (org-table-get-field nil field)
  1744. (cl-incf c)))
  1745. (forward-line)))
  1746. (org-table-align)))
  1747. ;;;###autoload
  1748. (defun org-table-convert ()
  1749. "Convert from `org-mode' table to table.el and back.
  1750. Obviously, this only works within limits. When an Org table is converted
  1751. to table.el, all horizontal separator lines get lost, because table.el uses
  1752. these as cell boundaries and has no notion of horizontal lines. A table.el
  1753. table can be converted to an Org table only if it does not do row or column
  1754. spanning. Multiline cells will become multiple cells. Beware, Org mode
  1755. does not test if the table can be successfully converted - it blindly
  1756. applies a recipe that works for simple tables."
  1757. (interactive)
  1758. (require 'table)
  1759. (if (org-at-table.el-p)
  1760. ;; convert to Org table
  1761. (let ((beg (copy-marker (org-table-begin t)))
  1762. (end (copy-marker (org-table-end t))))
  1763. (table-unrecognize-region beg end)
  1764. (goto-char beg)
  1765. (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
  1766. (replace-match ""))
  1767. (goto-char beg))
  1768. (if (org-at-table-p)
  1769. ;; convert to table.el table
  1770. (let ((beg (copy-marker (org-table-begin)))
  1771. (end (copy-marker (org-table-end))))
  1772. ;; first, get rid of all horizontal lines
  1773. (goto-char beg)
  1774. (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
  1775. (replace-match ""))
  1776. ;; insert a hline before first
  1777. (goto-char beg)
  1778. (org-table-insert-hline 'above)
  1779. (beginning-of-line -1)
  1780. ;; insert a hline after each line
  1781. (while (progn (beginning-of-line 3) (< (point) end))
  1782. (org-table-insert-hline))
  1783. (goto-char beg)
  1784. (setq end (move-marker end (org-table-end)))
  1785. ;; replace "+" at beginning and ending of hlines
  1786. (while (re-search-forward "^\\([ \t]*\\)|-" end t)
  1787. (replace-match "\\1+-"))
  1788. (goto-char beg)
  1789. (while (re-search-forward "-|[ \t]*$" end t)
  1790. (replace-match "-+"))
  1791. (goto-char beg)))))
  1792. (defun org-table-transpose-table-at-point ()
  1793. "Transpose Org table at point and eliminate hlines.
  1794. So a table like
  1795. | 1 | 2 | 4 | 5 |
  1796. |---+---+---+---|
  1797. | a | b | c | d |
  1798. | e | f | g | h |
  1799. will be transposed as
  1800. | 1 | a | e |
  1801. | 2 | b | f |
  1802. | 4 | c | g |
  1803. | 5 | d | h |
  1804. Note that horizontal lines disappear."
  1805. (interactive)
  1806. (let* ((table (delete 'hline (org-table-to-lisp)))
  1807. (dline_old (org-table-current-line))
  1808. (col_old (org-table-current-column))
  1809. (contents (mapcar (lambda (_)
  1810. (let ((tp table))
  1811. (mapcar
  1812. (lambda (_)
  1813. (prog1
  1814. (pop (car tp))
  1815. (setq tp (cdr tp))))
  1816. table)))
  1817. (car table))))
  1818. (goto-char (org-table-begin))
  1819. (re-search-forward "|")
  1820. (backward-char)
  1821. (delete-region (point) (org-table-end))
  1822. (insert (mapconcat
  1823. (lambda(x)
  1824. (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
  1825. contents ""))
  1826. (org-table-goto-line col_old)
  1827. (org-table-goto-column dline_old))
  1828. (org-table-align))
  1829. ;;;###autoload
  1830. (defun org-table-wrap-region (arg)
  1831. "Wrap several fields in a column like a paragraph.
  1832. This is useful if you'd like to spread the contents of a field over several
  1833. lines, in order to keep the table compact.
  1834. If there is an active region, and both point and mark are in the same column,
  1835. the text in the column is wrapped to minimum width for the given number of
  1836. lines. Generally, this makes the table more compact. A prefix ARG may be
  1837. used to change the number of desired lines. For example, \
  1838. `C-2 \\[org-table-wrap-region]'
  1839. formats the selected text to two lines. If the region was longer than two
  1840. lines, the remaining lines remain empty. A negative prefix argument reduces
  1841. the current number of lines by that amount. The wrapped text is pasted back
  1842. into the table. If you formatted it to more lines than it was before, fields
  1843. further down in the table get overwritten - so you might need to make space in
  1844. the table first.
  1845. If there is no region, the current field is split at the cursor position and
  1846. the text fragment to the right of the cursor is prepended to the field one
  1847. line down.
  1848. If there is no region, but you specify a prefix ARG, the current field gets
  1849. blank, and the content is appended to the field above."
  1850. (interactive "P")
  1851. (org-table-check-inside-data-field)
  1852. (if (org-region-active-p)
  1853. ;; There is a region: fill as a paragraph.
  1854. (let ((start (region-beginning)))
  1855. (org-table-cut-region (region-beginning) (region-end))
  1856. (when (> (length (car org-table-clip)) 1)
  1857. (user-error "Region must be limited to single column"))
  1858. (let ((nlines (cond ((not arg) (length org-table-clip))
  1859. ((< arg 1) (+ (length org-table-clip) arg))
  1860. (t arg))))
  1861. (setq org-table-clip
  1862. (mapcar #'list
  1863. (org-wrap (mapconcat #'car org-table-clip " ")
  1864. nil
  1865. nlines))))
  1866. (goto-char start)
  1867. (org-table-paste-rectangle))
  1868. ;; No region, split the current field at point.
  1869. (unless (org-get-alist-option org-M-RET-may-split-line 'table)
  1870. (skip-chars-forward "^\r\n|"))
  1871. (cond
  1872. (arg ; Combine with field above.
  1873. (let ((s (org-table-blank-field))
  1874. (col (org-table-current-column)))
  1875. (forward-line -1)
  1876. (while (org-at-table-hline-p) (forward-line -1))
  1877. (org-table-goto-column col)
  1878. (skip-chars-forward "^|")
  1879. (skip-chars-backward " ")
  1880. (insert " " (org-trim s))
  1881. (org-table-align)))
  1882. ((looking-at "\\([^|]+\\)+|") ; Split field.
  1883. (let ((s (match-string 1)))
  1884. (replace-match " |")
  1885. (goto-char (match-beginning 0))
  1886. (org-table-next-row)
  1887. (insert (org-trim s) " ")
  1888. (org-table-align)))
  1889. (t (org-table-next-row)))))
  1890. (defvar org-field-marker nil)
  1891. ;;;###autoload
  1892. (defun org-table-edit-field (arg)
  1893. "Edit table field in a different window.
  1894. This is mainly useful for fields that contain hidden parts.
  1895. When called with a `\\[universal-argument]' prefix, just make the full field
  1896. visible so that it can be edited in place.
  1897. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  1898. toggle `org-table-follow-field-mode'."
  1899. (interactive "P")
  1900. (unless (org-at-table-p) (user-error "Not at a table"))
  1901. (cond
  1902. ((equal arg '(16))
  1903. (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
  1904. (arg
  1905. (let ((b (save-excursion (skip-chars-backward "^|") (point)))
  1906. (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
  1907. (remove-text-properties b e '(invisible t intangible t))
  1908. (if (and (boundp 'font-lock-mode) font-lock-mode)
  1909. (font-lock-fontify-block))))
  1910. (t
  1911. (let ((pos (point-marker))
  1912. (coord
  1913. (if (eq org-table-use-standard-references t)
  1914. (concat (org-number-to-letters (org-table-current-column))
  1915. (int-to-string (org-table-current-dline)))
  1916. (concat "@" (int-to-string (org-table-current-dline))
  1917. "$" (int-to-string (org-table-current-column)))))
  1918. (field (org-table-get-field))
  1919. (cw (current-window-configuration))
  1920. p)
  1921. (goto-char pos)
  1922. (org-switch-to-buffer-other-window "*Org Table Edit Field*")
  1923. (when (and (local-variable-p 'org-field-marker)
  1924. (markerp org-field-marker))
  1925. (move-marker org-field-marker nil))
  1926. (erase-buffer)
  1927. (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
  1928. (let ((org-inhibit-startup t)) (org-mode))
  1929. (auto-fill-mode -1)
  1930. (setq truncate-lines nil)
  1931. (setq word-wrap t)
  1932. (goto-char (setq p (point-max)))
  1933. (insert (org-trim field))
  1934. (remove-text-properties p (point-max) '(invisible t intangible t))
  1935. (goto-char p)
  1936. (setq-local org-finish-function 'org-table-finish-edit-field)
  1937. (setq-local org-window-configuration cw)
  1938. (setq-local org-field-marker pos)
  1939. (message "Edit and finish with C-c C-c")))))
  1940. (defun org-table-finish-edit-field ()
  1941. "Finish editing a table data field.
  1942. Remove all newline characters, insert the result into the table, realign
  1943. the table and kill the editing buffer."
  1944. (let ((pos org-field-marker)
  1945. (cw org-window-configuration)
  1946. (cb (current-buffer))
  1947. text)
  1948. (goto-char (point-min))
  1949. (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
  1950. (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
  1951. (replace-match " "))
  1952. (setq text (org-trim (buffer-string)))
  1953. (set-window-configuration cw)
  1954. (kill-buffer cb)
  1955. (select-window (get-buffer-window (marker-buffer pos)))
  1956. (goto-char pos)
  1957. (move-marker pos nil)
  1958. (org-table-check-inside-data-field)
  1959. (org-table-get-field nil text)
  1960. (org-table-align)
  1961. (message "New field value inserted")))
  1962. (define-minor-mode org-table-follow-field-mode
  1963. "Minor mode to make the table field editor window follow the cursor.
  1964. When this mode is active, the field editor window will always show the
  1965. current field. The mode exits automatically when the cursor leaves the
  1966. table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
  1967. nil " TblFollow" nil
  1968. (if org-table-follow-field-mode
  1969. (add-hook 'post-command-hook 'org-table-follow-fields-with-editor
  1970. 'append 'local)
  1971. (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
  1972. (let* ((buf (get-buffer "*Org Table Edit Field*"))
  1973. (win (and buf (get-buffer-window buf))))
  1974. (when win (delete-window win))
  1975. (when buf
  1976. (with-current-buffer buf
  1977. (move-marker org-field-marker nil))
  1978. (kill-buffer buf)))))
  1979. (defun org-table-follow-fields-with-editor ()
  1980. (if (and org-table-exit-follow-field-mode-when-leaving-table
  1981. (not (org-at-table-p)))
  1982. ;; We have left the table, exit the follow mode
  1983. (org-table-follow-field-mode -1)
  1984. (when (org-table-check-inside-data-field 'noerror)
  1985. (let ((win (selected-window)))
  1986. (org-table-edit-field nil)
  1987. (org-fit-window-to-buffer)
  1988. (select-window win)))))
  1989. (defvar org-timecnt) ; dynamically scoped parameter
  1990. ;;;###autoload
  1991. (defun org-table-sum (&optional beg end nlast)
  1992. "Sum numbers in region of current table column.
  1993. The result will be displayed in the echo area, and will be available
  1994. as kill to be inserted with \\[yank].
  1995. If there is an active region, it is interpreted as a rectangle and all
  1996. numbers in that rectangle will be summed. If there is no active
  1997. region and point is located in a table column, sum all numbers in that
  1998. column.
  1999. If at least one number looks like a time HH:MM or HH:MM:SS, all other
  2000. numbers are assumed to be times as well (in decimal hours) and the
  2001. numbers are added as such.
  2002. If NLAST is a number, only the NLAST fields will actually be summed."
  2003. (interactive)
  2004. (save-excursion
  2005. (let (col (org-timecnt 0) diff h m s org-table-clip)
  2006. (cond
  2007. ((and beg end)) ; beg and end given explicitly
  2008. ((org-region-active-p)
  2009. (setq beg (region-beginning) end (region-end)))
  2010. (t
  2011. (setq col (org-table-current-column))
  2012. (goto-char (org-table-begin))
  2013. (unless (re-search-forward "^[ \t]*|[^-]" nil t)
  2014. (user-error "No table data"))
  2015. (org-table-goto-column col)
  2016. (setq beg (point))
  2017. (goto-char (org-table-end))
  2018. (unless (re-search-backward "^[ \t]*|[^-]" nil t)
  2019. (user-error "No table data"))
  2020. (org-table-goto-column col)
  2021. (setq end (point))))
  2022. (let* ((items (apply 'append (org-table-copy-region beg end)))
  2023. (items1 (cond ((not nlast) items)
  2024. ((>= nlast (length items)) items)
  2025. (t (setq items (reverse items))
  2026. (setcdr (nthcdr (1- nlast) items) nil)
  2027. (nreverse items))))
  2028. (numbers (delq nil (mapcar 'org-table-get-number-for-summing
  2029. items1)))
  2030. (res (apply '+ numbers))
  2031. (sres (if (= org-timecnt 0)
  2032. (number-to-string res)
  2033. (setq diff (* 3600 res)
  2034. h (floor (/ diff 3600)) diff (mod diff 3600)
  2035. m (floor (/ diff 60)) diff (mod diff 60)
  2036. s diff)
  2037. (format "%.0f:%02.0f:%02.0f" h m s))))
  2038. (kill-new sres)
  2039. (when (called-interactively-p 'interactive)
  2040. (message "%s" (substitute-command-keys
  2041. (format "Sum of %d items: %-20s \
  2042. \(\\[yank] will insert result into buffer)" (length numbers) sres))))
  2043. sres))))
  2044. (defun org-table-get-number-for-summing (s)
  2045. (let (n)
  2046. (if (string-match "^ *|? *" s)
  2047. (setq s (replace-match "" nil nil s)))
  2048. (if (string-match " *|? *$" s)
  2049. (setq s (replace-match "" nil nil s)))
  2050. (setq n (string-to-number s))
  2051. (cond
  2052. ((and (string-match "0" s)
  2053. (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
  2054. ((string-match "\\`[ \t]+\\'" s) nil)
  2055. ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
  2056. (let ((h (string-to-number (or (match-string 1 s) "0")))
  2057. (m (string-to-number (or (match-string 2 s) "0")))
  2058. (s (string-to-number (or (match-string 4 s) "0"))))
  2059. (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
  2060. (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
  2061. ((equal n 0) nil)
  2062. (t n))))
  2063. (defun org-table-current-field-formula (&optional key noerror)
  2064. "Return the formula active for the current field.
  2065. Assumes that table is already analyzed. If KEY is given, return
  2066. the key to this formula. Otherwise return the formula preceded
  2067. with \"=\" or \":=\"."
  2068. (let* ((line (count-lines org-table-current-begin-pos
  2069. (line-beginning-position)))
  2070. (row (org-table-line-to-dline line)))
  2071. (cond
  2072. (row
  2073. (let* ((col (org-table-current-column))
  2074. (name (car (rassoc (list line col)
  2075. org-table-named-field-locations)))
  2076. (scol (format "$%d" col))
  2077. (ref (format "@%d$%d" (org-table-current-dline) col))
  2078. (stored-list (org-table-get-stored-formulas noerror))
  2079. (ass (or (assoc name stored-list)
  2080. (assoc ref stored-list)
  2081. (assoc scol stored-list))))
  2082. (cond (key (car ass))
  2083. (ass (concat (if (string-match-p "^[0-9]+$" (car ass)) "=" ":=")
  2084. (cdr ass))))))
  2085. (noerror nil)
  2086. (t (error "No formula active for the current field")))))
  2087. (defun org-table-get-formula (&optional equation named)
  2088. "Read a formula from the minibuffer, offer stored formula as default.
  2089. When NAMED is non-nil, look for a named equation."
  2090. (let* ((stored-list (org-table-get-stored-formulas))
  2091. (name (car (rassoc (list (count-lines org-table-current-begin-pos
  2092. (line-beginning-position))
  2093. (org-table-current-column))
  2094. org-table-named-field-locations)))
  2095. (ref (format "@%d$%d"
  2096. (org-table-current-dline)
  2097. (org-table-current-column)))
  2098. (scol (cond
  2099. ((not named) (format "$%d" (org-table-current-column)))
  2100. ((and name (not (string-match "\\`LR[0-9]+\\'" name))) name)
  2101. (t ref)))
  2102. (name (or name ref))
  2103. (org-table-may-need-update nil)
  2104. (stored (cdr (assoc scol stored-list)))
  2105. (eq (cond
  2106. ((and stored equation (string-match-p "^ *=? *$" equation))
  2107. stored)
  2108. ((stringp equation)
  2109. equation)
  2110. (t (org-table-formula-from-user
  2111. (read-string
  2112. (org-table-formula-to-user
  2113. (format "%s formula %s="
  2114. (if named "Field" "Column")
  2115. scol))
  2116. (if stored (org-table-formula-to-user stored) "")
  2117. 'org-table-formula-history
  2118. )))))
  2119. mustsave)
  2120. (when (not (string-match "\\S-" eq))
  2121. ;; remove formula
  2122. (setq stored-list (delq (assoc scol stored-list) stored-list))
  2123. (org-table-store-formulas stored-list)
  2124. (user-error "Formula removed"))
  2125. (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  2126. (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  2127. (if (and name (not named))
  2128. ;; We set the column equation, delete the named one.
  2129. (setq stored-list (delq (assoc name stored-list) stored-list)
  2130. mustsave t))
  2131. (if stored
  2132. (setcdr (assoc scol stored-list) eq)
  2133. (setq stored-list (cons (cons scol eq) stored-list)))
  2134. (if (or mustsave (not (equal stored eq)))
  2135. (org-table-store-formulas stored-list))
  2136. eq))
  2137. (defun org-table-store-formulas (alist &optional location)
  2138. "Store the list of formulas below the current table.
  2139. If optional argument LOCATION is a buffer position, insert it at
  2140. LOCATION instead."
  2141. (save-excursion
  2142. (if location
  2143. (progn (goto-char location) (beginning-of-line))
  2144. (goto-char (org-table-end)))
  2145. (let ((case-fold-search t))
  2146. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+TBLFM:\\)\\(.*\n?\\)")
  2147. (progn
  2148. ;; Don't overwrite TBLFM, we might use text properties to
  2149. ;; store stuff.
  2150. (goto-char (match-beginning 3))
  2151. (delete-region (match-beginning 3) (match-end 0)))
  2152. (org-indent-line)
  2153. (insert (or (match-string 2) "#+TBLFM:")))
  2154. (insert " "
  2155. (mapconcat (lambda (x) (concat (car x) "=" (cdr x)))
  2156. (sort alist #'org-table-formula-less-p)
  2157. "::")
  2158. "\n"))))
  2159. (defsubst org-table-formula-make-cmp-string (a)
  2160. (when (string-match "\\`$[<>]" a)
  2161. (let ((arrow (string-to-char (substring a 1))))
  2162. ;; Fake a high number to make sure this is sorted at the end.
  2163. (setq a (org-table-formula-handle-first/last-rc a))
  2164. (setq a (format "$%d" (+ 10000
  2165. (if (= arrow ?<) -1000 0)
  2166. (string-to-number (substring a 1)))))))
  2167. (when (string-match
  2168. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  2169. a)
  2170. (concat
  2171. (if (match-end 2)
  2172. (format "@%05d" (string-to-number (match-string 2 a))) "")
  2173. (if (match-end 4)
  2174. (format "$%05d" (string-to-number (match-string 4 a))) "")
  2175. (if (match-end 5)
  2176. (concat "@@" (match-string 5 a))))))
  2177. (defun org-table-formula-less-p (a b)
  2178. "Compare two formulas for sorting."
  2179. (let ((as (org-table-formula-make-cmp-string (car a)))
  2180. (bs (org-table-formula-make-cmp-string (car b))))
  2181. (and as bs (string< as bs))))
  2182. ;;;###autoload
  2183. (defun org-table-get-stored-formulas (&optional noerror location)
  2184. "Return an alist with the stored formulas directly after current table.
  2185. By default, only return active formulas, i.e., formulas located
  2186. on the first line after the table. However, if optional argument
  2187. LOCATION is a buffer position, consider the formulas there."
  2188. (save-excursion
  2189. (if location
  2190. (progn (goto-char location) (beginning-of-line))
  2191. (goto-char (org-table-end)))
  2192. (let ((case-fold-search t))
  2193. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
  2194. (let ((strings (org-split-string (match-string-no-properties 2)
  2195. " *:: *"))
  2196. eq-alist seen)
  2197. (dolist (string strings (nreverse eq-alist))
  2198. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|\\$\\([_a-zA-Z0-9]+\\|\
  2199. [<>]+\\)\\) *= *\\(.*[^ \t]\\)"
  2200. string)
  2201. (let ((lhs
  2202. (let ((m (match-string 1 string)))
  2203. (cond
  2204. ((not (match-end 2)) m)
  2205. ;; Is it a column reference?
  2206. ((string-match-p "\\`$\\([0-9]+\\|[<>]+\\)\\'" m) m)
  2207. ;; Since named columns are not possible in
  2208. ;; LHS, assume this is a named field.
  2209. (t (match-string 2 string)))))
  2210. (rhs (match-string 3 string)))
  2211. (push (cons lhs rhs) eq-alist)
  2212. (cond
  2213. ((not (member lhs seen)) (push lhs seen))
  2214. (noerror
  2215. (message
  2216. "Double definition `%s=' in TBLFM line, please fix by hand"
  2217. lhs)
  2218. (ding)
  2219. (sit-for 2))
  2220. (t
  2221. (user-error
  2222. "Double definition `%s=' in TBLFM line, please fix by hand"
  2223. lhs)))))))))))
  2224. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2225. "Modify the equations after the table structure has been edited.
  2226. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2227. For all numbers larger than LIMIT, shift them by DELTA."
  2228. (save-excursion
  2229. (goto-char (org-table-end))
  2230. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2231. (let ((msg "The formulas in #+TBLFM have been updated")
  2232. (re (concat key "\\([0-9]+\\)"))
  2233. (re2
  2234. (when remove
  2235. (if (or (equal key "$") (equal key "$LR"))
  2236. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2237. (regexp-quote key) remove)
  2238. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2239. s n a)
  2240. (when remove
  2241. (while (re-search-forward re2 (point-at-eol) t)
  2242. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2243. (if (equal (char-before (match-beginning 0)) ?.)
  2244. (user-error
  2245. "Change makes TBLFM term %s invalid, use undo to recover"
  2246. (match-string 0))
  2247. (replace-match "")))))
  2248. (while (re-search-forward re (point-at-eol) t)
  2249. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2250. (setq s (match-string 1) n (string-to-number s))
  2251. (cond
  2252. ((setq a (assoc s replace))
  2253. (replace-match (concat key (cdr a)) t t)
  2254. (message msg))
  2255. ((and limit (> n limit))
  2256. (replace-match (concat key (int-to-string (+ n delta))) t t)
  2257. (message msg))))))
  2258. (forward-line))))
  2259. ;;;###autoload
  2260. (defun org-table-maybe-eval-formula ()
  2261. "Check if the current field starts with \"=\" or \":=\".
  2262. If yes, store the formula and apply it."
  2263. ;; We already know we are in a table. Get field will only return a formula
  2264. ;; when appropriate. It might return a separator line, but no problem.
  2265. (when org-table-formula-evaluate-inline
  2266. (let* ((field (org-trim (or (org-table-get-field) "")))
  2267. named eq)
  2268. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2269. (setq named (equal (string-to-char field) ?:)
  2270. eq (match-string 1 field))
  2271. (org-table-eval-formula (and named '(4))
  2272. (org-table-formula-from-user eq))))))
  2273. (defvar org-recalc-commands nil
  2274. "List of commands triggering the recalculation of a line.
  2275. Will be filled automatically during use.")
  2276. (defvar org-recalc-marks
  2277. '((" " . "Unmarked: no special line, no automatic recalculation")
  2278. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  2279. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  2280. ("!" . "Column name definition line. Reference in formula as $name.")
  2281. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  2282. ("_" . "Names for values in row below this one.")
  2283. ("^" . "Names for values in row above this one.")))
  2284. ;;;###autoload
  2285. (defun org-table-rotate-recalc-marks (&optional newchar)
  2286. "Rotate the recalculation mark in the first column.
  2287. If in any row, the first field is not consistent with a mark,
  2288. insert a new column for the markers.
  2289. When there is an active region, change all the lines in the region,
  2290. after prompting for the marking character.
  2291. After each change, a message will be displayed indicating the meaning
  2292. of the new mark."
  2293. (interactive)
  2294. (unless (org-at-table-p) (user-error "Not at a table"))
  2295. (let* ((region (org-region-active-p))
  2296. (l1 (and region
  2297. (save-excursion (goto-char (region-beginning))
  2298. (copy-marker (line-beginning-position)))))
  2299. (l2 (and region
  2300. (save-excursion (goto-char (region-end))
  2301. (copy-marker (line-beginning-position)))))
  2302. (l (copy-marker (line-beginning-position)))
  2303. (col (org-table-current-column))
  2304. (newchar (if region
  2305. (char-to-string
  2306. (read-char-exclusive
  2307. "Change region to what mark? Type # * ! $ or SPC: "))
  2308. newchar))
  2309. (no-special-column
  2310. (save-excursion
  2311. (goto-char (org-table-begin))
  2312. (re-search-forward
  2313. "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
  2314. (when (and newchar (not (assoc newchar org-recalc-marks)))
  2315. (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
  2316. newchar))
  2317. (when l1 (goto-char l1))
  2318. (save-excursion
  2319. (beginning-of-line)
  2320. (unless (looking-at org-table-dataline-regexp)
  2321. (user-error "Not at a table data line")))
  2322. (when no-special-column
  2323. (org-table-goto-column 1)
  2324. (org-table-insert-column))
  2325. (let ((previous-line-end (line-end-position))
  2326. (newchar
  2327. (save-excursion
  2328. (beginning-of-line)
  2329. (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
  2330. (newchar)
  2331. (t (cadr (member (match-string 1)
  2332. (append (mapcar #'car org-recalc-marks)
  2333. '(" ")))))))))
  2334. ;; Rotate mark in first row.
  2335. (org-table-get-field 1 (format " %s " newchar))
  2336. ;; Rotate marks in additional rows if a region is active.
  2337. (when region
  2338. (save-excursion
  2339. (forward-line)
  2340. (while (<= (point) l2)
  2341. (when (looking-at org-table-dataline-regexp)
  2342. (org-table-get-field 1 (format " %s " newchar)))
  2343. (forward-line))))
  2344. ;; Only align if rotation actually changed lines' length.
  2345. (when (/= previous-line-end (line-end-position)) (org-table-align)))
  2346. (goto-char l)
  2347. (org-table-goto-column (if no-special-column (1+ col) col))
  2348. (when l1 (set-marker l1 nil))
  2349. (when l2 (set-marker l2 nil))
  2350. (set-marker l nil)
  2351. (when (called-interactively-p 'interactive)
  2352. (message "%s" (cdr (assoc newchar org-recalc-marks))))))
  2353. ;;;###autoload
  2354. (defun org-table-analyze ()
  2355. "Analyze table at point and store results.
  2356. This function sets up the following dynamically scoped variables:
  2357. `org-table-column-name-regexp',
  2358. `org-table-column-names',
  2359. `org-table-current-begin-pos',
  2360. `org-table-current-line-types',
  2361. `org-table-current-ncol',
  2362. `org-table-dlines',
  2363. `org-table-hlines',
  2364. `org-table-local-parameters',
  2365. `org-table-named-field-locations'."
  2366. (let ((beg (org-table-begin))
  2367. (end (org-table-end)))
  2368. (save-excursion
  2369. (goto-char beg)
  2370. ;; Extract column names.
  2371. (setq org-table-column-names nil)
  2372. (when (save-excursion
  2373. (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
  2374. (let ((c 1))
  2375. (dolist (name (org-split-string (match-string 1) " *| *"))
  2376. (cl-incf c)
  2377. (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
  2378. (push (cons name (int-to-string c)) org-table-column-names)))))
  2379. (setq org-table-column-names (nreverse org-table-column-names))
  2380. (setq org-table-column-name-regexp
  2381. (format "\\$\\(%s\\)\\>"
  2382. (regexp-opt (mapcar #'car org-table-column-names) t)))
  2383. ;; Extract local parameters.
  2384. (setq org-table-local-parameters nil)
  2385. (save-excursion
  2386. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  2387. (dolist (field (org-split-string (match-string 1) " *| *"))
  2388. (when (string-match
  2389. "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  2390. (push (cons (match-string 1 field) (match-string 2 field))
  2391. org-table-local-parameters)))))
  2392. ;; Update named fields locations. We minimize `count-lines'
  2393. ;; processing by storing last known number of lines in LAST.
  2394. (setq org-table-named-field-locations nil)
  2395. (save-excursion
  2396. (let ((last (cons (point) 0)))
  2397. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  2398. (let ((c (match-string 1))
  2399. (fields (org-split-string (match-string 2) " *| *")))
  2400. (save-excursion
  2401. (forward-line (if (equal c "_") 1 -1))
  2402. (let ((fields1
  2403. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  2404. (org-split-string (match-string 1) " *| *")))
  2405. (line (cl-incf (cdr last) (count-lines (car last) (point))))
  2406. (col 1))
  2407. (setcar last (point)) ; Update last known position.
  2408. (while (and fields fields1)
  2409. (let ((field (pop fields))
  2410. (v (pop fields1)))
  2411. (cl-incf col)
  2412. (when (and (stringp field)
  2413. (stringp v)
  2414. (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
  2415. field))
  2416. (push (cons field v) org-table-local-parameters)
  2417. (push (list field line col)
  2418. org-table-named-field-locations))))))))))
  2419. ;; Re-use existing markers when possible.
  2420. (if (markerp org-table-current-begin-pos)
  2421. (move-marker org-table-current-begin-pos (point))
  2422. (setq org-table-current-begin-pos (point-marker)))
  2423. ;; Analyze the line types.
  2424. (let ((l 0) hlines dlines types)
  2425. (while (looking-at "[ \t]*|\\(-\\)?")
  2426. (push (if (match-end 1) 'hline 'dline) types)
  2427. (if (match-end 1) (push l hlines) (push l dlines))
  2428. (forward-line)
  2429. (cl-incf l))
  2430. (push 'hline types) ; Add an imaginary extra hline to the end.
  2431. (setq org-table-current-line-types (apply #'vector (nreverse types)))
  2432. (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
  2433. (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
  2434. ;; Get the number of columns from the first data line in table.
  2435. (goto-char beg)
  2436. (forward-line (aref org-table-dlines 1))
  2437. (let* ((fields
  2438. (org-split-string
  2439. (buffer-substring (line-beginning-position) (line-end-position))
  2440. "[ \t]*|[ \t]*"))
  2441. (nfields (length fields))
  2442. al al2)
  2443. (setq org-table-current-ncol nfields)
  2444. (let ((last-dline
  2445. (aref org-table-dlines (1- (length org-table-dlines)))))
  2446. (dotimes (i nfields)
  2447. (let ((column (1+ i)))
  2448. (push (list (format "LR%d" column) last-dline column) al)
  2449. (push (cons (format "LR%d" column) (nth i fields)) al2))))
  2450. (setq org-table-named-field-locations
  2451. (append org-table-named-field-locations al))
  2452. (setq org-table-local-parameters
  2453. (append org-table-local-parameters al2))))))
  2454. (defun org-table-goto-field (ref &optional create-column-p)
  2455. "Move point to a specific field in the current table.
  2456. REF is either the name of a field its absolute reference, as
  2457. a string. No column is created unless CREATE-COLUMN-P is
  2458. non-nil. If it is a function, it is called with the column
  2459. number as its argument as is used as a predicate to know if the
  2460. column can be created.
  2461. This function assumes the table is already analyzed (i.e., using
  2462. `org-table-analyze')."
  2463. (let* ((coordinates
  2464. (cond
  2465. ((cdr (assoc ref org-table-named-field-locations)))
  2466. ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
  2467. (list (condition-case nil
  2468. (aref org-table-dlines
  2469. (string-to-number (match-string 1 ref)))
  2470. (error (user-error "Invalid row number in %s" ref)))
  2471. (string-to-number (match-string 2 ref))))
  2472. (t (user-error "Unknown field: %s" ref))))
  2473. (line (car coordinates))
  2474. (column (nth 1 coordinates))
  2475. (create-new-column (if (functionp create-column-p)
  2476. (funcall create-column-p column)
  2477. create-column-p)))
  2478. (when coordinates
  2479. (goto-char org-table-current-begin-pos)
  2480. (forward-line line)
  2481. (org-table-goto-column column nil create-new-column))))
  2482. ;;;###autoload
  2483. (defun org-table-maybe-recalculate-line ()
  2484. "Recompute the current line if marked for it, and if we haven't just done it."
  2485. (interactive)
  2486. (and org-table-allow-automatic-line-recalculation
  2487. (not (and (memq last-command org-recalc-commands)
  2488. (eq org-last-recalc-line (line-beginning-position))))
  2489. (save-excursion (beginning-of-line 1)
  2490. (looking-at org-table-auto-recalculate-regexp))
  2491. (org-table-recalculate) t))
  2492. (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
  2493. (defsubst org-set-calc-mode (var &optional value)
  2494. (if (stringp var)
  2495. (setq var (assoc var '(("D" calc-angle-mode deg)
  2496. ("R" calc-angle-mode rad)
  2497. ("F" calc-prefer-frac t)
  2498. ("S" calc-symbolic-mode t)))
  2499. value (nth 2 var) var (nth 1 var)))
  2500. (if (memq var org-tbl-calc-modes)
  2501. (setcar (cdr (memq var org-tbl-calc-modes)) value)
  2502. (cons var (cons value org-tbl-calc-modes)))
  2503. org-tbl-calc-modes)
  2504. ;;;###autoload
  2505. (defun org-table-eval-formula (&optional arg equation
  2506. suppress-align suppress-const
  2507. suppress-store suppress-analysis)
  2508. "Replace the table field value at the cursor by the result of a calculation.
  2509. In a table, this command replaces the value in the current field with the
  2510. result of a formula. It also installs the formula as the \"current\" column
  2511. formula, by storing it in a special line below the table. When called
  2512. with a `\\[universal-argument]' prefix the formula is installed as a \
  2513. field formula.
  2514. When called with a `\\[universal-argument] \\[universal-argument]' prefix, \
  2515. insert the active equation for the field
  2516. back into the current field, so that it can be edited there. This is \
  2517. useful
  2518. in order to use \\<org-table-fedit-map>`\\[org-table-show-reference]' to \
  2519. check the referenced fields.
  2520. When called, the command first prompts for a formula, which is read in
  2521. the minibuffer. Previously entered formulas are available through the
  2522. history list, and the last used formula is offered as a default.
  2523. These stored formulas are adapted correctly when moving, inserting, or
  2524. deleting columns with the corresponding commands.
  2525. The formula can be any algebraic expression understood by the Calc package.
  2526. For details, see the Org mode manual.
  2527. This function can also be called from Lisp programs and offers
  2528. additional arguments: EQUATION can be the formula to apply. If this
  2529. argument is given, the user will not be prompted.
  2530. SUPPRESS-ALIGN is used to speed-up recursive calls by by-passing
  2531. unnecessary aligns.
  2532. SUPPRESS-CONST suppresses the interpretation of constants in the
  2533. formula, assuming that this has been done already outside the
  2534. function.
  2535. SUPPRESS-STORE means the formula should not be stored, either
  2536. because it is already stored, or because it is a modified
  2537. equation that should not overwrite the stored one.
  2538. SUPPRESS-ANALYSIS prevents analyzing the table and checking
  2539. location of point."
  2540. (interactive "P")
  2541. (unless suppress-analysis
  2542. (org-table-check-inside-data-field nil t)
  2543. (org-table-analyze))
  2544. (if (equal arg '(16))
  2545. (let ((eq (org-table-current-field-formula)))
  2546. (org-table-get-field nil eq)
  2547. (org-table-align)
  2548. (setq org-table-may-need-update t))
  2549. (let* (fields
  2550. (ndown (if (integerp arg) arg 1))
  2551. (org-table-automatic-realign nil)
  2552. (case-fold-search nil)
  2553. (down (> ndown 1))
  2554. (formula (if (and equation suppress-store)
  2555. equation
  2556. (org-table-get-formula equation (equal arg '(4)))))
  2557. (n0 (org-table-current-column))
  2558. (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
  2559. (numbers nil) ; was a variable, now fixed default
  2560. (keep-empty nil)
  2561. n form form0 formrpl formrg bw fmt x ev orig c lispp literal
  2562. duration duration-output-format)
  2563. ;; Parse the format string. Since we have a lot of modes, this is
  2564. ;; a lot of work. However, I think calc still uses most of the time.
  2565. (if (string-match ";" formula)
  2566. (let ((tmp (org-split-string formula ";")))
  2567. (setq formula (car tmp)
  2568. fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2569. (nth 1 tmp)))
  2570. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2571. (setq c (string-to-char (match-string 1 fmt))
  2572. n (string-to-number (match-string 2 fmt)))
  2573. (if (= c ?p)
  2574. (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
  2575. (setq org-tbl-calc-modes
  2576. (org-set-calc-mode
  2577. 'calc-float-format
  2578. (list (cdr (assoc c '((?n . float) (?f . fix)
  2579. (?s . sci) (?e . eng))))
  2580. n))))
  2581. (setq fmt (replace-match "" t t fmt)))
  2582. (if (string-match "[tTU]" fmt)
  2583. (let ((ff (match-string 0 fmt)))
  2584. (setq duration t numbers t
  2585. duration-output-format
  2586. (cond ((equal ff "T") nil)
  2587. ((equal ff "t") org-table-duration-custom-format)
  2588. ((equal ff "U") 'hh:mm))
  2589. fmt (replace-match "" t t fmt))))
  2590. (if (string-match "N" fmt)
  2591. (setq numbers t
  2592. fmt (replace-match "" t t fmt)))
  2593. (if (string-match "L" fmt)
  2594. (setq literal t
  2595. fmt (replace-match "" t t fmt)))
  2596. (if (string-match "E" fmt)
  2597. (setq keep-empty t
  2598. fmt (replace-match "" t t fmt)))
  2599. (while (string-match "[DRFS]" fmt)
  2600. (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
  2601. (setq fmt (replace-match "" t t fmt)))
  2602. (unless (string-match "\\S-" fmt)
  2603. (setq fmt nil))))
  2604. (when (and (not suppress-const) org-table-formula-use-constants)
  2605. (setq formula (org-table-formula-substitute-names formula)))
  2606. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2607. (setq formula (org-table-formula-handle-first/last-rc formula))
  2608. (while (> ndown 0)
  2609. (setq fields (org-split-string
  2610. (org-trim
  2611. (buffer-substring-no-properties
  2612. (line-beginning-position) (line-end-position)))
  2613. " *| *"))
  2614. ;; replace fields with duration values if relevant
  2615. (if duration
  2616. (setq fields
  2617. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2618. fields)))
  2619. (if (eq numbers t)
  2620. (setq fields (mapcar
  2621. (lambda (x)
  2622. (if (string-match "\\S-" x)
  2623. (number-to-string (string-to-number x))
  2624. x))
  2625. fields)))
  2626. (setq ndown (1- ndown))
  2627. (setq form (copy-sequence formula)
  2628. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2629. (if (and lispp literal) (setq lispp 'literal))
  2630. ;; Insert row and column number of formula result field
  2631. (while (string-match "[@$]#" form)
  2632. (setq form
  2633. (replace-match
  2634. (format "%d"
  2635. (save-match-data
  2636. (if (equal (substring form (match-beginning 0)
  2637. (1+ (match-beginning 0)))
  2638. "@")
  2639. (org-table-current-dline)
  2640. (org-table-current-column))))
  2641. t t form)))
  2642. ;; Check for old vertical references
  2643. (org-table--error-on-old-row-references form)
  2644. ;; Insert remote references
  2645. (setq form (org-table-remote-reference-indirection form))
  2646. (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2647. (setq form
  2648. (replace-match
  2649. (save-match-data
  2650. (org-table-make-reference
  2651. (let ((rmtrng (org-table-get-remote-range
  2652. (match-string 1 form) (match-string 2 form))))
  2653. (if duration
  2654. (if (listp rmtrng)
  2655. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2656. (org-table-time-string-to-seconds rmtrng))
  2657. rmtrng))
  2658. keep-empty numbers lispp))
  2659. t t form)))
  2660. ;; Insert complex ranges
  2661. (while (and (string-match org-table-range-regexp form)
  2662. (> (length (match-string 0 form)) 1))
  2663. (setq formrg
  2664. (save-match-data
  2665. (org-table-get-range
  2666. (match-string 0 form) org-table-current-begin-pos n0)))
  2667. (setq formrpl
  2668. (save-match-data
  2669. (org-table-make-reference
  2670. ;; possibly handle durations
  2671. (if duration
  2672. (if (listp formrg)
  2673. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2674. (org-table-time-string-to-seconds formrg))
  2675. formrg)
  2676. keep-empty numbers lispp)))
  2677. (if (not (save-match-data
  2678. (string-match (regexp-quote form) formrpl)))
  2679. (setq form (replace-match formrpl t t form))
  2680. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2681. ;; Insert simple ranges, i.e. included in the current row.
  2682. (while (string-match
  2683. "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
  2684. form)
  2685. (setq form
  2686. (replace-match
  2687. (save-match-data
  2688. (org-table-make-reference
  2689. (cl-subseq fields
  2690. (+ (if (match-end 2) n0 0)
  2691. (string-to-number (match-string 1 form))
  2692. -1)
  2693. (+ (if (match-end 4) n0 0)
  2694. (string-to-number (match-string 3 form))))
  2695. keep-empty numbers lispp))
  2696. t t form)))
  2697. (setq form0 form)
  2698. ;; Insert the references to fields in same row
  2699. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2700. (setq n (+ (string-to-number (match-string 1 form))
  2701. (if (match-end 2) n0 0))
  2702. x (nth (1- (if (= n 0) n0 (max n 1))) fields)
  2703. formrpl (save-match-data
  2704. (org-table-make-reference
  2705. x keep-empty numbers lispp)))
  2706. (when (or (not x)
  2707. (save-match-data
  2708. (string-match (regexp-quote formula) formrpl)))
  2709. (user-error "Invalid field specifier \"%s\""
  2710. (match-string 0 form)))
  2711. (setq form (replace-match formrpl t t form)))
  2712. (if lispp
  2713. (setq ev (condition-case nil
  2714. (eval (eval (read form)))
  2715. (error "#ERROR"))
  2716. ev (if (numberp ev) (number-to-string ev) ev)
  2717. ev (if duration (org-table-time-seconds-to-string
  2718. (string-to-number ev)
  2719. duration-output-format) ev))
  2720. ;; Use <...> time-stamps so that Calc can handle them.
  2721. (setq form
  2722. (replace-regexp-in-string org-ts-regexp-inactive "<\\1>" form))
  2723. ;; Internationalize local time-stamps by setting locale to
  2724. ;; "C".
  2725. (setq form
  2726. (replace-regexp-in-string
  2727. org-ts-regexp
  2728. (lambda (ts)
  2729. (let ((system-time-locale "C"))
  2730. (format-time-string
  2731. (org-time-stamp-format
  2732. (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2733. (apply #'encode-time
  2734. (save-match-data (org-parse-time-string ts))))))
  2735. form t t))
  2736. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2737. form
  2738. (calc-eval (cons form org-tbl-calc-modes)
  2739. (when (and (not keep-empty) numbers) 'num)))
  2740. ev (if duration (org-table-time-seconds-to-string
  2741. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2742. (string-to-number (org-table-time-string-to-seconds ev))
  2743. (string-to-number ev))
  2744. duration-output-format)
  2745. ev)))
  2746. (when org-table-formula-debug
  2747. (with-output-to-temp-buffer "*Substitution History*"
  2748. (princ (format "Substitution history of formula
  2749. Orig: %s
  2750. $xyz-> %s
  2751. @r$c-> %s
  2752. $1-> %s\n" orig formula form0 form))
  2753. (if (consp ev)
  2754. (princ (format " %s^\nError: %s"
  2755. (make-string (car ev) ?\-) (nth 1 ev)))
  2756. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2757. ev (or fmt "NONE")
  2758. (if fmt (format fmt (string-to-number ev)) ev)))))
  2759. (setq bw (get-buffer-window "*Substitution History*"))
  2760. (org-fit-window-to-buffer bw)
  2761. (unless (and (called-interactively-p 'any) (not ndown))
  2762. (unless (let (inhibit-redisplay)
  2763. (y-or-n-p "Debugging Formula. Continue to next? "))
  2764. (org-table-align)
  2765. (user-error "Abort"))
  2766. (delete-window bw)
  2767. (message "")))
  2768. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2769. (org-table-justify-field-maybe
  2770. (format org-table-formula-field-format
  2771. (cond
  2772. ((not (stringp ev)) ev)
  2773. (fmt (format fmt (string-to-number ev)))
  2774. ;; Replace any active time stamp in the result with
  2775. ;; an inactive one. Dates in tables are likely
  2776. ;; piece of regular data, not meant to appear in the
  2777. ;; agenda.
  2778. (t (replace-regexp-in-string org-ts-regexp "[\\1]" ev)))))
  2779. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2780. (call-interactively 'org-return)
  2781. (setq ndown 0)))
  2782. (and down (org-table-maybe-recalculate-line))
  2783. (or suppress-align (and org-table-may-need-update
  2784. (org-table-align))))))
  2785. (defun org-table-put-field-property (prop value)
  2786. (save-excursion
  2787. (put-text-property (progn (skip-chars-backward "^|") (point))
  2788. (progn (skip-chars-forward "^|") (point))
  2789. prop value)))
  2790. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2791. "Get a calc vector from a column, according to descriptor DESC.
  2792. Optional arguments TBEG and COL can give the beginning of the table and
  2793. the current column, to avoid unnecessary parsing.
  2794. HIGHLIGHT means just highlight the range.
  2795. When CORNERS-ONLY is set, only return the corners of the range as
  2796. a list (line1 column1 line2 column2) where line1 and line2 are
  2797. line numbers relative to beginning of table, or TBEG, and column1
  2798. and column2 are table column numbers."
  2799. (let* ((desc (if (string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
  2800. (replace-regexp-in-string "\\$" "@0$" desc)
  2801. desc))
  2802. (col (or col (org-table-current-column)))
  2803. (tbeg (or tbeg (org-table-begin)))
  2804. (thisline (count-lines tbeg (line-beginning-position))))
  2805. (unless (string-match org-table-range-regexp desc)
  2806. (user-error "Invalid table range specifier `%s'" desc))
  2807. (let ((rangep (match-end 3))
  2808. (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
  2809. (or (save-match-data
  2810. (and (org-string-nw-p r)
  2811. (org-table--descriptor-line r thisline)))
  2812. thisline)))
  2813. (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
  2814. (or (save-match-data
  2815. (and (org-string-nw-p r)
  2816. (org-table--descriptor-line r thisline)))
  2817. thisline)))
  2818. (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
  2819. (if (or (not c) (= (string-to-number c) 0)) col
  2820. (+ (string-to-number c)
  2821. (if (memq (string-to-char c) '(?- ?+)) col 0)))))
  2822. (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
  2823. (if (or (not c) (= (string-to-number c) 0)) col
  2824. (+ (string-to-number c)
  2825. (if (memq (string-to-char c) '(?- ?+)) col 0))))))
  2826. (save-excursion
  2827. (if (and (not corners-only)
  2828. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2829. ;; Just one field.
  2830. (progn
  2831. (forward-line (- r1 thisline))
  2832. (while (not (looking-at org-table-dataline-regexp))
  2833. (forward-line))
  2834. (prog1 (org-trim (org-table-get-field c1))
  2835. (when highlight (org-table-highlight-rectangle))))
  2836. ;; A range, return a vector. First sort the numbers to get
  2837. ;; a regular rectangle.
  2838. (let ((first-row (min r1 r2))
  2839. (last-row (max r1 r2))
  2840. (first-column (min c1 c2))
  2841. (last-column (max c1 c2)))
  2842. (if corners-only (list first-row first-column last-row last-column)
  2843. ;; Copy the range values into a list.
  2844. (forward-line (- first-row thisline))
  2845. (while (not (looking-at org-table-dataline-regexp))
  2846. (forward-line)
  2847. (cl-incf first-row))
  2848. (org-table-goto-column first-column)
  2849. (let ((beg (point)))
  2850. (forward-line (- last-row first-row))
  2851. (while (not (looking-at org-table-dataline-regexp))
  2852. (forward-line -1))
  2853. (org-table-goto-column last-column)
  2854. (let ((end (point)))
  2855. (when highlight
  2856. (org-table-highlight-rectangle
  2857. beg (progn (skip-chars-forward "^|\n") (point))))
  2858. ;; Return string representation of calc vector.
  2859. (mapcar #'org-trim
  2860. (apply #'append
  2861. (org-table-copy-region beg end))))))))))))
  2862. (defun org-table--descriptor-line (desc cline)
  2863. "Return relative line number corresponding to descriptor DESC.
  2864. The cursor is currently in relative line number CLINE."
  2865. (if (string-match "\\`[0-9]+\\'" desc)
  2866. (aref org-table-dlines (string-to-number desc))
  2867. (when (or (not (string-match
  2868. "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
  2869. ;; 1 2 3 4 5 6
  2870. desc))
  2871. (and (not (match-end 3)) (not (match-end 6)))
  2872. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2873. (user-error "Invalid row descriptor `%s'" desc))
  2874. (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
  2875. (hdir (match-string 2 desc))
  2876. (odir (match-string 5 desc))
  2877. (on (and (match-end 6) (string-to-number (match-string 6 desc))))
  2878. (rel (and (match-end 6)
  2879. (or (and (match-end 1) (not (match-end 3)))
  2880. (match-end 5)))))
  2881. (when (and hn (not hdir))
  2882. (setq cline 0)
  2883. (setq hdir "+")
  2884. (when (eq (aref org-table-current-line-types 0) 'hline) (cl-decf hn)))
  2885. (when (and (not hn) on (not odir)) (user-error "Should never happen"))
  2886. (when hn
  2887. (setq cline
  2888. (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
  2889. (when on
  2890. (setq cline
  2891. (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
  2892. cline)))
  2893. (defun org-table--row-type (type n i backwards relative desc)
  2894. "Return relative line of Nth row with type TYPE.
  2895. Search starts from relative line I. When BACKWARDS in non-nil,
  2896. look before I. When RELATIVE is non-nil, the reference is
  2897. relative. DESC is the original descriptor that started the
  2898. search, as a string."
  2899. (let ((l (length org-table-current-line-types)))
  2900. (catch :exit
  2901. (dotimes (_ n)
  2902. (while (and (cl-incf i (if backwards -1 1))
  2903. (>= i 0)
  2904. (< i l)
  2905. (not (eq (aref org-table-current-line-types i) type))
  2906. ;; We are going to cross a hline. Check if this is
  2907. ;; an authorized move.
  2908. (cond
  2909. ((not relative))
  2910. ((not (eq (aref org-table-current-line-types i) 'hline)))
  2911. ((eq org-table-relative-ref-may-cross-hline t))
  2912. ((eq org-table-relative-ref-may-cross-hline 'error)
  2913. (user-error "Row descriptor %s crosses hline" desc))
  2914. (t (cl-decf i (if backwards -1 1)) ; Step back.
  2915. (throw :exit nil)))))))
  2916. (cond ((or (< i 0) (>= i l))
  2917. (user-error "Row descriptor %s leads outside table" desc))
  2918. ;; The last hline doesn't exist. Instead, point to last row
  2919. ;; in table.
  2920. ((= i (1- l)) (1- i))
  2921. (t i))))
  2922. (defun org-table--error-on-old-row-references (s)
  2923. (when (string-match "&[-+0-9I]" s)
  2924. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2925. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2926. "Convert list ELEMENTS to something appropriate to insert into formula.
  2927. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2928. NUMBERS indicates that everything should be converted to numbers.
  2929. LISPP non-nil means to return something appropriate for a Lisp
  2930. list, `literal' is for the format specifier L."
  2931. ;; Calc nan (not a number) is used for the conversion of the empty
  2932. ;; field to a reference for several reasons: (i) It is accepted in a
  2933. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2934. ;; (ii) In a single field (not in range) it can be distinguished
  2935. ;; from "(nan)" which is the reference made from a single field
  2936. ;; containing "nan".
  2937. (if (stringp elements)
  2938. ;; field reference
  2939. (if lispp
  2940. (if (eq lispp 'literal)
  2941. elements
  2942. (if (and (eq elements "") (not keep-empty))
  2943. ""
  2944. (prin1-to-string
  2945. (if numbers (string-to-number elements) elements))))
  2946. (if (string-match "\\S-" elements)
  2947. (progn
  2948. (when numbers (setq elements (number-to-string
  2949. (string-to-number elements))))
  2950. (concat "(" elements ")"))
  2951. (if (or (not keep-empty) numbers) "(0)" "nan")))
  2952. ;; range reference
  2953. (unless keep-empty
  2954. (setq elements
  2955. (delq nil
  2956. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2957. elements))))
  2958. (setq elements (or elements '())) ; if delq returns nil then we need '()
  2959. (if lispp
  2960. (mapconcat
  2961. (lambda (x)
  2962. (if (eq lispp 'literal)
  2963. x
  2964. (prin1-to-string (if numbers (string-to-number x) x))))
  2965. elements " ")
  2966. (concat "[" (mapconcat
  2967. (lambda (x)
  2968. (if (string-match "\\S-" x)
  2969. (if numbers
  2970. (number-to-string (string-to-number x))
  2971. x)
  2972. (if (or (not keep-empty) numbers) "0" "nan")))
  2973. elements
  2974. ",") "]"))))
  2975. (defun org-table-message-once-per-second (t1 &rest args)
  2976. "If there has been more than one second since T1, display message.
  2977. ARGS are passed as arguments to the `message' function. Returns
  2978. current time if a message is printed, otherwise returns T1. If
  2979. T1 is nil, always messages."
  2980. (let ((curtime (current-time)))
  2981. (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
  2982. (progn (apply 'message args)
  2983. curtime)
  2984. t1)))
  2985. ;;;###autoload
  2986. (defun org-table-recalculate (&optional all noalign)
  2987. "Recalculate the current table line by applying all stored formulas.
  2988. With prefix arg ALL, do this for all lines in the table.
  2989. When called with a `\\[universal-argument] \\[universal-argument]' prefix, or \
  2990. if ALL is the symbol `iterate',
  2991. recompute the table until it no longer changes.
  2992. If NOALIGN is not nil, do not re-align the table after the computations
  2993. are done. This is typically used internally to save time, if it is
  2994. known that the table will be realigned a little later anyway."
  2995. (interactive "P")
  2996. (unless (memq this-command org-recalc-commands)
  2997. (push this-command org-recalc-commands))
  2998. (unless (org-at-table-p) (user-error "Not at a table"))
  2999. (if (or (eq all 'iterate) (equal all '(16)))
  3000. (org-table-iterate)
  3001. (org-table-analyze)
  3002. (let* ((eqlist (sort (org-table-get-stored-formulas)
  3003. (lambda (a b) (string< (car a) (car b)))))
  3004. (inhibit-redisplay (not debug-on-error))
  3005. (line-re org-table-dataline-regexp)
  3006. (log-first-time (current-time))
  3007. (log-last-time log-first-time)
  3008. (cnt 0)
  3009. beg end eqlcol eqlfield)
  3010. ;; Insert constants in all formulas.
  3011. (when eqlist
  3012. (org-table-save-field
  3013. ;; Expand equations, then split the equation list between
  3014. ;; column formulas and field formulas.
  3015. (dolist (eq eqlist)
  3016. (let* ((rhs (org-table-formula-substitute-names
  3017. (org-table-formula-handle-first/last-rc (cdr eq))))
  3018. (old-lhs (car eq))
  3019. (lhs
  3020. (org-table-formula-handle-first/last-rc
  3021. (cond
  3022. ((string-match "\\`@-?I+" old-lhs)
  3023. (user-error "Can't assign to hline relative reference"))
  3024. ((string-match "\\`$[<>]" old-lhs)
  3025. (let ((new (org-table-formula-handle-first/last-rc
  3026. old-lhs)))
  3027. (when (assoc new eqlist)
  3028. (user-error "\"%s=\" formula tries to overwrite \
  3029. existing formula for column %s"
  3030. old-lhs
  3031. new))
  3032. new))
  3033. (t old-lhs)))))
  3034. (if (string-match-p "\\`\\$[0-9]+\\'" lhs)
  3035. (push (cons lhs rhs) eqlcol)
  3036. (push (cons lhs rhs) eqlfield))))
  3037. (setq eqlcol (nreverse eqlcol))
  3038. ;; Expand ranges in lhs of formulas
  3039. (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
  3040. ;; Get the correct line range to process.
  3041. (if all
  3042. (progn
  3043. (setq end (copy-marker (org-table-end)))
  3044. (goto-char (setq beg org-table-current-begin-pos))
  3045. (cond
  3046. ((re-search-forward org-table-calculate-mark-regexp end t)
  3047. ;; This is a table with marked lines, compute selected
  3048. ;; lines.
  3049. (setq line-re org-table-recalculate-regexp))
  3050. ;; Move forward to the first non-header line.
  3051. ((and (re-search-forward org-table-dataline-regexp end t)
  3052. (re-search-forward org-table-hline-regexp end t)
  3053. (re-search-forward org-table-dataline-regexp end t))
  3054. (setq beg (match-beginning 0)))
  3055. ;; Just leave BEG at the start of the table.
  3056. (t nil)))
  3057. (setq beg (line-beginning-position)
  3058. end (copy-marker (line-beginning-position 2))))
  3059. (goto-char beg)
  3060. ;; Mark named fields untouchable. Also check if several
  3061. ;; field/range formulas try to set the same field.
  3062. (remove-text-properties beg end '(:org-untouchable t))
  3063. (let ((current-line (count-lines org-table-current-begin-pos
  3064. (line-beginning-position)))
  3065. seen-fields)
  3066. (dolist (eq eqlfield)
  3067. (let* ((name (car eq))
  3068. (location (assoc name org-table-named-field-locations))
  3069. (eq-line (or (nth 1 location)
  3070. (and (string-match "\\`@\\([0-9]+\\)" name)
  3071. (aref org-table-dlines
  3072. (string-to-number
  3073. (match-string 1 name))))))
  3074. (reference
  3075. (if location
  3076. ;; Turn field coordinates associated to NAME
  3077. ;; into an absolute reference.
  3078. (format "@%d$%d"
  3079. (org-table-line-to-dline eq-line)
  3080. (nth 2 location))
  3081. name)))
  3082. (when (member reference seen-fields)
  3083. (user-error "Several field/range formulas try to set %s"
  3084. reference))
  3085. (push reference seen-fields)
  3086. (when (or all (eq eq-line current-line))
  3087. (org-table-goto-field name)
  3088. (org-table-put-field-property :org-untouchable t)))))
  3089. ;; Evaluate the column formulas, but skip fields covered by
  3090. ;; field formulas.
  3091. (goto-char beg)
  3092. (while (re-search-forward line-re end t)
  3093. (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
  3094. ;; Unprotected line, recalculate.
  3095. (cl-incf cnt)
  3096. (when all
  3097. (setq log-last-time
  3098. (org-table-message-once-per-second
  3099. log-last-time
  3100. "Re-applying formulas to full table...(line %d)" cnt)))
  3101. (if (markerp org-last-recalc-line)
  3102. (move-marker org-last-recalc-line (line-beginning-position))
  3103. (setq org-last-recalc-line
  3104. (copy-marker (line-beginning-position))))
  3105. (dolist (entry eqlcol)
  3106. (goto-char org-last-recalc-line)
  3107. (org-table-goto-column
  3108. (string-to-number (substring (car entry) 1)) nil 'force)
  3109. (unless (get-text-property (point) :org-untouchable)
  3110. (org-table-eval-formula
  3111. nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
  3112. ;; Evaluate the field formulas.
  3113. (dolist (eq eqlfield)
  3114. (let ((reference (car eq))
  3115. (formula (cdr eq)))
  3116. (setq log-last-time
  3117. (org-table-message-once-per-second
  3118. (and all log-last-time)
  3119. "Re-applying formula to field: %s" (car eq)))
  3120. (org-table-goto-field
  3121. reference
  3122. ;; Possibly create a new column, as long as
  3123. ;; `org-table-formula-create-columns' allows it.
  3124. (let ((column-count (progn (end-of-line)
  3125. (1- (org-table-current-column)))))
  3126. (lambda (column)
  3127. (when (> column 1000)
  3128. (user-error "Formula column target too large"))
  3129. (and (> column column-count)
  3130. (or (eq org-table-formula-create-columns t)
  3131. (and (eq org-table-formula-create-columns 'warn)
  3132. (progn
  3133. (org-display-warning
  3134. "Out-of-bounds formula added columns")
  3135. t))
  3136. (and (eq org-table-formula-create-columns 'prompt)
  3137. (yes-or-no-p
  3138. "Out-of-bounds formula. Add columns? "))
  3139. (user-error
  3140. "Missing columns in the table. Aborting"))))))
  3141. (org-table-eval-formula nil formula t t t t))))
  3142. ;; Clean up markers and internal text property.
  3143. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  3144. (set-marker end nil)
  3145. (unless noalign
  3146. (when org-table-may-need-update (org-table-align))
  3147. (when all
  3148. (org-table-message-once-per-second
  3149. log-first-time "Re-applying formulas to %d lines... done" cnt)))
  3150. (org-table-message-once-per-second
  3151. (and all log-first-time) "Re-applying formulas... done")))))
  3152. ;;;###autoload
  3153. (defun org-table-iterate (&optional arg)
  3154. "Recalculate the table until it does not change anymore.
  3155. The maximum number of iterations is 10, but you can choose a different value
  3156. with the prefix ARG."
  3157. (interactive "P")
  3158. (let ((imax (if arg (prefix-numeric-value arg) 10))
  3159. (i 0)
  3160. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  3161. thistbl)
  3162. (catch 'exit
  3163. (while (< i imax)
  3164. (setq i (1+ i))
  3165. (org-table-recalculate 'all)
  3166. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  3167. (if (not (string= lasttbl thistbl))
  3168. (setq lasttbl thistbl)
  3169. (if (> i 1)
  3170. (message "Convergence after %d iterations" i)
  3171. (message "Table was already stable"))
  3172. (throw 'exit t)))
  3173. (user-error "No convergence after %d iterations" i))))
  3174. ;;;###autoload
  3175. (defun org-table-recalculate-buffer-tables ()
  3176. "Recalculate all tables in the current buffer."
  3177. (interactive)
  3178. (org-with-wide-buffer
  3179. (org-table-map-tables
  3180. (lambda ()
  3181. ;; Reason for separate `org-table-align': When repeating
  3182. ;; (org-table-recalculate t) `org-table-may-need-update' gets in
  3183. ;; the way.
  3184. (org-table-recalculate t t)
  3185. (org-table-align))
  3186. t)))
  3187. ;;;###autoload
  3188. (defun org-table-iterate-buffer-tables ()
  3189. "Iterate all tables in the buffer, to converge inter-table dependencies."
  3190. (interactive)
  3191. (let* ((imax 10)
  3192. (i imax)
  3193. (checksum (md5 (buffer-string)))
  3194. c1)
  3195. (org-with-wide-buffer
  3196. (catch 'exit
  3197. (while (> i 0)
  3198. (setq i (1- i))
  3199. (org-table-map-tables (lambda () (org-table-recalculate t t)) t)
  3200. (if (equal checksum (setq c1 (md5 (buffer-string))))
  3201. (progn
  3202. (org-table-map-tables #'org-table-align t)
  3203. (message "Convergence after %d iterations" (- imax i))
  3204. (throw 'exit t))
  3205. (setq checksum c1)))
  3206. (org-table-map-tables #'org-table-align t)
  3207. (user-error "No convergence after %d iterations" imax)))))
  3208. (defun org-table-calc-current-TBLFM (&optional arg)
  3209. "Apply the #+TBLFM in the line at point to the table."
  3210. (interactive "P")
  3211. (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
  3212. (let ((formula (buffer-substring
  3213. (line-beginning-position)
  3214. (line-end-position))))
  3215. (save-excursion
  3216. ;; Insert a temporary formula at right after the table
  3217. (goto-char (org-table-TBLFM-begin))
  3218. (let ((s (point-marker)))
  3219. (insert formula "\n")
  3220. (let ((e (point-marker)))
  3221. ;; Recalculate the table.
  3222. (beginning-of-line 0) ; move to the inserted line
  3223. (skip-chars-backward " \r\n\t")
  3224. (unwind-protect
  3225. (org-call-with-arg #'org-table-recalculate (or arg t))
  3226. ;; Delete the formula inserted temporarily.
  3227. (delete-region s e)
  3228. (set-marker s nil)
  3229. (set-marker e nil)))))))
  3230. (defun org-table-TBLFM-begin ()
  3231. "Find the beginning of the TBLFM lines and return its position.
  3232. Return nil when the beginning of TBLFM line was not found."
  3233. (save-excursion
  3234. (when (progn (forward-line 1)
  3235. (re-search-backward org-table-TBLFM-begin-regexp nil t))
  3236. (line-beginning-position 2))))
  3237. (defun org-table-expand-lhs-ranges (equations)
  3238. "Expand list of formulas.
  3239. If some of the RHS in the formulas are ranges or a row reference,
  3240. expand them to individual field equations for each field. This
  3241. function assumes the table is already analyzed (i.e., using
  3242. `org-table-analyze')."
  3243. (let (res)
  3244. (dolist (e equations (nreverse res))
  3245. (let ((lhs (car e))
  3246. (rhs (cdr e)))
  3247. (cond
  3248. ((string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
  3249. ;; This just refers to one fixed field.
  3250. (push e res))
  3251. ((string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
  3252. ;; This just refers to one fixed named field.
  3253. (push e res))
  3254. ((string-match-p "\\`\\$[0-9]+\\'" lhs)
  3255. ;; Column formulas are treated specially and are not
  3256. ;; expanded.
  3257. (push e res))
  3258. ((string-match "\\`@[0-9]+\\'" lhs)
  3259. (dotimes (ic org-table-current-ncol)
  3260. (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
  3261. rhs)
  3262. res)))
  3263. (t
  3264. (let* ((range (org-table-get-range
  3265. lhs org-table-current-begin-pos 1 nil 'corners))
  3266. (r1 (org-table-line-to-dline (nth 0 range)))
  3267. (c1 (nth 1 range))
  3268. (r2 (org-table-line-to-dline (nth 2 range) 'above))
  3269. (c2 (nth 3 range)))
  3270. (cl-loop for ir from r1 to r2 do
  3271. (cl-loop for ic from c1 to c2 do
  3272. (push (cons (propertize
  3273. (format "@%d$%d" ir ic) :orig-eqn e)
  3274. rhs)
  3275. res))))))))))
  3276. (defun org-table-formula-handle-first/last-rc (s)
  3277. "Replace @<, @>, $<, $> with first/last row/column of the table.
  3278. So @< and $< will always be replaced with @1 and $1, respectively.
  3279. The advantage of these special markers are that structure editing of
  3280. the table will not change them, while @1 and $1 will be modified
  3281. when a line/row is swapped out of that privileged position. So for
  3282. formulas that use a range of rows or columns, it may often be better
  3283. to anchor the formula with \"I\" row markers, or to offset from the
  3284. borders of the table using the @< @> $< $> makers."
  3285. (let (n nmax len char (start 0))
  3286. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
  3287. s start)
  3288. (if (match-end 3)
  3289. (setq start (match-end 3))
  3290. (setq nmax (if (equal (match-string 1 s) "@")
  3291. (1- (length org-table-dlines))
  3292. org-table-current-ncol)
  3293. len (- (match-end 2) (match-beginning 2))
  3294. char (string-to-char (match-string 2 s))
  3295. n (if (= char ?<)
  3296. len
  3297. (- nmax len -1)))
  3298. (if (or (< n 1) (> n nmax))
  3299. (user-error "Reference \"%s\" in expression \"%s\" points outside table"
  3300. (match-string 0 s) s))
  3301. (setq start (match-beginning 0))
  3302. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
  3303. s)
  3304. (defun org-table-formula-substitute-names (f)
  3305. "Replace $const with values in string F."
  3306. (let ((start 0)
  3307. (pp (/= (string-to-char f) ?'))
  3308. (duration (string-match-p ";.*[Tt].*\\'" f))
  3309. (new (replace-regexp-in-string ; Check for column names.
  3310. org-table-column-name-regexp
  3311. (lambda (m)
  3312. (concat "$" (cdr (assoc (match-string 1 m)
  3313. org-table-column-names))))
  3314. f t t)))
  3315. ;; Parameters and constants.
  3316. (while (setq start
  3317. (string-match
  3318. "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
  3319. new start))
  3320. (if (match-end 2) (setq start (match-end 2))
  3321. (cl-incf start)
  3322. ;; When a duration is expected, convert value on the fly.
  3323. (let ((value
  3324. (save-match-data
  3325. (let ((v (org-table-get-constant (match-string 1 new))))
  3326. (if (and (org-string-nw-p v) duration)
  3327. (org-table-time-string-to-seconds v)
  3328. v)))))
  3329. (when value
  3330. (setq new (replace-match
  3331. (concat (and pp "(") value (and pp ")")) t t new))))))
  3332. (if org-table-formula-debug (propertize new :orig-formula f) new)))
  3333. (defun org-table-get-constant (const)
  3334. "Find the value for a parameter or constant in a formula.
  3335. Parameters get priority."
  3336. (or (cdr (assoc const org-table-local-parameters))
  3337. (cdr (assoc const org-table-formula-constants-local))
  3338. (cdr (assoc const org-table-formula-constants))
  3339. (and (fboundp 'constants-get) (constants-get const))
  3340. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  3341. (org-entry-get nil (substring const 5) 'inherit))
  3342. "#UNDEFINED_NAME"))
  3343. (defvar org-table-fedit-map
  3344. (let ((map (make-sparse-keymap)))
  3345. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  3346. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  3347. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  3348. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  3349. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  3350. (org-defkey map "\C-c?" 'org-table-show-reference)
  3351. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  3352. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  3353. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  3354. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  3355. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  3356. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  3357. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  3358. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  3359. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  3360. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  3361. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  3362. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  3363. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  3364. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  3365. map))
  3366. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
  3367. '("Edit-Formulas"
  3368. ["Finish and Install" org-table-fedit-finish t]
  3369. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  3370. ["Abort" org-table-fedit-abort t]
  3371. "--"
  3372. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  3373. ["Complete Lisp Symbol" lisp-complete-symbol t]
  3374. "--"
  3375. "Shift Reference at Point"
  3376. ["Up" org-table-fedit-ref-up t]
  3377. ["Down" org-table-fedit-ref-down t]
  3378. ["Left" org-table-fedit-ref-left t]
  3379. ["Right" org-table-fedit-ref-right t]
  3380. "-"
  3381. "Change Test Row for Column Formulas"
  3382. ["Up" org-table-fedit-line-up t]
  3383. ["Down" org-table-fedit-line-down t]
  3384. "--"
  3385. ["Scroll Table Window" org-table-fedit-scroll t]
  3386. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  3387. ["Show Table Grid" org-table-fedit-toggle-coordinates
  3388. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  3389. org-table-overlay-coordinates)]
  3390. "--"
  3391. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  3392. :style toggle :selected org-table-buffer-is-an]))
  3393. (defvar org-pos)
  3394. (defvar org-table--fedit-source nil
  3395. "Position of the TBLFM line being edited.")
  3396. ;;;###autoload
  3397. (defun org-table-edit-formulas ()
  3398. "Edit the formulas of the current table in a separate buffer."
  3399. (interactive)
  3400. (let ((at-tblfm (org-at-TBLFM-p)))
  3401. (unless (or at-tblfm (org-at-table-p))
  3402. (user-error "Not at a table"))
  3403. (save-excursion
  3404. ;; Move point within the table before analyzing it.
  3405. (when at-tblfm (re-search-backward "^[ \t]*|"))
  3406. (org-table-analyze))
  3407. (let ((key (org-table-current-field-formula 'key 'noerror))
  3408. (eql (sort (org-table-get-stored-formulas t (and at-tblfm (point)))
  3409. #'org-table-formula-less-p))
  3410. (pos (point-marker))
  3411. (source (copy-marker (line-beginning-position)))
  3412. (startline 1)
  3413. (wc (current-window-configuration))
  3414. (sel-win (selected-window))
  3415. (titles '((column . "# Column Formulas\n")
  3416. (field . "# Field and Range Formulas\n")
  3417. (named . "# Named Field Formulas\n"))))
  3418. (org-switch-to-buffer-other-window "*Edit Formulas*")
  3419. (erase-buffer)
  3420. ;; Keep global-font-lock-mode from turning on font-lock-mode
  3421. (let ((font-lock-global-modes '(not fundamental-mode)))
  3422. (fundamental-mode))
  3423. (setq-local font-lock-global-modes (list 'not major-mode))
  3424. (setq-local org-pos pos)
  3425. (setq-local org-table--fedit-source source)
  3426. (setq-local org-window-configuration wc)
  3427. (setq-local org-selected-window sel-win)
  3428. (use-local-map org-table-fedit-map)
  3429. (add-hook 'post-command-hook #'org-table-fedit-post-command t t)
  3430. (easy-menu-add org-table-fedit-menu)
  3431. (setq startline (org-current-line))
  3432. (dolist (entry eql)
  3433. (let* ((type (cond
  3434. ((string-match "\\`$\\([0-9]+\\|[<>]+\\)\\'" (car entry))
  3435. 'column)
  3436. ((equal (string-to-char (car entry)) ?@) 'field)
  3437. (t 'named)))
  3438. (title (assq type titles)))
  3439. (when title
  3440. (unless (bobp) (insert "\n"))
  3441. (insert
  3442. (org-add-props (cdr title) nil 'face font-lock-comment-face))
  3443. (setq titles (remove title titles)))
  3444. (when (equal key (car entry)) (setq startline (org-current-line)))
  3445. (let ((s (concat
  3446. (if (memq (string-to-char (car entry)) '(?@ ?$)) "" "$")
  3447. (car entry) " = " (cdr entry) "\n")))
  3448. (remove-text-properties 0 (length s) '(face nil) s)
  3449. (insert s))))
  3450. (when (eq org-table-use-standard-references t)
  3451. (org-table-fedit-toggle-ref-type))
  3452. (org-goto-line startline)
  3453. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  3454. Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
  3455. See menu for more commands.")))))
  3456. (defun org-table-fedit-post-command ()
  3457. (when (not (memq this-command '(lisp-complete-symbol)))
  3458. (let ((win (selected-window)))
  3459. (save-excursion
  3460. (ignore-errors (org-table-show-reference))
  3461. (select-window win)))))
  3462. (defun org-table-formula-to-user (s)
  3463. "Convert a formula from internal to user representation."
  3464. (if (eq org-table-use-standard-references t)
  3465. (org-table-convert-refs-to-an s)
  3466. s))
  3467. (defun org-table-formula-from-user (s)
  3468. "Convert a formula from user to internal representation."
  3469. (if org-table-use-standard-references
  3470. (org-table-convert-refs-to-rc s)
  3471. s))
  3472. (defun org-table-convert-refs-to-rc (s)
  3473. "Convert spreadsheet references from A7 to @7$28.
  3474. Works for single references, but also for entire formulas and even the
  3475. full TBLFM line."
  3476. (let ((start 0))
  3477. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
  3478. (cond
  3479. ((match-end 3)
  3480. ;; format match, just advance
  3481. (setq start (match-end 0)))
  3482. ((and (> (match-beginning 0) 0)
  3483. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  3484. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  3485. ;; 3.e5 or something like this.
  3486. (setq start (match-end 0)))
  3487. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  3488. ;; (member (match-string 1 s)
  3489. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  3490. )
  3491. ;; function name, just advance
  3492. (setq start (match-end 0)))
  3493. (t
  3494. (setq start (match-beginning 0)
  3495. s (replace-match
  3496. (if (equal (match-string 2 s) "&")
  3497. (format "$%d" (org-letters-to-number (match-string 1 s)))
  3498. (format "@%d$%d"
  3499. (string-to-number (match-string 2 s))
  3500. (org-letters-to-number (match-string 1 s))))
  3501. t t s)))))
  3502. s))
  3503. (defun org-table-convert-refs-to-an (s)
  3504. "Convert spreadsheet references from to @7$28 to AB7.
  3505. Works for single references, but also for entire formulas and even the
  3506. full TBLFM line."
  3507. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  3508. (setq s (replace-match
  3509. (format "%s%d"
  3510. (org-number-to-letters
  3511. (string-to-number (match-string 2 s)))
  3512. (string-to-number (match-string 1 s)))
  3513. t t s)))
  3514. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  3515. (setq s (replace-match (concat "\\1"
  3516. (org-number-to-letters
  3517. (string-to-number (match-string 2 s))) "&")
  3518. t nil s)))
  3519. s)
  3520. (defun org-letters-to-number (s)
  3521. "Convert a base 26 number represented by letters into an integer.
  3522. For example: AB -> 28."
  3523. (let ((n 0))
  3524. (setq s (upcase s))
  3525. (while (> (length s) 0)
  3526. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3527. s (substring s 1)))
  3528. n))
  3529. (defun org-number-to-letters (n)
  3530. "Convert an integer into a base 26 number represented by letters.
  3531. For example: 28 -> AB."
  3532. (let ((s ""))
  3533. (while (> n 0)
  3534. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3535. n (/ (1- n) 26)))
  3536. s))
  3537. (defun org-table-time-string-to-seconds (s)
  3538. "Convert a time string into numerical duration in seconds.
  3539. S can be a string matching either -?HH:MM:SS or -?HH:MM.
  3540. If S is a string representing a number, keep this number."
  3541. (if (equal s "")
  3542. s
  3543. (let (hour minus min sec res)
  3544. (cond
  3545. ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3546. (setq minus (< 0 (length (match-string 1 s)))
  3547. hour (string-to-number (match-string 2 s))
  3548. min (string-to-number (match-string 3 s))
  3549. sec (string-to-number (match-string 4 s)))
  3550. (if minus
  3551. (setq res (- (+ (* hour 3600) (* min 60) sec)))
  3552. (setq res (+ (* hour 3600) (* min 60) sec))))
  3553. ((and (not (string-match org-ts-regexp-both s))
  3554. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3555. (setq minus (< 0 (length (match-string 1 s)))
  3556. hour (string-to-number (match-string 2 s))
  3557. min (string-to-number (match-string 3 s)))
  3558. (if minus
  3559. (setq res (- (+ (* hour 3600) (* min 60))))
  3560. (setq res (+ (* hour 3600) (* min 60)))))
  3561. (t (setq res (string-to-number s))))
  3562. (number-to-string res))))
  3563. (defun org-table-time-seconds-to-string (secs &optional output-format)
  3564. "Convert a number of seconds to a time string.
  3565. If OUTPUT-FORMAT is non-nil, return a number of days, hours,
  3566. minutes or seconds."
  3567. (let* ((secs0 (abs secs))
  3568. (res
  3569. (cond ((eq output-format 'days)
  3570. (format "%.3f" (/ (float secs0) 86400)))
  3571. ((eq output-format 'hours)
  3572. (format "%.2f" (/ (float secs0) 3600)))
  3573. ((eq output-format 'minutes)
  3574. (format "%.1f" (/ (float secs0) 60)))
  3575. ((eq output-format 'seconds)
  3576. (format "%d" secs0))
  3577. ((eq output-format 'hh:mm)
  3578. ;; Ignore seconds
  3579. (substring (format-seconds
  3580. (if org-table-duration-hour-zero-padding
  3581. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3582. secs0)
  3583. 0 -3))
  3584. (t (format-seconds
  3585. (if org-table-duration-hour-zero-padding
  3586. "%.2h:%.2m:%.2s" "%h:%.2m:%.2s")
  3587. secs0)))))
  3588. (if (< secs 0) (concat "-" res) res)))
  3589. ;;; Columns shrinking
  3590. (defun org-table--shrunk-field ()
  3591. "Non-nil if current field is narrowed.
  3592. When non-nil, return the overlay narrowing the field."
  3593. (cl-some (lambda (o)
  3594. (and (eq 'table-column-hide (overlay-get o 'org-overlay-type))
  3595. o))
  3596. (overlays-at (save-excursion
  3597. (skip-chars-forward (if (org-at-table-hline-p) "^+|"
  3598. "^|")
  3599. (line-end-position))
  3600. (1- (point))))))
  3601. (defun org-table--list-shrunk-columns ()
  3602. "List currently shrunk columns in table at point."
  3603. (save-excursion
  3604. ;; We really check shrunk columns in current row only. It could
  3605. ;; be wrong if all rows do not contain the same number of columns
  3606. ;; (i.e. the table is not properly aligned). As a consequence,
  3607. ;; some columns may not be shrunk again upon aligning the table.
  3608. ;;
  3609. ;; For example, in the following table, cursor is on first row and
  3610. ;; "<>" indicates a shrunk column.
  3611. ;;
  3612. ;; | |
  3613. ;; | | <> |
  3614. ;;
  3615. ;; Aligning table from the first row will not shrink again the
  3616. ;; second row, which was not visible initially.
  3617. ;;
  3618. ;; However, fixing it requires to check every row, which may be
  3619. ;; slow on large tables. Moreover, the hindrance of this
  3620. ;; pathological case is very limited.
  3621. (beginning-of-line)
  3622. (search-forward "|")
  3623. (let ((separator (if (org-at-table-hline-p) "+" "|"))
  3624. (column 1)
  3625. (shrunk (and (org-table--shrunk-field) (list 1)))
  3626. (end (line-end-position)))
  3627. (while (search-forward separator end t)
  3628. (cl-incf column)
  3629. (when (org-table--shrunk-field) (push column shrunk)))
  3630. (nreverse shrunk))))
  3631. (defun org-table--make-shrinking-overlay (start end display field &optional pre)
  3632. "Create an overlay to shrink text between START and END.
  3633. Use string DISPLAY instead of the real text between the two
  3634. buffer positions. FIELD is the real contents of the field, as
  3635. a string, or nil. It is meant to be displayed upon moving the
  3636. mouse onto the overlay.
  3637. Return the overlay."
  3638. (let ((show-before-edit
  3639. (lambda (o &rest _)
  3640. ;; Removing one overlay removes all other overlays in the
  3641. ;; same column.
  3642. (mapc #'delete-overlay
  3643. (cdr (overlay-get o 'org-table-column-overlays)))))
  3644. (o (make-overlay start end)))
  3645. (overlay-put o 'insert-behind-hooks (and (not pre) (list show-before-edit)))
  3646. (overlay-put o 'insert-in-front-hooks (list show-before-edit))
  3647. (overlay-put o 'modification-hooks (list show-before-edit))
  3648. (overlay-put o 'org-overlay-type 'table-column-hide)
  3649. (when (stringp field) (overlay-put o 'help-echo field))
  3650. ;; Make sure overlays stays on top of table coordinates overlays.
  3651. ;; See `org-table-overlay-coordinates'.
  3652. (overlay-put o 'priority 1)
  3653. (org-overlay-display o display 'org-table t)
  3654. o))
  3655. (defun org-table--shrink-field (width start end contents)
  3656. "Shrink a table field to a specified width.
  3657. WIDTH is an integer representing the number of characters to
  3658. display, in addition to `org-table-shrunk-column-indicator'. START
  3659. and END are, respectively, the beginning and ending positions of
  3660. the field. CONTENTS is its trimmed contents, as a string, or
  3661. `hline' for table rules.
  3662. Real field is hidden under one or two overlays. They have the
  3663. following properties:
  3664. `org-overlay-type'
  3665. Set to `table-column-hide'. Used to identify overlays
  3666. responsible for shrinking columns in a table.
  3667. `org-table-column-overlays'
  3668. It is a list with the pattern (siblings . COLUMN-OVERLAYS)
  3669. where COLUMN-OVERLAYS is the list of all overlays hiding the
  3670. same column.
  3671. Whenever the text behind or next to the overlay is modified, all
  3672. the overlays in the column are deleted, effectively displaying
  3673. the column again.
  3674. Return a list of overlays hiding the field, or nil if field is
  3675. already hidden."
  3676. (cond
  3677. ((org-table--shrunk-field) nil) ;already shrunk: bail out
  3678. ((or (= 0 width) ;shrink to one character
  3679. (>= 1 (org-string-width (buffer-substring start end))))
  3680. (list (org-table--make-shrinking-overlay
  3681. start end org-table-shrunk-column-indicator
  3682. (if (eq 'hline contents) "" contents))))
  3683. ((eq contents 'hline) ;no contents to hide
  3684. (list (org-table--make-shrinking-overlay
  3685. start end
  3686. (concat (make-string (max 0 (1+ width)) ?-)
  3687. org-table-shrunk-column-indicator)
  3688. "")))
  3689. (t
  3690. ;; If the field is not empty, consider using two overlays: one for
  3691. ;; the blanks at the beginning of the field, and another one at
  3692. ;; the end of the field. The former ensures a shrunk field is
  3693. ;; always displayed with a single white space character in front
  3694. ;; of it -- e.g., so that even right-aligned fields appear to the
  3695. ;; left -- and the latter cuts the field at WIDTH visible
  3696. ;; characters.
  3697. (let* ((pre-overlay
  3698. (and (not (equal contents ""))
  3699. (org-with-point-at start (looking-at "\\( [ \t]+\\)\\S-"))
  3700. (org-table--make-shrinking-overlay
  3701. start (match-end 1) org-table-separator-space nil 'pre)))
  3702. (post-overlay
  3703. (let* ((start (if pre-overlay (overlay-end pre-overlay)
  3704. (1+ start)))
  3705. (w (org-string-width (buffer-substring start (1- end)))))
  3706. (if (>= width w)
  3707. ;; Field is too short. Extend its size by adding
  3708. ;; white space characters to the right overlay.
  3709. (org-table--make-shrinking-overlay
  3710. (1- end) end (concat (make-string (- width w) ?\s)
  3711. org-table-shrunk-column-indicator)
  3712. contents)
  3713. ;; Find cut location so that WIDTH characters are visible.
  3714. (org-table--make-shrinking-overlay
  3715. (let* ((begin start)
  3716. (lower begin)
  3717. (upper (1- end)))
  3718. (catch :exit
  3719. (while (> (- upper lower) 1)
  3720. (let ((mean (+ (ash lower -1)
  3721. (ash upper -1)
  3722. (logand lower upper 1))))
  3723. (pcase (org-string-width (buffer-substring begin mean))
  3724. ((pred (= width)) (throw :exit mean))
  3725. ((pred (< width)) (setq upper mean))
  3726. (_ (setq lower mean)))))
  3727. upper))
  3728. end org-table-shrunk-column-indicator contents)))))
  3729. (delq nil (list pre-overlay post-overlay))))))
  3730. (defun org-table--read-column-selection (select max)
  3731. "Read column selection select as a list of numbers.
  3732. SELECT is a string containing column ranges, separated by white
  3733. space characters, see `org-table-hide-column' for details. MAX
  3734. is the maximum column number.
  3735. Return value is a sorted list of numbers. Ignore any number
  3736. outside of the [1;MAX] range."
  3737. (catch :all
  3738. (sort
  3739. (delete-dups
  3740. (cl-mapcan
  3741. (lambda (s)
  3742. (cond
  3743. ((member s '("-" "1-")) (throw :all (number-sequence 1 max)))
  3744. ((string-match-p "\\`[0-9]+\\'" s)
  3745. (let ((n (string-to-number s)))
  3746. (and (> n 0) (<= n max) (list n))))
  3747. ((string-match "\\`\\([0-9]+\\)?-\\([0-9]+\\)?\\'" s)
  3748. (let ((n (match-string 1 s))
  3749. (m (match-string 2 s)))
  3750. (number-sequence (if n (max 1 (string-to-number n))
  3751. 1)
  3752. (if m (min max (string-to-number m))
  3753. max))))
  3754. (t nil))) ;invalid specification
  3755. (split-string select)))
  3756. #'<)))
  3757. (defun org-table--shrink-columns (columns beg end)
  3758. "Shrink COLUMNS in a table.
  3759. COLUMNS is a sorted list of column numbers. BEG and END are,
  3760. respectively, the beginning position and the end position of the
  3761. table."
  3762. (org-with-wide-buffer
  3763. (org-font-lock-ensure beg end)
  3764. (dolist (c columns)
  3765. (goto-char beg)
  3766. (let ((width nil)
  3767. (fields nil))
  3768. (while (< (point) end)
  3769. (catch :continue
  3770. (let* ((hline? (org-at-table-hline-p))
  3771. (separator (if hline? "+" "|")))
  3772. ;; Move to COLUMN.
  3773. (search-forward "|")
  3774. (or (= c 1) ;already there
  3775. (search-forward separator (line-end-position) t (1- c))
  3776. (throw :continue nil)) ;skip invalid columns
  3777. ;; Extract boundaries and contents from current field.
  3778. ;; Also set the column's width if we encounter a width
  3779. ;; cookie for the first time.
  3780. (let* ((start (point))
  3781. (end (progn
  3782. (skip-chars-forward (concat "^|" separator)
  3783. (line-end-position))
  3784. (point)))
  3785. (contents (if hline? 'hline
  3786. (org-trim (buffer-substring start end)))))
  3787. (push (list start end contents) fields)
  3788. (when (and (null width)
  3789. (not hline?)
  3790. (string-match "\\`<[lrc]?\\([0-9]+\\)>\\'" contents))
  3791. (setq width (string-to-number (match-string 1 contents)))))))
  3792. (forward-line))
  3793. ;; Link overlays for current field to the other overlays in the
  3794. ;; same column.
  3795. (let ((chain (list 'siblings)))
  3796. (dolist (field fields)
  3797. (dolist (new (apply #'org-table--shrink-field (or width 0) field))
  3798. (push new (cdr chain))
  3799. (overlay-put new 'org-table-column-overlays chain))))))))
  3800. ;;;###autoload
  3801. (defun org-table-toggle-column-width (&optional arg)
  3802. "Shrink or expand current column in an Org table.
  3803. If a width cookie specifies a width W for the column, the first
  3804. W visible characters are displayed. Otherwise, the column is
  3805. shrunk to a single character.
  3806. When point is before the first column or after the last one, ask
  3807. for the columns to shrink or expand, as a list of ranges.
  3808. A column range can be one of the following patterns:
  3809. N column N only
  3810. N-M every column between N and M (both inclusive)
  3811. N- every column between N (inclusive) and the last column
  3812. -M every column between the first one and M (inclusive)
  3813. - every column
  3814. When optional argument ARG is a string, use it as white space
  3815. separated list of column ranges.
  3816. When called with `\\[universal-argument]' prefix, call \
  3817. `org-table-shrink', i.e.,
  3818. shrink columns with a width cookie and expand the others.
  3819. When called with `\\[universal-argument] \\[universal-argument]' \
  3820. prefix, expand all columns."
  3821. (interactive "P")
  3822. (unless (org-at-table-p) (user-error "Not in a table"))
  3823. (let* ((begin (org-table-begin))
  3824. (end (org-table-end))
  3825. ;; Compute an upper bound for the number of columns.
  3826. ;; Nonexistent columns are ignored anyway.
  3827. (max-columns (/ (- (line-end-position) (line-beginning-position)) 2))
  3828. (shrunk (org-table--list-shrunk-columns))
  3829. (columns
  3830. (pcase arg
  3831. (`nil
  3832. (if (save-excursion
  3833. (skip-chars-backward "^|" (line-beginning-position))
  3834. (or (bolp) (looking-at-p "[ \t]*$")))
  3835. ;; Point is either before first column or past last
  3836. ;; one. Ask for columns to operate on.
  3837. (org-table--read-column-selection
  3838. (read-string "Column ranges (e.g. 2-4 6-): ")
  3839. max-columns)
  3840. (list (org-table-current-column))))
  3841. ((pred stringp) (org-table--read-column-selection arg max-columns))
  3842. ((or `(4) `(16)) nil)
  3843. (_ (user-error "Invalid argument: %S" arg)))))
  3844. (pcase arg
  3845. (`(4) (org-table-shrink begin end))
  3846. (`(16) (org-table-expand begin end))
  3847. (_
  3848. (org-table-expand begin end)
  3849. (org-table--shrink-columns
  3850. (cl-set-exclusive-or columns shrunk) begin end)))))
  3851. ;;;###autoload
  3852. (defun org-table-shrink (&optional begin end)
  3853. "Shrink all columns with a width cookie in the table at point.
  3854. Columns without a width cookie are expanded.
  3855. Optional arguments BEGIN and END, when non-nil, specify the
  3856. beginning and end position of the current table."
  3857. (interactive)
  3858. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3859. (org-with-wide-buffer
  3860. (let ((begin (or begin (org-table-begin)))
  3861. (end (or end (org-table-end)))
  3862. (regexp "|[ \t]*<[lrc]?[0-9]+>[ \t]*\\(|\\|$\\)")
  3863. (columns))
  3864. (goto-char begin)
  3865. (while (re-search-forward regexp end t)
  3866. (goto-char (match-beginning 1))
  3867. (cl-pushnew (org-table-current-column) columns))
  3868. (org-table-expand begin end)
  3869. ;; Make sure invisible characters in the table are at the right
  3870. ;; place since column widths take them into account.
  3871. (org-font-lock-ensure begin end)
  3872. (org-table--shrink-columns (sort columns #'<) begin end))))
  3873. ;;;###autoload
  3874. (defun org-table-expand (&optional begin end)
  3875. "Expand all columns in the table at point.
  3876. Optional arguments BEGIN and END, when non-nil, specify the
  3877. beginning and end position of the current table."
  3878. (interactive)
  3879. (unless (or begin (org-at-table-p)) (user-error "Not at a table"))
  3880. (org-with-wide-buffer
  3881. (let ((begin (or begin (org-table-begin)))
  3882. (end (or end (org-table-end))))
  3883. (remove-overlays begin end 'org-overlay-type 'table-column-hide))))
  3884. ;;; Formula editing
  3885. (defun org-table-fedit-convert-buffer (function)
  3886. "Convert all references in this buffer, using FUNCTION."
  3887. (let ((origin (copy-marker (line-beginning-position))))
  3888. (goto-char (point-min))
  3889. (while (not (eobp))
  3890. (insert (funcall function (buffer-substring (point) (line-end-position))))
  3891. (delete-region (point) (line-end-position))
  3892. (forward-line))
  3893. (goto-char origin)
  3894. (set-marker origin nil)))
  3895. (defun org-table-fedit-toggle-ref-type ()
  3896. "Convert all references in the buffer from B3 to @3$2 and back."
  3897. (interactive)
  3898. (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
  3899. (org-table-fedit-convert-buffer
  3900. (if org-table-buffer-is-an
  3901. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3902. (message "Reference type switched to %s"
  3903. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3904. (defun org-table-fedit-ref-up ()
  3905. "Shift the reference at point one row/hline up."
  3906. (interactive)
  3907. (org-table-fedit-shift-reference 'up))
  3908. (defun org-table-fedit-ref-down ()
  3909. "Shift the reference at point one row/hline down."
  3910. (interactive)
  3911. (org-table-fedit-shift-reference 'down))
  3912. (defun org-table-fedit-ref-left ()
  3913. "Shift the reference at point one field to the left."
  3914. (interactive)
  3915. (org-table-fedit-shift-reference 'left))
  3916. (defun org-table-fedit-ref-right ()
  3917. "Shift the reference at point one field to the right."
  3918. (interactive)
  3919. (org-table-fedit-shift-reference 'right))
  3920. (defun org-table-fedit-shift-reference (dir)
  3921. (cond
  3922. ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
  3923. (if (memq dir '(left right))
  3924. (org-rematch-and-replace 1 (eq dir 'left))
  3925. (user-error "Cannot shift reference in this direction")))
  3926. ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3927. ;; A B3-like reference
  3928. (if (memq dir '(up down))
  3929. (org-rematch-and-replace 2 (eq dir 'up))
  3930. (org-rematch-and-replace 1 (eq dir 'left))))
  3931. ((org-in-regexp
  3932. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3933. ;; An internal reference
  3934. (if (memq dir '(up down))
  3935. (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3936. (org-rematch-and-replace 5 (eq dir 'left))))))
  3937. (defun org-rematch-and-replace (n &optional decr hline)
  3938. "Re-match the group N, and replace it with the shifted reference."
  3939. (or (match-end n) (user-error "Cannot shift reference in this direction"))
  3940. (goto-char (match-beginning n))
  3941. (and (looking-at (regexp-quote (match-string n)))
  3942. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  3943. t t)))
  3944. (defun org-table-shift-refpart (ref &optional decr hline)
  3945. "Shift a reference part REF.
  3946. If DECR is set, decrease the references row/column, else increase.
  3947. If HLINE is set, this may be a hline reference, it certainly is not
  3948. a translation reference."
  3949. (save-match-data
  3950. (let* ((sign (string-match "^[-+]" ref)) n)
  3951. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  3952. (cond
  3953. ((and hline (string-match "^I+" ref))
  3954. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  3955. (setq n (+ n (if decr -1 1)))
  3956. (if (= n 0) (setq n (+ n (if decr -1 1))))
  3957. (if sign
  3958. (setq sign (if (< n 0) "-" "+") n (abs n))
  3959. (setq n (max 1 n)))
  3960. (concat sign (make-string n ?I)))
  3961. ((string-match "^[0-9]+" ref)
  3962. (setq n (string-to-number (concat sign ref)))
  3963. (setq n (+ n (if decr -1 1)))
  3964. (if sign
  3965. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  3966. (number-to-string (max 1 n))))
  3967. ((string-match "^[a-zA-Z]+" ref)
  3968. (org-number-to-letters
  3969. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  3970. (t (user-error "Cannot shift reference"))))))
  3971. (defun org-table-fedit-toggle-coordinates ()
  3972. "Toggle the display of coordinates in the referenced table."
  3973. (interactive)
  3974. (let ((pos (marker-position org-pos)))
  3975. (with-current-buffer (marker-buffer org-pos)
  3976. (save-excursion
  3977. (goto-char pos)
  3978. (org-table-toggle-coordinate-overlays)))))
  3979. (defun org-table-fedit-finish (&optional arg)
  3980. "Parse the buffer for formula definitions and install them.
  3981. With prefix ARG, apply the new formulas to the table."
  3982. (interactive "P")
  3983. (org-table-remove-rectangle-highlight)
  3984. (when org-table-use-standard-references
  3985. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  3986. (setq org-table-buffer-is-an nil))
  3987. (let ((pos org-pos)
  3988. (sel-win org-selected-window)
  3989. (source org-table--fedit-source)
  3990. eql)
  3991. (goto-char (point-min))
  3992. (while (re-search-forward
  3993. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  3994. nil t)
  3995. (let ((var (match-string 1))
  3996. (form (org-trim (match-string 3))))
  3997. (unless (equal form "")
  3998. (while (string-match "[ \t]*\n[ \t]*" form)
  3999. (setq form (replace-match " " t t form)))
  4000. (when (assoc var eql)
  4001. (user-error "Double formulas for %s" var))
  4002. (push (cons var form) eql))))
  4003. (set-window-configuration org-window-configuration)
  4004. (select-window sel-win)
  4005. (goto-char source)
  4006. (org-table-store-formulas eql)
  4007. (set-marker pos nil)
  4008. (set-marker source nil)
  4009. (kill-buffer "*Edit Formulas*")
  4010. (if arg
  4011. (org-table-recalculate 'all)
  4012. (message "New formulas installed - press C-u C-c C-c to apply."))))
  4013. (defun org-table-fedit-abort ()
  4014. "Abort editing formulas, without installing the changes."
  4015. (interactive)
  4016. (org-table-remove-rectangle-highlight)
  4017. (let ((pos org-pos) (sel-win org-selected-window))
  4018. (set-window-configuration org-window-configuration)
  4019. (select-window sel-win)
  4020. (goto-char pos)
  4021. (move-marker pos nil)
  4022. (message "Formula editing aborted without installing changes")))
  4023. (defun org-table-fedit-lisp-indent ()
  4024. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  4025. (interactive)
  4026. (let ((pos (point)) beg end ind)
  4027. (beginning-of-line 1)
  4028. (cond
  4029. ((looking-at "[ \t]")
  4030. (goto-char pos)
  4031. (call-interactively 'lisp-indent-line))
  4032. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  4033. ((not (fboundp 'pp-buffer))
  4034. (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
  4035. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  4036. (goto-char (- (match-end 0) 2))
  4037. (setq beg (point))
  4038. (setq ind (make-string (current-column) ?\ ))
  4039. (condition-case nil (forward-sexp 1)
  4040. (error
  4041. (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  4042. (setq end (point))
  4043. (save-restriction
  4044. (narrow-to-region beg end)
  4045. (if (eq last-command this-command)
  4046. (progn
  4047. (goto-char (point-min))
  4048. (setq this-command nil)
  4049. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  4050. (replace-match " ")))
  4051. (pp-buffer)
  4052. (untabify (point-min) (point-max))
  4053. (goto-char (1+ (point-min)))
  4054. (while (re-search-forward "^." nil t)
  4055. (beginning-of-line 1)
  4056. (insert ind))
  4057. (goto-char (point-max))
  4058. (org-delete-backward-char 1)))
  4059. (goto-char beg))
  4060. (t nil))))
  4061. (defvar org-show-positions nil)
  4062. (defun org-table-show-reference (&optional local)
  4063. "Show the location/value of the $ expression at point.
  4064. When LOCAL is non-nil, show references for the table at point."
  4065. (interactive)
  4066. (org-table-remove-rectangle-highlight)
  4067. (when local (org-table-analyze))
  4068. (catch 'exit
  4069. (let ((pos (if local (point) org-pos))
  4070. (face2 'highlight)
  4071. (org-inhibit-highlight-removal t)
  4072. (win (selected-window))
  4073. (org-show-positions nil)
  4074. var name e what match dest)
  4075. (setq what (cond
  4076. ((org-in-regexp "^@[0-9]+[ \t=]")
  4077. (setq match (concat (substring (match-string 0) 0 -1)
  4078. "$1.."
  4079. (substring (match-string 0) 0 -1)
  4080. "$100"))
  4081. 'range)
  4082. ((or (org-in-regexp org-table-range-regexp2)
  4083. (org-in-regexp org-table-translate-regexp)
  4084. (org-in-regexp org-table-range-regexp))
  4085. (setq match
  4086. (save-match-data
  4087. (org-table-convert-refs-to-rc (match-string 0))))
  4088. 'range)
  4089. ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  4090. ((org-in-regexp "\\$[0-9]+") 'column)
  4091. ((not local) nil)
  4092. (t (user-error "No reference at point")))
  4093. match (and what (or match (match-string 0))))
  4094. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  4095. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  4096. 'secondary-selection))
  4097. (add-hook 'before-change-functions
  4098. #'org-table-remove-rectangle-highlight)
  4099. (when (eq what 'name) (setq var (substring match 1)))
  4100. (when (eq what 'range)
  4101. (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
  4102. (setq match (org-table-formula-substitute-names match)))
  4103. (unless local
  4104. (save-excursion
  4105. (end-of-line)
  4106. (re-search-backward "^\\S-" nil t)
  4107. (beginning-of-line)
  4108. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
  4109. \\([0-9]+\\|&\\)\\) *=")
  4110. (setq dest
  4111. (save-match-data
  4112. (org-table-convert-refs-to-rc (match-string 1))))
  4113. (org-table-add-rectangle-overlay
  4114. (match-beginning 1) (match-end 1) face2))))
  4115. (if (and (markerp pos) (marker-buffer pos))
  4116. (if (get-buffer-window (marker-buffer pos))
  4117. (select-window (get-buffer-window (marker-buffer pos)))
  4118. (org-switch-to-buffer-other-window (get-buffer-window
  4119. (marker-buffer pos)))))
  4120. (goto-char pos)
  4121. (org-table-force-dataline)
  4122. (let ((table-start
  4123. (if local org-table-current-begin-pos (org-table-begin))))
  4124. (when dest
  4125. (setq name (substring dest 1))
  4126. (cond
  4127. ((string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  4128. (org-table-goto-field dest))
  4129. ((string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
  4130. dest)
  4131. (org-table-goto-field dest))
  4132. (t (org-table-goto-column (string-to-number name))))
  4133. (move-marker pos (point))
  4134. (org-table-highlight-rectangle nil nil face2))
  4135. (cond
  4136. ((equal dest match))
  4137. ((not match))
  4138. ((eq what 'range)
  4139. (ignore-errors (org-table-get-range match table-start nil 'highlight)))
  4140. ((setq e (assoc var org-table-named-field-locations))
  4141. (org-table-goto-field var)
  4142. (org-table-highlight-rectangle)
  4143. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  4144. ((setq e (assoc var org-table-column-names))
  4145. (org-table-goto-column (string-to-number (cdr e)))
  4146. (org-table-highlight-rectangle)
  4147. (goto-char table-start)
  4148. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  4149. (org-table-end) t)
  4150. (progn
  4151. (goto-char (match-beginning 1))
  4152. (org-table-highlight-rectangle)
  4153. (message "Named column (column %s)" (cdr e)))
  4154. (user-error "Column name not found")))
  4155. ((eq what 'column)
  4156. ;; Column number.
  4157. (org-table-goto-column (string-to-number (substring match 1)))
  4158. (org-table-highlight-rectangle)
  4159. (message "Column %s" (substring match 1)))
  4160. ((setq e (assoc var org-table-local-parameters))
  4161. (goto-char table-start)
  4162. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  4163. (progn
  4164. (goto-char (match-beginning 1))
  4165. (org-table-highlight-rectangle)
  4166. (message "Local parameter."))
  4167. (user-error "Parameter not found")))
  4168. ((not var) (user-error "No reference at point"))
  4169. ((setq e (assoc var org-table-formula-constants-local))
  4170. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  4171. var (cdr e)))
  4172. ((setq e (assoc var org-table-formula-constants))
  4173. (message "Constant: $%s=%s in `org-table-formula-constants'."
  4174. var (cdr e)))
  4175. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  4176. (message "Constant: $%s=%s, from `constants.el'%s."
  4177. var e (format " (%s units)" constants-unit-system)))
  4178. (t (user-error "Undefined name $%s" var)))
  4179. (goto-char pos)
  4180. (when (and org-show-positions
  4181. (not (memq this-command '(org-table-fedit-scroll
  4182. org-table-fedit-scroll-down))))
  4183. (push pos org-show-positions)
  4184. (push table-start org-show-positions)
  4185. (let ((min (apply 'min org-show-positions))
  4186. (max (apply 'max org-show-positions)))
  4187. (set-window-start (selected-window) min)
  4188. (goto-char max)
  4189. (or (pos-visible-in-window-p max)
  4190. (set-window-start (selected-window) max)))))
  4191. (select-window win))))
  4192. (defun org-table-force-dataline ()
  4193. "Move point to the closest data line in a table.
  4194. Raise an error if the table contains no data line. Preserve
  4195. column when moving point."
  4196. (unless (org-match-line org-table-dataline-regexp)
  4197. (let* ((re org-table-dataline-regexp)
  4198. (column (current-column))
  4199. (p1 (save-excursion (re-search-forward re (org-table-end) t)))
  4200. (p2 (save-excursion (re-search-backward re (org-table-begin) t))))
  4201. (cond ((and p1 p2)
  4202. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  4203. p1
  4204. p2)))
  4205. ((or p1 p2) (goto-char (or p1 p2)))
  4206. (t (user-error "No table data line around here")))
  4207. (org-move-to-column column))))
  4208. (defun org-table-fedit-line-up ()
  4209. "Move cursor one line up in the window showing the table."
  4210. (interactive)
  4211. (org-table-fedit-move 'previous-line))
  4212. (defun org-table-fedit-line-down ()
  4213. "Move cursor one line down in the window showing the table."
  4214. (interactive)
  4215. (org-table-fedit-move 'next-line))
  4216. (defun org-table-fedit-move (command)
  4217. "Move the cursor in the window showing the table.
  4218. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  4219. (let ((org-table-allow-automatic-line-recalculation nil)
  4220. (pos org-pos) (win (selected-window)) p)
  4221. (select-window (get-buffer-window (marker-buffer org-pos)))
  4222. (setq p (point))
  4223. (call-interactively command)
  4224. (while (and (org-at-table-p)
  4225. (org-at-table-hline-p))
  4226. (call-interactively command))
  4227. (or (org-at-table-p) (goto-char p))
  4228. (move-marker pos (point))
  4229. (select-window win)))
  4230. (defun org-table-fedit-scroll (N)
  4231. (interactive "p")
  4232. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  4233. (scroll-other-window N)))
  4234. (defun org-table-fedit-scroll-down (N)
  4235. (interactive "p")
  4236. (org-table-fedit-scroll (- N)))
  4237. (defvar org-table-rectangle-overlays nil)
  4238. (defun org-table-add-rectangle-overlay (beg end &optional face)
  4239. "Add a new overlay."
  4240. (let ((ov (make-overlay beg end)))
  4241. (overlay-put ov 'face (or face 'secondary-selection))
  4242. (push ov org-table-rectangle-overlays)))
  4243. (defun org-table-highlight-rectangle (&optional beg end face)
  4244. "Highlight rectangular region in a table.
  4245. When buffer positions BEG and END are provided, use them to
  4246. delimit the region to highlight. Otherwise, refer to point. Use
  4247. FACE, when non-nil, for the highlight."
  4248. (let* ((beg (or beg (point)))
  4249. (end (or end (point)))
  4250. (b (min beg end))
  4251. (e (max beg end))
  4252. (start-coordinates
  4253. (save-excursion
  4254. (goto-char b)
  4255. (cons (line-beginning-position) (org-table-current-column))))
  4256. (end-coordinates
  4257. (save-excursion
  4258. (goto-char e)
  4259. (cons (line-beginning-position) (org-table-current-column)))))
  4260. (when (boundp 'org-show-positions)
  4261. (setq org-show-positions (cons b (cons e org-show-positions))))
  4262. (goto-char (car start-coordinates))
  4263. (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
  4264. (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
  4265. (last-row (car end-coordinates)))
  4266. (while (<= (point) last-row)
  4267. (when (looking-at org-table-dataline-regexp)
  4268. (org-table-goto-column column-start)
  4269. (skip-chars-backward "^|\n")
  4270. (let ((p (point)))
  4271. (org-table-goto-column column-end)
  4272. (skip-chars-forward "^|\n")
  4273. (org-table-add-rectangle-overlay p (point) face)))
  4274. (forward-line)))
  4275. (goto-char (car start-coordinates)))
  4276. (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
  4277. (defun org-table-remove-rectangle-highlight (&rest _ignore)
  4278. "Remove the rectangle overlays."
  4279. (unless org-inhibit-highlight-removal
  4280. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  4281. (mapc 'delete-overlay org-table-rectangle-overlays)
  4282. (setq org-table-rectangle-overlays nil)))
  4283. (defvar-local org-table-coordinate-overlays nil
  4284. "Collects the coordinate grid overlays, so that they can be removed.")
  4285. (defun org-table-overlay-coordinates ()
  4286. "Add overlays to the table at point, to show row/column coordinates."
  4287. (interactive)
  4288. (mapc 'delete-overlay org-table-coordinate-overlays)
  4289. (setq org-table-coordinate-overlays nil)
  4290. (save-excursion
  4291. (let ((id 0) (ih 0) hline eol str ov)
  4292. (goto-char (org-table-begin))
  4293. (while (org-at-table-p)
  4294. (setq eol (point-at-eol))
  4295. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  4296. (push ov org-table-coordinate-overlays)
  4297. (setq hline (looking-at org-table-hline-regexp))
  4298. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  4299. (format "%4d" (setq id (1+ id)))))
  4300. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  4301. (when hline
  4302. (let ((ic 0))
  4303. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  4304. (cl-incf ic)
  4305. (let* ((beg (1+ (match-beginning 0)))
  4306. (s1 (format "$%d" ic))
  4307. (s2 (org-number-to-letters ic))
  4308. (str (if (eq t org-table-use-standard-references) s2 s1))
  4309. (ov (make-overlay beg (+ beg (length str)))))
  4310. (push ov org-table-coordinate-overlays)
  4311. (org-overlay-display ov str 'org-special-keyword 'evaporate)))))
  4312. (forward-line)))))
  4313. ;;;###autoload
  4314. (defun org-table-toggle-coordinate-overlays ()
  4315. "Toggle the display of Row/Column numbers in tables."
  4316. (interactive)
  4317. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  4318. (message "Tables Row/Column numbers display turned %s"
  4319. (if org-table-overlay-coordinates "on" "off"))
  4320. (when (and (org-at-table-p) org-table-overlay-coordinates)
  4321. (org-table-align))
  4322. (unless org-table-overlay-coordinates
  4323. (mapc 'delete-overlay org-table-coordinate-overlays)
  4324. (setq org-table-coordinate-overlays nil)))
  4325. ;;;###autoload
  4326. (defun org-table-toggle-formula-debugger ()
  4327. "Toggle the formula debugger in tables."
  4328. (interactive)
  4329. (setq org-table-formula-debug (not org-table-formula-debug))
  4330. (message "Formula debugging has been turned %s"
  4331. (if org-table-formula-debug "on" "off")))
  4332. ;;; The orgtbl minor mode
  4333. ;; Define a minor mode which can be used in other modes in order to
  4334. ;; integrate the Org table editor.
  4335. ;; This is really a hack, because the Org table editor uses several
  4336. ;; keys which normally belong to the major mode, for example the TAB
  4337. ;; and RET keys. Here is how it works: The minor mode defines all the
  4338. ;; keys necessary to operate the table editor, but wraps the commands
  4339. ;; into a function which tests if the cursor is currently inside
  4340. ;; a table. If that is the case, the table editor command is
  4341. ;; executed. However, when any of those keys is used outside a table,
  4342. ;; the function uses `key-binding' to look up if the key has an
  4343. ;; associated command in another currently active keymap (minor modes,
  4344. ;; major mode, global), and executes that command. There might be
  4345. ;; problems if any of the keys used by the table editor is otherwise
  4346. ;; used as a prefix key.
  4347. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  4348. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  4349. ;; addresses this by checking explicitly for both bindings.
  4350. ;; The optimized version (see variable `orgtbl-optimized') takes over
  4351. ;; all keys which are bound to `self-insert-command' in the *global map*.
  4352. ;; Some modes bind other commands to simple characters, for example
  4353. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  4354. ;; active, this binding is ignored inside tables and replaced with a
  4355. ;; modified self-insert.
  4356. (defvar orgtbl-mode-map (make-keymap)
  4357. "Keymap for `orgtbl-mode'.")
  4358. (defvar org-old-auto-fill-inhibit-regexp nil
  4359. "Local variable used by `orgtbl-mode'.")
  4360. (defconst orgtbl-line-start-regexp
  4361. "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
  4362. "Matches a line belonging to an orgtbl.")
  4363. (defconst orgtbl-extra-font-lock-keywords
  4364. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  4365. 0 (quote 'org-table) 'prepend))
  4366. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  4367. ;; Install it as a minor mode.
  4368. (put 'orgtbl-mode :included t)
  4369. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  4370. ;;;###autoload
  4371. (define-minor-mode orgtbl-mode
  4372. "The Org mode table editor as a minor mode for use in other modes."
  4373. :lighter " OrgTbl" :keymap orgtbl-mode-map
  4374. (org-load-modules-maybe)
  4375. (cond
  4376. ((derived-mode-p 'org-mode)
  4377. ;; Exit without error, in case some hook functions calls this by
  4378. ;; accident in Org mode.
  4379. (message "Orgtbl mode is not useful in Org mode, command ignored"))
  4380. (orgtbl-mode
  4381. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  4382. ;; Make sure we are first in minor-mode-map-alist
  4383. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  4384. ;; FIXME: maybe it should use emulation-mode-map-alists?
  4385. (and c (setq minor-mode-map-alist
  4386. (cons c (delq c minor-mode-map-alist)))))
  4387. (setq-local org-table-may-need-update t)
  4388. (add-hook 'before-change-functions 'org-before-change-function
  4389. nil 'local)
  4390. (setq-local org-old-auto-fill-inhibit-regexp
  4391. auto-fill-inhibit-regexp)
  4392. (setq-local auto-fill-inhibit-regexp
  4393. (if auto-fill-inhibit-regexp
  4394. (concat orgtbl-line-start-regexp "\\|"
  4395. auto-fill-inhibit-regexp)
  4396. orgtbl-line-start-regexp))
  4397. (when (fboundp 'font-lock-add-keywords)
  4398. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  4399. (org-restart-font-lock))
  4400. (easy-menu-add orgtbl-mode-menu))
  4401. (t
  4402. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  4403. (remove-hook 'before-change-functions 'org-before-change-function t)
  4404. (when (fboundp 'font-lock-remove-keywords)
  4405. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  4406. (org-restart-font-lock))
  4407. (easy-menu-remove orgtbl-mode-menu)
  4408. (force-mode-line-update 'all))))
  4409. (defun orgtbl-make-binding (fun n &rest keys)
  4410. "Create a function for binding in the table minor mode.
  4411. FUN is the command to call inside a table. N is used to create a unique
  4412. command name. KEYS are keys that should be checked in for a command
  4413. to execute outside of tables."
  4414. (eval
  4415. (list 'defun
  4416. (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
  4417. '(arg)
  4418. (concat "In tables, run `" (symbol-name fun) "'.\n"
  4419. "Outside of tables, run the binding of `"
  4420. (mapconcat #'key-description keys "' or `")
  4421. "'.")
  4422. '(interactive "p")
  4423. (list 'if
  4424. '(org-at-table-p)
  4425. (list 'call-interactively (list 'quote fun))
  4426. (list 'let '(orgtbl-mode)
  4427. (list 'call-interactively
  4428. (append '(or)
  4429. (mapcar (lambda (k)
  4430. (list 'key-binding k))
  4431. keys)
  4432. '('orgtbl-error))))))))
  4433. (defun orgtbl-error ()
  4434. "Error when there is no default binding for a table key."
  4435. (interactive)
  4436. (user-error "This key has no function outside tables"))
  4437. (defun orgtbl-setup ()
  4438. "Setup orgtbl keymaps."
  4439. (let ((nfunc 0)
  4440. (bindings
  4441. '(([(meta shift left)] org-table-delete-column)
  4442. ([(meta left)] org-table-move-column-left)
  4443. ([(meta right)] org-table-move-column-right)
  4444. ([(meta shift right)] org-table-insert-column)
  4445. ([(meta shift up)] org-table-kill-row)
  4446. ([(meta shift down)] org-table-insert-row)
  4447. ([(meta up)] org-table-move-row-up)
  4448. ([(meta down)] org-table-move-row-down)
  4449. ("\C-c\C-w" org-table-cut-region)
  4450. ("\C-c\M-w" org-table-copy-region)
  4451. ("\C-c\C-y" org-table-paste-rectangle)
  4452. ("\C-c\C-w" org-table-wrap-region)
  4453. ("\C-c-" org-table-insert-hline)
  4454. ("\C-c}" org-table-toggle-coordinate-overlays)
  4455. ("\C-c{" org-table-toggle-formula-debugger)
  4456. ("\C-m" org-table-next-row)
  4457. ([(shift return)] org-table-copy-down)
  4458. ("\C-c?" org-table-field-info)
  4459. ("\C-c " org-table-blank-field)
  4460. ("\C-c+" org-table-sum)
  4461. ("\C-c=" org-table-eval-formula)
  4462. ("\C-c'" org-table-edit-formulas)
  4463. ("\C-c`" org-table-edit-field)
  4464. ("\C-c*" org-table-recalculate)
  4465. ("\C-c^" org-table-sort-lines)
  4466. ("\M-a" org-table-beginning-of-field)
  4467. ("\M-e" org-table-end-of-field)
  4468. ([(control ?#)] org-table-rotate-recalc-marks)))
  4469. elt key fun cmd)
  4470. (while (setq elt (pop bindings))
  4471. (setq nfunc (1+ nfunc))
  4472. (setq key (org-key (car elt))
  4473. fun (nth 1 elt)
  4474. cmd (orgtbl-make-binding fun nfunc key))
  4475. (org-defkey orgtbl-mode-map key cmd))
  4476. ;; Special treatment needed for TAB, RET and DEL
  4477. (org-defkey orgtbl-mode-map [(return)]
  4478. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  4479. (org-defkey orgtbl-mode-map "\C-m"
  4480. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  4481. (org-defkey orgtbl-mode-map [(tab)]
  4482. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  4483. (org-defkey orgtbl-mode-map "\C-i"
  4484. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  4485. (org-defkey orgtbl-mode-map [(shift tab)]
  4486. (orgtbl-make-binding 'org-table-previous-field 104
  4487. [(shift tab)] [(tab)] "\C-i"))
  4488. (org-defkey orgtbl-mode-map [backspace]
  4489. (orgtbl-make-binding 'org-delete-backward-char 109
  4490. [backspace] (kbd "DEL")))
  4491. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  4492. (orgtbl-make-binding 'org-table-previous-field 107
  4493. [S-iso-lefttab] [backtab] [(shift tab)]
  4494. [(tab)] "\C-i"))
  4495. (org-defkey orgtbl-mode-map [backtab]
  4496. (orgtbl-make-binding 'org-table-previous-field 108
  4497. [backtab] [S-iso-lefttab] [(shift tab)]
  4498. [(tab)] "\C-i"))
  4499. (org-defkey orgtbl-mode-map "\M-\C-m"
  4500. (orgtbl-make-binding 'org-table-wrap-region 105
  4501. "\M-\C-m" [(meta return)]))
  4502. (org-defkey orgtbl-mode-map [(meta return)]
  4503. (orgtbl-make-binding 'org-table-wrap-region 106
  4504. [(meta return)] "\M-\C-m"))
  4505. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  4506. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  4507. (when orgtbl-optimized
  4508. ;; If the user wants maximum table support, we need to hijack
  4509. ;; some standard editing functions
  4510. (org-remap orgtbl-mode-map
  4511. 'self-insert-command 'orgtbl-self-insert-command
  4512. 'delete-char 'org-delete-char
  4513. 'delete-backward-char 'org-delete-backward-char)
  4514. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  4515. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
  4516. '("OrgTbl"
  4517. ["Create or convert" org-table-create-or-convert-from-region
  4518. :active (not (org-at-table-p)) :keys "C-c |" ]
  4519. "--"
  4520. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  4521. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  4522. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  4523. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  4524. "--"
  4525. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  4526. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  4527. ["Copy Field from Above"
  4528. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  4529. "--"
  4530. ("Column"
  4531. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  4532. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  4533. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  4534. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  4535. ("Row"
  4536. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  4537. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  4538. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  4539. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  4540. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  4541. "--"
  4542. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  4543. ("Rectangle"
  4544. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  4545. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  4546. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  4547. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  4548. "--"
  4549. ("Radio tables"
  4550. ["Insert table template" orgtbl-insert-radio-table
  4551. (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates)]
  4552. ["Comment/uncomment table" orgtbl-toggle-comment t])
  4553. "--"
  4554. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  4555. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  4556. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  4557. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  4558. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  4559. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  4560. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  4561. ["Sum Column/Rectangle" org-table-sum
  4562. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  4563. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  4564. ["Debug Formulas"
  4565. org-table-toggle-formula-debugger :active (org-at-table-p)
  4566. :keys "C-c {"
  4567. :style toggle :selected org-table-formula-debug]
  4568. ["Show Col/Row Numbers"
  4569. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  4570. :keys "C-c }"
  4571. :style toggle :selected org-table-overlay-coordinates]
  4572. "--"
  4573. ("Plot"
  4574. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4575. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4576. t))
  4577. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4578. "If the cursor is inside a table, realign the table.
  4579. If it is a table to be sent away to a receiver, do it.
  4580. With prefix arg, also recompute table."
  4581. (interactive "P")
  4582. (let ((case-fold-search t) (pos (point)) action)
  4583. (save-excursion
  4584. (beginning-of-line 1)
  4585. (setq action (cond
  4586. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4587. ((looking-at "[ \t]*|") pos)
  4588. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4589. (cond
  4590. ((integerp action)
  4591. (goto-char action)
  4592. (org-table-maybe-eval-formula)
  4593. (if arg
  4594. (call-interactively 'org-table-recalculate)
  4595. (org-table-maybe-recalculate-line))
  4596. (call-interactively 'org-table-align)
  4597. (when (orgtbl-send-table 'maybe)
  4598. (run-hooks 'orgtbl-after-send-table-hook)))
  4599. ((eq action 'recalc)
  4600. (save-excursion
  4601. (beginning-of-line 1)
  4602. (skip-chars-backward " \r\n\t")
  4603. (if (org-at-table-p)
  4604. (org-call-with-arg 'org-table-recalculate t))))
  4605. (t (let (orgtbl-mode)
  4606. (call-interactively (key-binding "\C-c\C-c")))))))
  4607. (defun orgtbl-create-or-convert-from-region (_arg)
  4608. "Create table or convert region to table, if no conflicting binding.
  4609. This installs the table binding `C-c |', but only if there is no
  4610. conflicting binding to this key outside orgtbl-mode."
  4611. (interactive "P")
  4612. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4613. (if cmd
  4614. (call-interactively cmd)
  4615. (call-interactively 'org-table-create-or-convert-from-region))))
  4616. (defun orgtbl-tab (arg)
  4617. "Justification and field motion for `orgtbl-mode'."
  4618. (interactive "P")
  4619. (if arg (org-table-edit-field t)
  4620. (org-table-justify-field-maybe)
  4621. (org-table-next-field)))
  4622. (defun orgtbl-ret ()
  4623. "Justification and field motion for `orgtbl-mode'."
  4624. (interactive)
  4625. (if (bobp)
  4626. (newline)
  4627. (org-table-justify-field-maybe)
  4628. (org-table-next-row)))
  4629. (defun orgtbl-self-insert-command (N)
  4630. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4631. If the cursor is in a table looking at whitespace, the whitespace is
  4632. overwritten, and the table is not marked as requiring realignment."
  4633. (interactive "p")
  4634. (if (and (org-at-table-p)
  4635. (or
  4636. (and org-table-auto-blank-field
  4637. (member last-command
  4638. '(orgtbl-hijacker-command-100
  4639. orgtbl-hijacker-command-101
  4640. orgtbl-hijacker-command-102
  4641. orgtbl-hijacker-command-103
  4642. orgtbl-hijacker-command-104
  4643. orgtbl-hijacker-command-105
  4644. yas/expand))
  4645. (org-table-blank-field))
  4646. t)
  4647. (eq N 1)
  4648. (looking-at "[^|\n]* \\( \\)|"))
  4649. (let (org-table-may-need-update)
  4650. (delete-region (match-beginning 1) (match-end 1))
  4651. (self-insert-command N))
  4652. (setq org-table-may-need-update t)
  4653. (let* (orgtbl-mode
  4654. a
  4655. (cmd (or (key-binding
  4656. (or (and (listp function-key-map)
  4657. (setq a (assoc last-input-event function-key-map))
  4658. (cdr a))
  4659. (vector last-input-event)))
  4660. 'self-insert-command)))
  4661. (call-interactively cmd)
  4662. (if (and org-self-insert-cluster-for-undo
  4663. (eq cmd 'self-insert-command))
  4664. (if (not (eq last-command 'orgtbl-self-insert-command))
  4665. (setq org-self-insert-command-undo-counter 1)
  4666. (if (>= org-self-insert-command-undo-counter 20)
  4667. (setq org-self-insert-command-undo-counter 1)
  4668. (and (> org-self-insert-command-undo-counter 0)
  4669. buffer-undo-list
  4670. (not (cadr buffer-undo-list)) ; remove nil entry
  4671. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  4672. (setq org-self-insert-command-undo-counter
  4673. (1+ org-self-insert-command-undo-counter))))))))
  4674. ;;;###autoload
  4675. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  4676. "Regular expression matching exponentials as produced by calc.")
  4677. (defun orgtbl-gather-send-defs ()
  4678. "Gather a plist of :name, :transform, :params for each destination before
  4679. a radio table."
  4680. (save-excursion
  4681. (goto-char (org-table-begin))
  4682. (let (rtn)
  4683. (beginning-of-line 0)
  4684. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  4685. (let ((name (org-no-properties (match-string 1)))
  4686. (transform (intern (match-string 2)))
  4687. (params (if (match-end 3)
  4688. (read (concat "(" (match-string 3) ")")))))
  4689. (push (list :name name :transform transform :params params)
  4690. rtn)
  4691. (beginning-of-line 0)))
  4692. rtn)))
  4693. (defun orgtbl-send-replace-tbl (name text)
  4694. "Find and replace table NAME with TEXT."
  4695. (save-excursion
  4696. (goto-char (point-min))
  4697. (let* ((location-flag nil)
  4698. (name (regexp-quote name))
  4699. (begin-re (format "BEGIN +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name))
  4700. (end-re (format "END +RECEIVE +ORGTBL +%s\\([ \t]\\|$\\)" name)))
  4701. (while (re-search-forward begin-re nil t)
  4702. (unless location-flag (setq location-flag t))
  4703. (let ((beg (line-beginning-position 2)))
  4704. (unless (re-search-forward end-re nil t)
  4705. (user-error "Cannot find end of receiver location at %d" beg))
  4706. (beginning-of-line)
  4707. (delete-region beg (point))
  4708. (insert text "\n")))
  4709. (unless location-flag
  4710. (user-error "No valid receiver location found in the buffer")))))
  4711. ;;;###autoload
  4712. (defun org-table-to-lisp (&optional txt)
  4713. "Convert the table at point to a Lisp structure.
  4714. The structure will be a list. Each item is either the symbol `hline'
  4715. for a horizontal separator line, or a list of field values as strings.
  4716. The table is taken from the parameter TXT, or from the buffer at point."
  4717. (unless (or txt (org-at-table-p)) (user-error "No table at point"))
  4718. (let ((txt (or txt
  4719. (buffer-substring-no-properties (org-table-begin)
  4720. (org-table-end)))))
  4721. (mapcar (lambda (x)
  4722. (if (string-match org-table-hline-regexp x) 'hline
  4723. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  4724. (org-split-string txt "[ \t]*\n[ \t]*"))))
  4725. (defun orgtbl-send-table (&optional maybe)
  4726. "Send a transformed version of table at point to the receiver position.
  4727. With argument MAYBE, fail quietly if no transformation is defined
  4728. for this table."
  4729. (interactive)
  4730. (catch 'exit
  4731. (unless (org-at-table-p) (user-error "Not at a table"))
  4732. ;; when non-interactive, we assume align has just happened.
  4733. (when (called-interactively-p 'any) (org-table-align))
  4734. (let ((dests (orgtbl-gather-send-defs))
  4735. (table (org-table-to-lisp
  4736. (buffer-substring-no-properties (org-table-begin)
  4737. (org-table-end))))
  4738. (ntbl 0))
  4739. (unless dests
  4740. (if maybe (throw 'exit nil)
  4741. (user-error "Don't know how to transform this table")))
  4742. (dolist (dest dests)
  4743. (let ((name (plist-get dest :name))
  4744. (transform (plist-get dest :transform))
  4745. (params (plist-get dest :params)))
  4746. (unless (fboundp transform)
  4747. (user-error "No such transformation function %s" transform))
  4748. (orgtbl-send-replace-tbl name (funcall transform table params)))
  4749. (cl-incf ntbl))
  4750. (message "Table converted and installed at %d receiver location%s"
  4751. ntbl (if (> ntbl 1) "s" ""))
  4752. (and (> ntbl 0) ntbl))))
  4753. (defun org-remove-by-index (list indices &optional i0)
  4754. "Remove the elements in LIST with indices in INDICES.
  4755. First element has index 0, or I0 if given."
  4756. (if (not indices)
  4757. list
  4758. (if (integerp indices) (setq indices (list indices)))
  4759. (setq i0 (1- (or i0 0)))
  4760. (delq :rm (mapcar (lambda (x)
  4761. (setq i0 (1+ i0))
  4762. (if (memq i0 indices) :rm x))
  4763. list))))
  4764. (defun orgtbl-toggle-comment ()
  4765. "Comment or uncomment the orgtbl at point."
  4766. (interactive)
  4767. (let* ((case-fold-search t)
  4768. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  4769. (re2 (concat "^" orgtbl-line-start-regexp))
  4770. (commented (save-excursion (beginning-of-line 1)
  4771. (cond ((looking-at re1) t)
  4772. ((looking-at re2) nil)
  4773. (t (user-error "Not at an org table")))))
  4774. (re (if commented re1 re2))
  4775. beg end)
  4776. (save-excursion
  4777. (beginning-of-line 1)
  4778. (while (looking-at re) (beginning-of-line 0))
  4779. (beginning-of-line 2)
  4780. (setq beg (point))
  4781. (while (looking-at re) (beginning-of-line 2))
  4782. (setq end (point)))
  4783. (comment-region beg end (if commented '(4) nil))))
  4784. (defun orgtbl-insert-radio-table ()
  4785. "Insert a radio table template appropriate for this major mode."
  4786. (interactive)
  4787. (let* ((e (cl-assoc-if #'derived-mode-p orgtbl-radio-table-templates))
  4788. (txt (nth 1 e))
  4789. name pos)
  4790. (unless e (user-error "No radio table setup defined for %s" major-mode))
  4791. (setq name (read-string "Table name: "))
  4792. (while (string-match "%n" txt)
  4793. (setq txt (replace-match name t t txt)))
  4794. (or (bolp) (insert "\n"))
  4795. (setq pos (point))
  4796. (insert txt)
  4797. (goto-char pos)))
  4798. ;;;###autoload
  4799. (defun orgtbl-to-generic (table params)
  4800. "Convert the orgtbl-mode TABLE to some other format.
  4801. This generic routine can be used for many standard cases.
  4802. TABLE is a list, each entry either the symbol `hline' for
  4803. a horizontal separator line, or a list of fields for that
  4804. line. PARAMS is a property list of parameters that can
  4805. influence the conversion.
  4806. Valid parameters are:
  4807. :backend, :raw
  4808. Export back-end used as a basis to transcode elements of the
  4809. table, when no specific parameter applies to it. It is also
  4810. used to translate cells contents. You can prevent this by
  4811. setting :raw property to a non-nil value.
  4812. :splice
  4813. When non-nil, only convert rows, not the table itself. This is
  4814. equivalent to setting to the empty string both :tstart
  4815. and :tend, which see.
  4816. :skip
  4817. When set to an integer N, skip the first N lines of the table.
  4818. Horizontal separation lines do count for this parameter!
  4819. :skipcols
  4820. List of columns that should be skipped. If the table has
  4821. a column with calculation marks, that column is automatically
  4822. discarded beforehand.
  4823. :hline
  4824. String to be inserted on horizontal separation lines. May be
  4825. nil to ignore these lines altogether.
  4826. :sep
  4827. Separator between two fields, as a string.
  4828. Each in the following group may be either a string or a function
  4829. of no arguments returning a string:
  4830. :tstart, :tend
  4831. Strings to start and end the table. Ignored when :splice is t.
  4832. :lstart, :lend
  4833. Strings to start and end a new table line.
  4834. :llstart, :llend
  4835. Strings to start and end the last table line. Default,
  4836. respectively, to :lstart and :lend.
  4837. Each in the following group may be a string or a function of one
  4838. argument (either the cells in the current row, as a list of
  4839. strings, or the current cell) returning a string:
  4840. :lfmt
  4841. Format string for an entire row, with enough %s to capture all
  4842. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  4843. :llfmt
  4844. Format for the entire last line, defaults to :lfmt.
  4845. :fmt
  4846. A format to be used to wrap the field, should contain %s for
  4847. the original field value. For example, to wrap everything in
  4848. dollars, you could use :fmt \"$%s$\". This may also be
  4849. a property list with column numbers and format strings, or
  4850. functions, e.g.,
  4851. (:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  4852. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  4853. Same as above, specific for the header lines in the table.
  4854. All lines before the first hline are treated as header. If
  4855. any of these is not present, the data line value is used.
  4856. This may be either a string or a function of two arguments:
  4857. :efmt
  4858. Use this format to print numbers with exponential. The format
  4859. should have %s twice for inserting mantissa and exponent, for
  4860. example \"%s\\\\times10^{%s}\". This may also be a property
  4861. list with column numbers and format strings or functions.
  4862. :fmt will still be applied after :efmt."
  4863. ;; Make sure `org-export-create-backend' is available.
  4864. (require 'ox)
  4865. (let* ((backend (plist-get params :backend))
  4866. (custom-backend
  4867. ;; Build a custom back-end according to PARAMS. Before
  4868. ;; defining a translator, check if there is anything to do.
  4869. ;; When there isn't, let BACKEND handle the element.
  4870. (org-export-create-backend
  4871. :parent (or backend 'org)
  4872. :transcoders
  4873. `((table . ,(org-table--to-generic-table params))
  4874. (table-row . ,(org-table--to-generic-row params))
  4875. (table-cell . ,(org-table--to-generic-cell params))
  4876. ;; Macros are not going to be expanded. However, no
  4877. ;; regular back-end has a transcoder for them. We
  4878. ;; provide one so they are not ignored, but displayed
  4879. ;; as-is instead.
  4880. (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
  4881. data info)
  4882. ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
  4883. ;; Initialize communication channel in INFO.
  4884. (with-temp-buffer
  4885. (let ((org-inhibit-startup t)) (org-mode))
  4886. (let ((standard-output (current-buffer))
  4887. (org-element-use-cache nil))
  4888. (dolist (e table)
  4889. (cond ((eq e 'hline) (princ "|--\n"))
  4890. ((consp e)
  4891. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  4892. (princ "\n")))))
  4893. ;; Add back-end specific filters, but not user-defined ones. In
  4894. ;; particular, make sure to call parse-tree filters on the
  4895. ;; table.
  4896. (setq info
  4897. (let ((org-export-filters-alist nil))
  4898. (org-export-install-filters
  4899. (org-combine-plists
  4900. (org-export-get-environment backend nil params)
  4901. `(:back-end ,(org-export-get-backend backend))))))
  4902. (setq data
  4903. (org-export-filter-apply-functions
  4904. (plist-get info :filter-parse-tree)
  4905. (org-element-map (org-element-parse-buffer) 'table
  4906. #'identity nil t)
  4907. info)))
  4908. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  4909. (user-error "Unknown :backend value"))
  4910. (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
  4911. ;; Handle :skip parameter.
  4912. (let ((skip (plist-get info :skip)))
  4913. (when skip
  4914. (unless (wholenump skip) (user-error "Wrong :skip value"))
  4915. (let ((n 0))
  4916. (org-element-map data 'table-row
  4917. (lambda (row)
  4918. (if (>= n skip) t
  4919. (org-element-extract-element row)
  4920. (cl-incf n)
  4921. nil))
  4922. nil t))))
  4923. ;; Handle :skipcols parameter.
  4924. (let ((skipcols (plist-get info :skipcols)))
  4925. (when skipcols
  4926. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  4927. (org-element-map data 'table
  4928. (lambda (table)
  4929. (let ((specialp (org-export-table-has-special-column-p table)))
  4930. (dolist (row (org-element-contents table))
  4931. (when (eq (org-element-property :type row) 'standard)
  4932. (let ((c 1))
  4933. (dolist (cell (nthcdr (if specialp 1 0)
  4934. (org-element-contents row)))
  4935. (when (memq c skipcols)
  4936. (org-element-extract-element cell))
  4937. (cl-incf c))))))))))
  4938. ;; Since we are going to export using a low-level mechanism,
  4939. ;; ignore special column and special rows manually.
  4940. (let ((special? (org-export-table-has-special-column-p data))
  4941. ignore)
  4942. (org-element-map data (if special? '(table-cell table-row) 'table-row)
  4943. (lambda (datum)
  4944. (when (if (eq (org-element-type datum) 'table-row)
  4945. (org-export-table-row-is-special-p datum nil)
  4946. (org-export-first-sibling-p datum nil))
  4947. (push datum ignore))))
  4948. (setq info (plist-put info :ignore-list ignore)))
  4949. ;; We use a low-level mechanism to export DATA so as to skip all
  4950. ;; usual pre-processing and post-processing, i.e., hooks, Babel
  4951. ;; code evaluation, include keywords and macro expansion. Only
  4952. ;; back-end specific filters are retained.
  4953. (let ((output (org-export-data-with-backend data custom-backend info)))
  4954. ;; Remove final newline.
  4955. (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
  4956. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  4957. (cond ((null value) nil)
  4958. ((functionp value) `(funcall ',value ,@args))
  4959. ((stringp value)
  4960. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  4961. (args `(format ,value ,@args))
  4962. (t value)))
  4963. ((and with-cons (consp value))
  4964. `(let ((val (cadr (memq column ',value))))
  4965. (cond ((null val) contents)
  4966. ((stringp val) (format val ,@args))
  4967. ((functionp val) (funcall val ,@args))
  4968. (t (user-error "Wrong %s value" ,name)))))
  4969. (t (user-error "Wrong %s value" name))))
  4970. (defun org-table--to-generic-table (params)
  4971. "Return custom table transcoder according to PARAMS.
  4972. PARAMS is a plist. See `orgtbl-to-generic' for more
  4973. information."
  4974. (let ((backend (plist-get params :backend))
  4975. (splice (plist-get params :splice))
  4976. (tstart (plist-get params :tstart))
  4977. (tend (plist-get params :tend)))
  4978. `(lambda (table contents info)
  4979. (concat
  4980. ,(and tstart (not splice)
  4981. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  4982. ,(if (or (not backend) tstart tend splice) 'contents
  4983. `(org-export-with-backend ',backend table contents info))
  4984. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  4985. (defun org-table--to-generic-row (params)
  4986. "Return custom table row transcoder according to PARAMS.
  4987. PARAMS is a plist. See `orgtbl-to-generic' for more
  4988. information."
  4989. (let* ((backend (plist-get params :backend))
  4990. (lstart (plist-get params :lstart))
  4991. (llstart (plist-get params :llstart))
  4992. (hlstart (plist-get params :hlstart))
  4993. (hllstart (plist-get params :hllstart))
  4994. (lend (plist-get params :lend))
  4995. (llend (plist-get params :llend))
  4996. (hlend (plist-get params :hlend))
  4997. (hllend (plist-get params :hllend))
  4998. (lfmt (plist-get params :lfmt))
  4999. (llfmt (plist-get params :llfmt))
  5000. (hlfmt (plist-get params :hlfmt))
  5001. (hllfmt (plist-get params :hllfmt)))
  5002. `(lambda (row contents info)
  5003. (if (eq (org-element-property :type row) 'rule)
  5004. ,(cond
  5005. ((plist-member params :hline)
  5006. (org-table--generic-apply (plist-get params :hline) ":hline"))
  5007. (backend `(org-export-with-backend ',backend row nil info)))
  5008. (let ((headerp ,(and (or hlfmt hlstart hlend)
  5009. '(org-export-table-row-in-header-p row info)))
  5010. (last-header-p
  5011. ,(and (or hllfmt hllstart hllend)
  5012. '(org-export-table-row-ends-header-p row info)))
  5013. (lastp (not (org-export-get-next-element row info))))
  5014. (when contents
  5015. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  5016. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  5017. ;; `:lstart', `:lend' and their relatives.
  5018. ,(let ((cells
  5019. '(org-element-map row 'table-cell
  5020. (lambda (cell)
  5021. ;; Export all cells, without separators.
  5022. ;;
  5023. ;; Use `org-export-data-with-backend'
  5024. ;; instead of `org-export-data' to eschew
  5025. ;; cached values, which
  5026. ;; ignore :orgtbl-ignore-sep parameter.
  5027. (org-export-data-with-backend
  5028. cell
  5029. (plist-get info :back-end)
  5030. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  5031. info)))
  5032. `(cond
  5033. ,(and hllfmt
  5034. `(last-header-p ,(org-table--generic-apply
  5035. hllfmt ":hllfmt" nil cells)))
  5036. ,(and hlfmt
  5037. `(headerp ,(org-table--generic-apply
  5038. hlfmt ":hlfmt" nil cells)))
  5039. ,(and llfmt
  5040. `(lastp ,(org-table--generic-apply
  5041. llfmt ":llfmt" nil cells)))
  5042. (t
  5043. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  5044. `(concat
  5045. (cond
  5046. ,(and
  5047. (or hllstart hllend)
  5048. `(last-header-p
  5049. (concat
  5050. ,(org-table--generic-apply hllstart ":hllstart")
  5051. contents
  5052. ,(org-table--generic-apply hllend ":hllend"))))
  5053. ,(and
  5054. (or hlstart hlend)
  5055. `(headerp
  5056. (concat
  5057. ,(org-table--generic-apply hlstart ":hlstart")
  5058. contents
  5059. ,(org-table--generic-apply hlend ":hlend"))))
  5060. ,(and
  5061. (or llstart llend)
  5062. `(lastp
  5063. (concat
  5064. ,(org-table--generic-apply llstart ":llstart")
  5065. contents
  5066. ,(org-table--generic-apply llend ":llend"))))
  5067. (t
  5068. ,(cond
  5069. ((or lstart lend)
  5070. `(concat
  5071. ,(org-table--generic-apply lstart ":lstart")
  5072. contents
  5073. ,(org-table--generic-apply lend ":lend")))
  5074. (backend
  5075. `(org-export-with-backend
  5076. ',backend row contents info))
  5077. (t 'contents)))))))))))))))
  5078. (defun org-table--to-generic-cell (params)
  5079. "Return custom table cell transcoder according to PARAMS.
  5080. PARAMS is a plist. See `orgtbl-to-generic' for more
  5081. information."
  5082. (let* ((backend (plist-get params :backend))
  5083. (efmt (plist-get params :efmt))
  5084. (fmt (plist-get params :fmt))
  5085. (hfmt (plist-get params :hfmt))
  5086. (sep (plist-get params :sep))
  5087. (hsep (plist-get params :hsep)))
  5088. `(lambda (cell contents info)
  5089. ;; Make sure that contents are exported as Org data when :raw
  5090. ;; parameter is non-nil.
  5091. ,(when (and backend (plist-get params :raw))
  5092. `(setq contents
  5093. ;; Since we don't know what are the pseudo object
  5094. ;; types defined in backend, we cannot pass them to
  5095. ;; `org-element-interpret-data'. As a consequence,
  5096. ;; they will be treated as pseudo elements, and will
  5097. ;; have newlines appended instead of spaces.
  5098. ;; Therefore, we must make sure :post-blank value is
  5099. ;; really turned into spaces.
  5100. (replace-regexp-in-string
  5101. "\n" " "
  5102. (org-trim
  5103. (org-element-interpret-data
  5104. (org-element-contents cell))))))
  5105. (let ((headerp ,(and (or hfmt hsep)
  5106. '(org-export-table-row-in-header-p
  5107. (org-export-get-parent-element cell) info)))
  5108. (column
  5109. ;; Call costly `org-export-table-cell-address' only if
  5110. ;; absolutely necessary, i.e., if one
  5111. ;; of :fmt :efmt :hfmt has a "plist type" value.
  5112. ,(and (cl-some (lambda (v) (integerp (car-safe v)))
  5113. (list efmt hfmt fmt))
  5114. '(1+ (cdr (org-export-table-cell-address cell info))))))
  5115. (when contents
  5116. ;; Check if we can apply `:efmt' on CONTENTS.
  5117. ,(when efmt
  5118. `(when (string-match orgtbl-exp-regexp contents)
  5119. (let ((mantissa (match-string 1 contents))
  5120. (exponent (match-string 2 contents)))
  5121. (setq contents ,(org-table--generic-apply
  5122. efmt ":efmt" t 'mantissa 'exponent)))))
  5123. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  5124. (cond
  5125. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  5126. hfmt ":hfmt" t 'contents))))
  5127. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  5128. fmt ":fmt" t 'contents))))))
  5129. ;; If a separator is provided, use it instead of BACKEND's.
  5130. ;; Separators are ignored when LFMT (or equivalent) is
  5131. ;; provided.
  5132. ,(cond
  5133. ((or hsep sep)
  5134. `(if (or ,(and (not sep) '(not headerp))
  5135. (plist-get info :orgtbl-ignore-sep)
  5136. (not (org-export-get-next-element cell info)))
  5137. ,(if (not backend) 'contents
  5138. `(org-export-with-backend ',backend cell contents info))
  5139. (concat contents
  5140. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  5141. (or hsep sep)))))
  5142. (backend `(org-export-with-backend ',backend cell contents info))
  5143. (t 'contents))))))
  5144. ;;;###autoload
  5145. (defun orgtbl-to-tsv (table params)
  5146. "Convert the orgtbl-mode table to TAB separated material."
  5147. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  5148. ;;;###autoload
  5149. (defun orgtbl-to-csv (table params)
  5150. "Convert the orgtbl-mode table to CSV material.
  5151. This does take care of the proper quoting of fields with comma or quotes."
  5152. (orgtbl-to-generic table
  5153. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  5154. params)))
  5155. ;;;###autoload
  5156. (defun orgtbl-to-latex (table params)
  5157. "Convert the orgtbl-mode TABLE to LaTeX.
  5158. TABLE is a list, each entry either the symbol `hline' for
  5159. a horizontal separator line, or a list of fields for that line.
  5160. PARAMS is a property list of parameters that can influence the
  5161. conversion. All parameters from `orgtbl-to-generic' are
  5162. supported. It is also possible to use the following ones:
  5163. :booktabs
  5164. When non-nil, use formal \"booktabs\" style.
  5165. :environment
  5166. Specify environment to use, as a string. If you use
  5167. \"longtable\", you may also want to specify :language property,
  5168. as a string, to get proper continuation strings."
  5169. (require 'ox-latex)
  5170. (orgtbl-to-generic
  5171. table
  5172. (org-combine-plists
  5173. ;; Provide sane default values.
  5174. (list :backend 'latex
  5175. :latex-default-table-mode 'table
  5176. :latex-tables-centered nil
  5177. :latex-tables-booktabs (plist-get params :booktabs)
  5178. :latex-table-scientific-notation nil
  5179. :latex-default-table-environment
  5180. (or (plist-get params :environment) "tabular"))
  5181. params)))
  5182. ;;;###autoload
  5183. (defun orgtbl-to-html (table params)
  5184. "Convert the orgtbl-mode TABLE to HTML.
  5185. TABLE is a list, each entry either the symbol `hline' for
  5186. a horizontal separator line, or a list of fields for that line.
  5187. PARAMS is a property list of parameters that can influence the
  5188. conversion. All parameters from `orgtbl-to-generic' are
  5189. supported. It is also possible to use the following one:
  5190. :attributes
  5191. Attributes and values, as a plist, which will be used in
  5192. <table> tag."
  5193. (require 'ox-html)
  5194. (orgtbl-to-generic
  5195. table
  5196. (org-combine-plists
  5197. ;; Provide sane default values.
  5198. (list :backend 'html
  5199. :html-table-data-tags '("<td%s>" . "</td>")
  5200. :html-table-use-header-tags-for-first-column nil
  5201. :html-table-align-individual-fields t
  5202. :html-table-row-tags '("<tr>" . "</tr>")
  5203. :html-table-attributes
  5204. (if (plist-member params :attributes)
  5205. (plist-get params :attributes)
  5206. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  5207. :frame "hsides")))
  5208. params)))
  5209. ;;;###autoload
  5210. (defun orgtbl-to-texinfo (table params)
  5211. "Convert the orgtbl-mode TABLE to Texinfo.
  5212. TABLE is a list, each entry either the symbol `hline' for
  5213. a horizontal separator line, or a list of fields for that line.
  5214. PARAMS is a property list of parameters that can influence the
  5215. conversion. All parameters from `orgtbl-to-generic' are
  5216. supported. It is also possible to use the following one:
  5217. :columns
  5218. Column widths, as a string. When providing column fractions,
  5219. \"@columnfractions\" command can be omitted."
  5220. (require 'ox-texinfo)
  5221. (let ((output
  5222. (orgtbl-to-generic
  5223. table
  5224. (org-combine-plists
  5225. (list :backend 'texinfo
  5226. :texinfo-tables-verbatim nil
  5227. :texinfo-table-scientific-notation nil)
  5228. params)))
  5229. (columns (let ((w (plist-get params :columns)))
  5230. (cond ((not w) nil)
  5231. ((string-match-p "{\\|@columnfractions " w) w)
  5232. (t (concat "@columnfractions " w))))))
  5233. (if (not columns) output
  5234. (replace-regexp-in-string
  5235. "@multitable \\(.*\\)" columns output t nil 1))))
  5236. ;;;###autoload
  5237. (defun orgtbl-to-orgtbl (table params)
  5238. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  5239. TABLE is a list, each entry either the symbol `hline' for
  5240. a horizontal separator line, or a list of fields for that line.
  5241. PARAMS is a property list of parameters that can influence the
  5242. conversion. All parameters from `orgtbl-to-generic' are
  5243. supported.
  5244. Useful when slicing one table into many. The :hline, :sep,
  5245. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  5246. be set to provide ORGTBL directives for the generated table."
  5247. (require 'ox-org)
  5248. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  5249. (defun orgtbl-to-table.el (table params)
  5250. "Convert the orgtbl-mode TABLE into a table.el table.
  5251. TABLE is a list, each entry either the symbol `hline' for
  5252. a horizontal separator line, or a list of fields for that line.
  5253. PARAMS is a property list of parameters that can influence the
  5254. conversion. All parameters from `orgtbl-to-generic' are
  5255. supported."
  5256. (with-temp-buffer
  5257. (insert (orgtbl-to-orgtbl table params))
  5258. (org-table-align)
  5259. (replace-regexp-in-string
  5260. "-|" "-+"
  5261. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  5262. (defun orgtbl-to-unicode (table params)
  5263. "Convert the orgtbl-mode TABLE into a table with unicode characters.
  5264. TABLE is a list, each entry either the symbol `hline' for
  5265. a horizontal separator line, or a list of fields for that line.
  5266. PARAMS is a property list of parameters that can influence the
  5267. conversion. All parameters from `orgtbl-to-generic' are
  5268. supported. It is also possible to use the following ones:
  5269. :ascii-art
  5270. When non-nil, use \"ascii-art-to-unicode\" package to translate
  5271. the table. You can download it here:
  5272. http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  5273. :narrow
  5274. When non-nil, narrow columns width than provided width cookie,
  5275. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  5276. (require 'ox-ascii)
  5277. (orgtbl-to-generic
  5278. table
  5279. (org-combine-plists
  5280. (list :backend 'ascii
  5281. :ascii-charset 'utf-8
  5282. :ascii-table-widen-columns (not (plist-get params :narrow))
  5283. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  5284. params)))
  5285. ;; Put the cursor in a column containing numerical values
  5286. ;; of an Org table,
  5287. ;; type C-c " a
  5288. ;; A new column is added with a bar plot.
  5289. ;; When the table is refreshed (C-u C-c *),
  5290. ;; the plot is updated to reflect the new values.
  5291. (defun orgtbl-ascii-draw (value min max &optional width characters)
  5292. "Draw an ascii bar in a table.
  5293. VALUE is the value to plot, it determines the width of the bar to draw.
  5294. MIN is the value that will be displayed as empty (zero width bar).
  5295. MAX is the value that will draw a bar filling all the WIDTH.
  5296. WIDTH is the span in characters from MIN to MAX.
  5297. CHARACTERS is a string that will compose the bar, with shades of grey
  5298. from pure white to pure black. It defaults to a 10 characters string
  5299. of regular ascii characters."
  5300. (let* ((width (ceiling (or width 12)))
  5301. (characters (or characters " .:;c!lhVHW"))
  5302. (len (1- (length characters)))
  5303. (value (float (if (numberp value)
  5304. value (string-to-number value))))
  5305. (relative (/ (- value min) (- max min)))
  5306. (steps (round (* relative width len))))
  5307. (cond ((< steps 0) "too small")
  5308. ((> steps (* width len)) "too large")
  5309. (t (let* ((int-division (/ steps len))
  5310. (remainder (- steps (* int-division len))))
  5311. (concat (make-string int-division (elt characters len))
  5312. (string (elt characters remainder))))))))
  5313. ;;;###autoload
  5314. (defun orgtbl-ascii-plot (&optional ask)
  5315. "Draw an ASCII bar plot in a column.
  5316. With cursor in a column containing numerical values, this function
  5317. will draw a plot in a new column.
  5318. ASK, if given, is a numeric prefix to override the default 12
  5319. characters width of the plot. ASK may also be the `\\[universal-argument]' \
  5320. prefix,
  5321. which will prompt for the width."
  5322. (interactive "P")
  5323. (let ((col (org-table-current-column))
  5324. (min 1e999) ; 1e999 will be converted to infinity
  5325. (max -1e999) ; which is the desired result
  5326. (table (org-table-to-lisp))
  5327. (length
  5328. (cond ((consp ask)
  5329. (read-number "Length of column " 12))
  5330. ((numberp ask) ask)
  5331. (t 12))))
  5332. ;; Skip any hline a the top of table.
  5333. (while (eq (car table) 'hline) (setq table (cdr table)))
  5334. ;; Skip table header if any.
  5335. (dolist (x (or (cdr (memq 'hline table)) table))
  5336. (when (consp x)
  5337. (setq x (nth (1- col) x))
  5338. (when (string-match
  5339. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  5340. x)
  5341. (setq x (string-to-number x))
  5342. (when (> min x) (setq min x))
  5343. (when (< max x) (setq max x)))))
  5344. (org-table-insert-column)
  5345. (org-table-move-column-right)
  5346. (org-table-store-formulas
  5347. (cons
  5348. (cons
  5349. (concat "$" (number-to-string (1+ col)))
  5350. (format "'(%s $%s %s %s %s)"
  5351. "orgtbl-ascii-draw" col min max length))
  5352. (org-table-get-stored-formulas)))
  5353. (org-table-recalculate t)))
  5354. ;; Example of extension: unicode characters
  5355. ;; Here are two examples of different styles.
  5356. ;; Unicode block characters are used to give a smooth effect.
  5357. ;; See http://en.wikipedia.org/wiki/Block_Elements
  5358. ;; Use one of those drawing functions
  5359. ;; - orgtbl-ascii-draw (the default ascii)
  5360. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  5361. ;; - orgtbl-uc-draw-cont (smooth unicode)
  5362. ;; This is best viewed with the "DejaVu Sans Mono" font
  5363. ;; (use M-x set-frame-font).
  5364. (defun orgtbl-uc-draw-grid (value min max &optional width)
  5365. "Draw a bar in a table using block unicode characters.
  5366. It is a variant of orgtbl-ascii-draw with Unicode block
  5367. characters, for a smooth display. Bars appear as grids (to the
  5368. extent the font allows)."
  5369. ;; http://en.wikipedia.org/wiki/Block_Elements
  5370. ;; best viewed with the "DejaVu Sans Mono" font.
  5371. (orgtbl-ascii-draw value min max width
  5372. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  5373. (defun orgtbl-uc-draw-cont (value min max &optional width)
  5374. "Draw a bar in a table using block unicode characters.
  5375. It is a variant of orgtbl-ascii-draw with Unicode block
  5376. characters, for a smooth display. Bars are solid (to the extent
  5377. the font allows)."
  5378. (orgtbl-ascii-draw value min max width
  5379. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  5380. (defun org-table-get-remote-range (name-or-id form)
  5381. "Get a field value or a list of values in a range from table at ID.
  5382. NAME-OR-ID may be the name of a table in the current file as set
  5383. by a \"#+NAME:\" directive. The first table following this line
  5384. will then be used. Alternatively, it may be an ID referring to
  5385. any entry, also in a different file. In this case, the first
  5386. table in that entry will be referenced.
  5387. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  5388. \"@I$2..@II$2\". All the references must be absolute, not relative.
  5389. The return value is either a single string for a single field, or a
  5390. list of the fields in the rectangle."
  5391. (save-match-data
  5392. (let ((case-fold-search t) (id-loc nil)
  5393. ;; Protect a bunch of variables from being overwritten by
  5394. ;; the context of the remote table.
  5395. org-table-column-names org-table-column-name-regexp
  5396. org-table-local-parameters org-table-named-field-locations
  5397. org-table-current-line-types
  5398. org-table-current-begin-pos org-table-dlines
  5399. org-table-current-ncol
  5400. org-table-hlines
  5401. org-table-last-column-widths
  5402. org-table-last-alignment
  5403. buffer loc)
  5404. (setq form (org-table-convert-refs-to-rc form))
  5405. (org-with-wide-buffer
  5406. (goto-char (point-min))
  5407. (if (re-search-forward
  5408. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  5409. (regexp-quote name-or-id) "[ \t]*$")
  5410. nil t)
  5411. (setq buffer (current-buffer) loc (match-beginning 0))
  5412. (setq id-loc (org-id-find name-or-id 'marker))
  5413. (unless (and id-loc (markerp id-loc))
  5414. (user-error "Can't find remote table \"%s\"" name-or-id))
  5415. (setq buffer (marker-buffer id-loc)
  5416. loc (marker-position id-loc))
  5417. (move-marker id-loc nil))
  5418. (with-current-buffer buffer
  5419. (org-with-wide-buffer
  5420. (goto-char loc)
  5421. (forward-char 1)
  5422. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  5423. (not (match-beginning 1)))
  5424. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  5425. (org-table-analyze)
  5426. (setq form (org-table-formula-substitute-names
  5427. (org-table-formula-handle-first/last-rc form)))
  5428. (if (and (string-match org-table-range-regexp form)
  5429. (> (length (match-string 0 form)) 1))
  5430. (org-table-get-range
  5431. (match-string 0 form) org-table-current-begin-pos 1)
  5432. form)))))))
  5433. (defun org-table-remote-reference-indirection (form)
  5434. "Return formula with table remote references substituted by indirection.
  5435. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  5436. This indirection works only with the format @ROW$COLUMN. The
  5437. format \"B3\" is not supported because it can not be
  5438. distinguished from a plain table name or ID."
  5439. (let ((regexp
  5440. ;; Same as in `org-table-eval-formula'.
  5441. (concat "\\<remote([ \t]*\\("
  5442. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  5443. "[@$][^ \t,]+"
  5444. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
  5445. (replace-regexp-in-string
  5446. regexp
  5447. (lambda (m)
  5448. (save-match-data
  5449. (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
  5450. (org-table-get-range
  5451. (if (string-match-p "\\`\\$[0-9]+\\'" eq)
  5452. (concat "@0" eq)
  5453. eq)))))
  5454. form t t 1)))
  5455. (defmacro org-define-lookup-function (mode)
  5456. (let ((mode-str (symbol-name mode))
  5457. (first-p (eq mode 'first))
  5458. (all-p (eq mode 'all)))
  5459. (let ((plural-str (if all-p "s" "")))
  5460. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  5461. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  5462. If R-LIST is nil, return matching element%s of S-LIST.
  5463. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  5464. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  5465. This function is generated by a call to the macro `org-define-lookup-function'."
  5466. mode-str plural-str plural-str plural-str)
  5467. (let ,(let ((lvars '((p (or predicate 'equal))
  5468. (sl s-list)
  5469. (rl (or r-list s-list))
  5470. (ret nil))))
  5471. (if first-p (cons '(match-p nil) lvars) lvars))
  5472. (while ,(if first-p '(and (not match-p) sl) 'sl)
  5473. (when (funcall p val (car sl))
  5474. ,(when first-p '(setq match-p t))
  5475. (let ((rval (car rl)))
  5476. (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
  5477. (setq sl (cdr sl) rl (cdr rl)))
  5478. ret)))))
  5479. (org-define-lookup-function first)
  5480. (org-define-lookup-function last)
  5481. (org-define-lookup-function all)
  5482. (provide 'org-table)
  5483. ;; Local variables:
  5484. ;; generated-autoload-file: "org-loaddefs.el"
  5485. ;; End:
  5486. ;;; org-table.el ends here