org-table.el 173 KB

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