org-table.el 206 KB

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