org-table.el 175 KB

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