org-table.el 176 KB

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