org-table.el 206 KB

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