org-table.el 172 KB

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