org-table.el 184 KB

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