org-table.el 177 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682
  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.6
  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 formrpl bw fmt x ev orig c lispp literal duration)
  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 "T" fmt)
  2263. (setq duration t numbers t
  2264. fmt (replace-match "" t t fmt)))
  2265. (if (string-match "N" fmt)
  2266. (setq numbers t
  2267. fmt (replace-match "" t t fmt)))
  2268. (if (string-match "L" fmt)
  2269. (setq literal t
  2270. fmt (replace-match "" t t fmt)))
  2271. (if (string-match "E" fmt)
  2272. (setq keep-empty t
  2273. fmt (replace-match "" t t fmt)))
  2274. (while (string-match "[DRFS]" fmt)
  2275. (setq modes (org-set-calc-mode (match-string 0 fmt)))
  2276. (setq fmt (replace-match "" t t fmt)))
  2277. (unless (string-match "\\S-" fmt)
  2278. (setq fmt nil))))
  2279. (if (and (not suppress-const) org-table-formula-use-constants)
  2280. (setq formula (org-table-formula-substitute-names formula)))
  2281. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2282. (while (> ndown 0)
  2283. (setq fields
  2284. (mapcar (lambda (cell)
  2285. (let ((duration (org-table-time-string-to-seconds cell)))
  2286. (if duration (number-to-string duration) cell)))
  2287. (org-split-string
  2288. (org-no-properties
  2289. (buffer-substring (point-at-bol) (point-at-eol)))
  2290. " *| *")))
  2291. (if (eq numbers t)
  2292. (setq fields (mapcar
  2293. (lambda (x) (number-to-string (string-to-number x)))
  2294. fields)))
  2295. (setq ndown (1- ndown))
  2296. (setq form (copy-sequence formula)
  2297. lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
  2298. (if (and lispp literal) (setq lispp 'literal))
  2299. ;; Insert row and column number of formula result field
  2300. (while (string-match "[@$]#" form)
  2301. (setq form
  2302. (replace-match
  2303. (format "%d"
  2304. (save-match-data
  2305. (if (equal (substring form (match-beginning 0)
  2306. (1+ (match-beginning 0)))
  2307. "@")
  2308. (org-table-current-dline)
  2309. (org-table-current-column))))
  2310. t t form)))
  2311. ;; Check for old vertical references
  2312. (setq form (org-table-rewrite-old-row-references form))
  2313. ;; Insert remote references
  2314. (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2315. (setq form
  2316. (replace-match
  2317. (save-match-data
  2318. (org-table-make-reference
  2319. (org-table-get-remote-range
  2320. (match-string 1 form) (match-string 2 form))
  2321. keep-empty numbers lispp))
  2322. t t form)))
  2323. ;; Insert complex ranges
  2324. (while (and (string-match org-table-range-regexp form)
  2325. (> (length (match-string 0 form)) 1))
  2326. (setq formrpl
  2327. (save-match-data
  2328. (org-table-make-reference
  2329. (org-table-get-range (match-string 0 form) nil n0)
  2330. keep-empty numbers lispp)))
  2331. (if (not (save-match-data
  2332. (string-match (regexp-quote form) formrpl)))
  2333. (setq form (replace-match formrpl t t form))
  2334. (error "Spreadsheet error: invalid reference \"%s\"" form)))
  2335. ;; Insert simple ranges
  2336. (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
  2337. (setq form
  2338. (replace-match
  2339. (save-match-data
  2340. (org-table-make-reference
  2341. (org-sublist
  2342. fields (string-to-number (match-string 1 form))
  2343. (string-to-number (match-string 2 form)))
  2344. keep-empty numbers lispp))
  2345. t t form)))
  2346. (setq form0 form)
  2347. ;; Insert the references to fields in same row
  2348. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2349. (setq n (+ (string-to-number (match-string 1 form))
  2350. (if (match-end 2) n0 0))
  2351. x (nth (1- (if (= n 0) n0 (max n 1))) fields))
  2352. (unless x (error "Invalid field specifier \"%s\""
  2353. (match-string 0 form)))
  2354. (setq form (replace-match
  2355. (save-match-data
  2356. (org-table-make-reference x nil numbers lispp))
  2357. t t form)))
  2358. (if lispp
  2359. (setq ev (condition-case nil
  2360. (eval (eval (read form)))
  2361. (error "#ERROR"))
  2362. ev (if (numberp ev) (number-to-string ev) ev)
  2363. ev (if duration (org-table-time-seconds-to-string
  2364. (string-to-number ev)) ev))
  2365. (or (fboundp 'calc-eval)
  2366. (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
  2367. (setq ev (calc-eval (cons form modes)
  2368. (if numbers 'num))
  2369. ev (if duration (org-table-time-seconds-to-string
  2370. (string-to-number ev)) ev)))
  2371. (when org-table-formula-debug
  2372. (with-output-to-temp-buffer "*Substitution History*"
  2373. (princ (format "Substitution history of formula
  2374. Orig: %s
  2375. $xyz-> %s
  2376. @r$c-> %s
  2377. $1-> %s\n" orig formula form0 form))
  2378. (if (listp ev)
  2379. (princ (format " %s^\nError: %s"
  2380. (make-string (car ev) ?\-) (nth 1 ev)))
  2381. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2382. ev (or fmt "NONE")
  2383. (if fmt (format fmt (string-to-number ev)) ev)))))
  2384. (setq bw (get-buffer-window "*Substitution History*"))
  2385. (org-fit-window-to-buffer bw)
  2386. (unless (and (org-called-interactively-p 'any) (not ndown))
  2387. (unless (let (inhibit-redisplay)
  2388. (y-or-n-p "Debugging Formula. Continue to next? "))
  2389. (org-table-align)
  2390. (error "Abort"))
  2391. (delete-window bw)
  2392. (message "")))
  2393. (if (listp ev) (setq fmt nil ev "#ERROR"))
  2394. (org-table-justify-field-maybe
  2395. (if fmt (format fmt (string-to-number ev)) ev))
  2396. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2397. (call-interactively 'org-return)
  2398. (setq ndown 0)))
  2399. (and down (org-table-maybe-recalculate-line))
  2400. (or suppress-align (and org-table-may-need-update
  2401. (org-table-align))))))
  2402. (defun org-table-put-field-property (prop value)
  2403. (save-excursion
  2404. (put-text-property (progn (skip-chars-backward "^|") (point))
  2405. (progn (skip-chars-forward "^|") (point))
  2406. prop value)))
  2407. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2408. "Get a calc vector from a column, according to descriptor DESC.
  2409. Optional arguments TBEG and COL can give the beginning of the table and
  2410. the current column, to avoid unnecessary parsing.
  2411. HIGHLIGHT means just highlight the range.
  2412. When CORNERS-ONLY is set, only return the corners of the range as
  2413. a list (line1 column1 line2 column2) where line1 and line2 are line numbers
  2414. in the buffer and column1 and column2 are table column numbers."
  2415. (if (not (equal (string-to-char desc) ?@))
  2416. (setq desc (concat "@" desc)))
  2417. (save-excursion
  2418. (or tbeg (setq tbeg (org-table-begin)))
  2419. (or col (setq col (org-table-current-column)))
  2420. (let ((thisline (org-current-line))
  2421. beg end c1 c2 r1 r2 rangep tmp)
  2422. (unless (string-match org-table-range-regexp desc)
  2423. (error "Invalid table range specifier `%s'" desc))
  2424. (setq rangep (match-end 3)
  2425. r1 (and (match-end 1) (match-string 1 desc))
  2426. r2 (and (match-end 4) (match-string 4 desc))
  2427. c1 (and (match-end 2) (substring (match-string 2 desc) 1))
  2428. c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
  2429. (and c1 (setq c1 (+ (string-to-number c1)
  2430. (if (memq (string-to-char c1) '(?- ?+)) col 0))))
  2431. (and c2 (setq c2 (+ (string-to-number c2)
  2432. (if (memq (string-to-char c2) '(?- ?+)) col 0))))
  2433. (if (equal r1 "") (setq r1 nil))
  2434. (if (equal r2 "") (setq r2 nil))
  2435. (if r1 (setq r1 (org-table-get-descriptor-line r1)))
  2436. (if r2 (setq r2 (org-table-get-descriptor-line r2)))
  2437. ; (setq r2 (or r2 r1) c2 (or c2 c1))
  2438. (if (not r1) (setq r1 thisline))
  2439. (if (not r2) (setq r2 thisline))
  2440. (if (not c1) (setq c1 col))
  2441. (if (not c2) (setq c2 col))
  2442. (if (and (not corners-only)
  2443. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2444. ;; just one field
  2445. (progn
  2446. (org-goto-line r1)
  2447. (while (not (looking-at org-table-dataline-regexp))
  2448. (beginning-of-line 2))
  2449. (prog1 (org-trim (org-table-get-field c1))
  2450. (if highlight (org-table-highlight-rectangle (point) (point)))))
  2451. ;; A range, return a vector
  2452. ;; First sort the numbers to get a regular ractangle
  2453. (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
  2454. (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
  2455. (if corners-only
  2456. ;; Only return the corners of the range
  2457. (list r1 c1 r2 c2)
  2458. ;; Copy the range values into a list
  2459. (org-goto-line r1)
  2460. (while (not (looking-at org-table-dataline-regexp))
  2461. (beginning-of-line 2))
  2462. (org-table-goto-column c1)
  2463. (setq beg (point))
  2464. (org-goto-line r2)
  2465. (while (not (looking-at org-table-dataline-regexp))
  2466. (beginning-of-line 0))
  2467. (org-table-goto-column c2)
  2468. (setq end (point))
  2469. (if highlight
  2470. (org-table-highlight-rectangle
  2471. beg (progn (skip-chars-forward "^|\n") (point))))
  2472. ;; return string representation of calc vector
  2473. (mapcar 'org-trim
  2474. (apply 'append (org-table-copy-region beg end))))))))
  2475. (defun org-table-get-descriptor-line (desc &optional cline bline table)
  2476. "Analyze descriptor DESC and retrieve the corresponding line number.
  2477. The cursor is currently in line CLINE, the table begins in line BLINE,
  2478. and TABLE is a vector with line types."
  2479. (if (string-match "^[0-9]+$" desc)
  2480. (aref org-table-dlines (string-to-number desc))
  2481. (setq cline (or cline (org-current-line))
  2482. bline (or bline org-table-current-begin-line)
  2483. table (or table org-table-current-line-types))
  2484. (if (or
  2485. (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
  2486. ;; 1 2 3 4 5 6
  2487. (and (not (match-end 3)) (not (match-end 6)))
  2488. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2489. (error "Invalid row descriptor `%s'" desc))
  2490. (let* ((hdir (and (match-end 2) (match-string 2 desc)))
  2491. (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
  2492. (odir (and (match-end 5) (match-string 5 desc)))
  2493. (on (if (match-end 6) (string-to-number (match-string 6 desc))))
  2494. (i (- cline bline))
  2495. (rel (and (match-end 6)
  2496. (or (and (match-end 1) (not (match-end 3)))
  2497. (match-end 5)))))
  2498. (if (and hn (not hdir))
  2499. (progn
  2500. (setq i 0 hdir "+")
  2501. (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
  2502. (if (and (not hn) on (not odir))
  2503. (error "Should never happen");;(aref org-table-dlines on)
  2504. (if (and hn (> hn 0))
  2505. (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
  2506. nil hn cline desc)))
  2507. (if on
  2508. (setq i (org-table-find-row-type table i 'dline (equal odir "-")
  2509. rel on cline desc)))
  2510. (+ bline i)))))
  2511. (defun org-table-find-row-type (table i type backwards relative n cline desc)
  2512. "FIXME: Needs more documentation."
  2513. (let ((l (length table)))
  2514. (while (> n 0)
  2515. (while (and (setq i (+ i (if backwards -1 1)))
  2516. (>= i 0) (< i l)
  2517. (not (eq (aref table i) type))
  2518. (if (and relative (eq (aref table i) 'hline))
  2519. (cond
  2520. ((eq org-table-relative-ref-may-cross-hline t) t)
  2521. ((eq org-table-relative-ref-may-cross-hline 'error)
  2522. (error "Row descriptor %s used in line %d crosses hline" desc cline))
  2523. (t (setq i (- i (if backwards -1 1))
  2524. n 1)
  2525. nil))
  2526. t)))
  2527. (setq n (1- n)))
  2528. (if (or (< i 0) (>= i l))
  2529. (error "Row descriptor %s used in line %d leads outside table"
  2530. desc cline)
  2531. i)))
  2532. (defun org-table-rewrite-old-row-references (s)
  2533. (if (string-match "&[-+0-9I]" s)
  2534. (error "Formula contains old &row reference, please rewrite using @-syntax")
  2535. s))
  2536. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2537. "Convert list ELEMENTS to something appropriate to insert into formula.
  2538. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2539. NUMBERS indicates that everything should be converted to numbers.
  2540. LISPP means to return something appropriate for a Lisp list."
  2541. (if (stringp elements) ; just a single val
  2542. (if lispp
  2543. (if (eq lispp 'literal)
  2544. elements
  2545. (prin1-to-string (if numbers (string-to-number elements) elements)))
  2546. (if (equal elements "") (setq elements "0"))
  2547. (if numbers (setq elements (number-to-string (string-to-number elements))))
  2548. (concat "(" elements ")"))
  2549. (unless keep-empty
  2550. (setq elements
  2551. (delq nil
  2552. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2553. elements))))
  2554. (setq elements (or elements '("0")))
  2555. (if lispp
  2556. (mapconcat
  2557. (lambda (x)
  2558. (if (eq lispp 'literal)
  2559. x
  2560. (prin1-to-string (if numbers (string-to-number x) x))))
  2561. elements " ")
  2562. (concat "[" (mapconcat
  2563. (lambda (x)
  2564. (if numbers (number-to-string (string-to-number x)) x))
  2565. elements
  2566. ",") "]"))))
  2567. (defun org-table-recalculate (&optional all noalign)
  2568. "Recalculate the current table line by applying all stored formulas.
  2569. With prefix arg ALL, do this for all lines in the table.
  2570. With the prefix argument ALL is `(16)' \
  2571. \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
  2572. it is the symbol `iterate', recompute the table until it no longer changes.
  2573. If NOALIGN is not nil, do not re-align the table after the computations
  2574. are done. This is typically used internally to save time, if it is
  2575. known that the table will be realigned a little later anyway."
  2576. (interactive "P")
  2577. (or (memq this-command org-recalc-commands)
  2578. (setq org-recalc-commands (cons this-command org-recalc-commands)))
  2579. (unless (org-at-table-p) (error "Not at a table"))
  2580. (if (or (eq all 'iterate) (equal all '(16)))
  2581. (org-table-iterate)
  2582. (org-table-get-specials)
  2583. (let* ((eqlist (sort (org-table-get-stored-formulas)
  2584. (lambda (a b) (string< (car a) (car b)))))
  2585. (eqlist1 (copy-sequence eqlist))
  2586. (inhibit-redisplay (not debug-on-error))
  2587. (line-re org-table-dataline-regexp)
  2588. (thisline (org-current-line))
  2589. (thiscol (org-table-current-column))
  2590. seen-fields lhs1
  2591. beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
  2592. ;; Insert constants in all formulas
  2593. (setq eqlist
  2594. (mapcar (lambda (x)
  2595. (when (string-match "\\`$[<>]" (car x))
  2596. (setq lhs1 (car x))
  2597. (setq x (cons (substring
  2598. (org-table-formula-handle-first/last-rc
  2599. (car x)) 1)
  2600. (cdr x)))
  2601. (if (assoc (car x) eqlist1)
  2602. (error "\"%s=\" formula tries to overwrite existing formula for column %s"
  2603. lhs1 (car x))))
  2604. (cons
  2605. (org-table-formula-handle-first/last-rc (car x))
  2606. (org-table-formula-substitute-names
  2607. (org-table-formula-handle-first/last-rc (cdr x)))))
  2608. eqlist))
  2609. ;; Split the equation list
  2610. (while (setq eq (pop eqlist))
  2611. (if (<= (string-to-char (car eq)) ?9)
  2612. (push eq eqlnum)
  2613. (push eq eqlname)))
  2614. (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
  2615. ;; Expand ranges in lhs of formulas
  2616. (setq eqlname (org-table-expand-lhs-ranges eqlname))
  2617. ;; Get the correct line range to process
  2618. (if all
  2619. (progn
  2620. (setq end (move-marker (make-marker) (1+ (org-table-end))))
  2621. (goto-char (setq beg (org-table-begin)))
  2622. (if (re-search-forward org-table-calculate-mark-regexp end t)
  2623. ;; This is a table with marked lines, compute selected lines
  2624. (setq line-re org-table-recalculate-regexp)
  2625. ;; Move forward to the first non-header line
  2626. (if (and (re-search-forward org-table-dataline-regexp end t)
  2627. (re-search-forward org-table-hline-regexp end t)
  2628. (re-search-forward org-table-dataline-regexp end t))
  2629. (setq beg (match-beginning 0))
  2630. nil))) ;; just leave beg where it is
  2631. (setq beg (point-at-bol)
  2632. end (move-marker (make-marker) (1+ (point-at-eol)))))
  2633. (goto-char beg)
  2634. (and all (message "Re-applying formulas to full table..."))
  2635. ;; First find the named fields, and mark them untouchable.
  2636. ;; Also check if several field/range formulas try to set the same field.
  2637. (remove-text-properties beg end '(org-untouchable t))
  2638. (while (setq eq (pop eqlname))
  2639. (setq name (car eq)
  2640. a (assoc name org-table-named-field-locations))
  2641. (setq name1 name)
  2642. (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
  2643. (nth 2 a))))
  2644. (when (member name1 seen-fields)
  2645. (error "Several field/range formulas try to set %s" name1))
  2646. (push name1 seen-fields)
  2647. (and (not a)
  2648. (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
  2649. (setq a (list name
  2650. (condition-case nil
  2651. (aref org-table-dlines
  2652. (string-to-number (match-string 1 name)))
  2653. (error (error "Invalid row number in %s"
  2654. name)))
  2655. (string-to-number (match-string 2 name)))))
  2656. (when (and a (or all (equal (nth 1 a) thisline)))
  2657. (message "Re-applying formula to field: %s" name)
  2658. (org-goto-line (nth 1 a))
  2659. (org-table-goto-column (nth 2 a))
  2660. (push (append a (list (cdr eq))) eqlname1)
  2661. (org-table-put-field-property :org-untouchable t)))
  2662. (setq eqlname1 (nreverse eqlname1))
  2663. ;; Now evaluate the column formulas, but skip fields covered by
  2664. ;; field formulas
  2665. (goto-char beg)
  2666. (while (re-search-forward line-re end t)
  2667. (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
  2668. ;; Unprotected line, recalculate
  2669. (and all (message "Re-applying formulas to full table...(line %d)"
  2670. (setq cnt (1+ cnt))))
  2671. (setq org-last-recalc-line (org-current-line))
  2672. (setq eql eqlnum)
  2673. (while (setq entry (pop eql))
  2674. (org-goto-line org-last-recalc-line)
  2675. (org-table-goto-column (string-to-number (car entry)) nil 'force)
  2676. (unless (get-text-property (point) :org-untouchable)
  2677. (org-table-eval-formula nil (cdr entry)
  2678. 'noalign 'nocst 'nostore 'noanalysis)))))
  2679. ;; Now evaluate the field formulas
  2680. (while (setq eq (pop eqlname1))
  2681. (message "Re-applying formula to field: %s" (car eq))
  2682. (org-goto-line (nth 1 eq))
  2683. (org-table-goto-column (nth 2 eq))
  2684. (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
  2685. 'nostore 'noanalysis))
  2686. (org-goto-line thisline)
  2687. (org-table-goto-column thiscol)
  2688. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  2689. (or noalign (and org-table-may-need-update (org-table-align))
  2690. (and all (message "Re-applying formulas to %d lines...done" cnt)))
  2691. ;; back to initial position
  2692. (message "Re-applying formulas...done")
  2693. (org-goto-line thisline)
  2694. (org-table-goto-column thiscol)
  2695. (or noalign (and org-table-may-need-update (org-table-align))
  2696. (and all (message "Re-applying formulas...done"))))))
  2697. (defun org-table-iterate (&optional arg)
  2698. "Recalculate the table until it does not change anymore.
  2699. The maximun number of iterations is 10, but you can chose a different value
  2700. with the prefix ARG."
  2701. (interactive "P")
  2702. (let ((imax (if arg (prefix-numeric-value arg) 10))
  2703. (i 0)
  2704. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  2705. thistbl)
  2706. (catch 'exit
  2707. (while (< i imax)
  2708. (setq i (1+ i))
  2709. (org-table-recalculate 'all)
  2710. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  2711. (if (not (string= lasttbl thistbl))
  2712. (setq lasttbl thistbl)
  2713. (if (> i 1)
  2714. (message "Convergence after %d iterations" i)
  2715. (message "Table was already stable"))
  2716. (throw 'exit t)))
  2717. (error "No convergence after %d iterations" i))))
  2718. (defun org-table-recalculate-buffer-tables ()
  2719. "Recalculate all tables in the current buffer."
  2720. (interactive)
  2721. (save-excursion
  2722. (save-restriction
  2723. (widen)
  2724. (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
  2725. (defun org-table-iterate-buffer-tables ()
  2726. "Iterate all tables in the buffer, to converge inter-table dependencies."
  2727. (interactive)
  2728. (let* ((imax 10)
  2729. (checksum (md5 (buffer-string)))
  2730. c1
  2731. (i imax))
  2732. (save-excursion
  2733. (save-restriction
  2734. (widen)
  2735. (catch 'exit
  2736. (while (> i 0)
  2737. (setq i (1- i))
  2738. (org-table-map-tables (lambda () (org-table-recalculate t)) t)
  2739. (if (equal checksum (setq c1 (md5 (buffer-string))))
  2740. (progn
  2741. (message "Convergence after %d iterations" (- imax i))
  2742. (throw 'exit t))
  2743. (setq checksum c1)))
  2744. (error "No convergence after %d iterations" imax))))))
  2745. (defun org-table-expand-lhs-ranges (equations)
  2746. "Expand list of formulas.
  2747. If some of the RHS in the formulas are ranges or a row reference, expand
  2748. them to individual field equations for each field."
  2749. (let (e res lhs rhs range r1 r2 c1 c2)
  2750. (while (setq e (pop equations))
  2751. (setq lhs (car e) rhs (cdr e))
  2752. (cond
  2753. ((string-match "^@-?[-+I0-9]+\\$-?[0-9]+$" lhs)
  2754. ;; This just refers to one fixed field
  2755. (push e res))
  2756. ((string-match "^[a-zA-Z][a-zA-Z0-9]*$" lhs)
  2757. ;; This just refers to one fixed named field
  2758. (push e res))
  2759. ((string-match "^@[0-9]+$" lhs)
  2760. (loop for ic from 1 to org-table-current-ncol do
  2761. (push (cons (format "%s$%d" lhs ic) rhs) res)
  2762. (put-text-property 0 (length (caar res))
  2763. :orig-eqn e (caar res))))
  2764. (t
  2765. (setq range (org-table-get-range lhs org-table-current-begin-pos
  2766. 1 nil 'corners))
  2767. (setq r1 (nth 0 range) c1 (nth 1 range)
  2768. r2 (nth 2 range) c2 (nth 3 range))
  2769. (setq r1 (org-table-line-to-dline r1))
  2770. (setq r2 (org-table-line-to-dline r2 'above))
  2771. (loop for ir from r1 to r2 do
  2772. (loop for ic from c1 to c2 do
  2773. (push (cons (format "@%d$%d" ir ic) rhs) res)
  2774. (put-text-property 0 (length (caar res))
  2775. :orig-eqn e (caar res)))))))
  2776. (nreverse res)))
  2777. (defun org-table-formula-handle-first/last-rc (s)
  2778. "Replace @<, @>, $<, $> with first/last row/column of the table.
  2779. So @< and $< will always be replaced with @1 and $1, respectively.
  2780. The advantage of these special markers are that structure editing of
  2781. the table will not change them, while @1 and $1 will be modified
  2782. when a line/row is swaped out of that privileged position. So for
  2783. formulas that use a range of rows or columns, it may often be better
  2784. to anchor the formula with \"I\" row markers, or to offset from the
  2785. borders of the table using the @< @> $< $> makers."
  2786. (let (n nmax len char)
  2787. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)" s)
  2788. (setq nmax (if (equal (match-string 1 s) "@")
  2789. (1- (length org-table-dlines))
  2790. org-table-current-ncol)
  2791. len (- (match-end 2) (match-beginning 2))
  2792. char (string-to-char (match-string 2 s))
  2793. n (if (= char ?<)
  2794. len
  2795. (- nmax len -1)))
  2796. (if (or (< n 1) (> n nmax))
  2797. (error "Reference \"%s\" in expression \"%s\" points outside table"
  2798. (match-string 0 s) s))
  2799. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s))))
  2800. s)
  2801. (defun org-table-formula-substitute-names (f)
  2802. "Replace $const with values in string F."
  2803. (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
  2804. ;; First, check for column names
  2805. (while (setq start (string-match org-table-column-name-regexp f start))
  2806. (setq start (1+ start))
  2807. (setq a (assoc (match-string 1 f) org-table-column-names))
  2808. (setq f (replace-match (concat "$" (cdr a)) t t f)))
  2809. ;; Parameters and constants
  2810. (setq start 0)
  2811. (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)" f start))
  2812. (if (match-end 2)
  2813. (setq start (match-end 2))
  2814. (setq start (1+ start))
  2815. (if (setq a (save-match-data
  2816. (org-table-get-constant (match-string 1 f))))
  2817. (setq f (replace-match
  2818. (concat (if pp "(") a (if pp ")")) t t f)))))
  2819. (if org-table-formula-debug
  2820. (put-text-property 0 (length f) :orig-formula f1 f))
  2821. f))
  2822. (defun org-table-get-constant (const)
  2823. "Find the value for a parameter or constant in a formula.
  2824. Parameters get priority."
  2825. (or (cdr (assoc const org-table-local-parameters))
  2826. (cdr (assoc const org-table-formula-constants-local))
  2827. (cdr (assoc const org-table-formula-constants))
  2828. (and (fboundp 'constants-get) (constants-get const))
  2829. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  2830. (org-entry-get nil (substring const 5) 'inherit))
  2831. "#UNDEFINED_NAME"))
  2832. (defvar org-table-fedit-map
  2833. (let ((map (make-sparse-keymap)))
  2834. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  2835. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  2836. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  2837. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  2838. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  2839. (org-defkey map "\C-c?" 'org-table-show-reference)
  2840. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  2841. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  2842. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  2843. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  2844. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  2845. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  2846. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  2847. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  2848. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  2849. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  2850. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  2851. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  2852. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  2853. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  2854. map))
  2855. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
  2856. '("Edit-Formulas"
  2857. ["Finish and Install" org-table-fedit-finish t]
  2858. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  2859. ["Abort" org-table-fedit-abort t]
  2860. "--"
  2861. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  2862. ["Complete Lisp Symbol" lisp-complete-symbol t]
  2863. "--"
  2864. "Shift Reference at Point"
  2865. ["Up" org-table-fedit-ref-up t]
  2866. ["Down" org-table-fedit-ref-down t]
  2867. ["Left" org-table-fedit-ref-left t]
  2868. ["Right" org-table-fedit-ref-right t]
  2869. "-"
  2870. "Change Test Row for Column Formulas"
  2871. ["Up" org-table-fedit-line-up t]
  2872. ["Down" org-table-fedit-line-down t]
  2873. "--"
  2874. ["Scroll Table Window" org-table-fedit-scroll t]
  2875. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  2876. ["Show Table Grid" org-table-fedit-toggle-coordinates
  2877. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  2878. org-table-overlay-coordinates)]
  2879. "--"
  2880. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  2881. :style toggle :selected org-table-buffer-is-an]))
  2882. (defvar org-pos)
  2883. (defun org-table-edit-formulas ()
  2884. "Edit the formulas of the current table in a separate buffer."
  2885. (interactive)
  2886. (when (save-excursion (beginning-of-line 1) (looking-at "[ \t]*#\\+TBLFM"))
  2887. (beginning-of-line 0))
  2888. (unless (org-at-table-p) (error "Not at a table"))
  2889. (org-table-get-specials)
  2890. (let ((key (org-table-current-field-formula 'key 'noerror))
  2891. (eql (sort (org-table-get-stored-formulas 'noerror)
  2892. 'org-table-formula-less-p))
  2893. (pos (move-marker (make-marker) (point)))
  2894. (startline 1)
  2895. (wc (current-window-configuration))
  2896. (sel-win (selected-window))
  2897. (titles '((column . "# Column Formulas\n")
  2898. (field . "# Field and Range Formulas\n")
  2899. (named . "# Named Field Formulas\n")))
  2900. entry s type title)
  2901. (org-switch-to-buffer-other-window "*Edit Formulas*")
  2902. (erase-buffer)
  2903. ;; Keep global-font-lock-mode from turning on font-lock-mode
  2904. (let ((font-lock-global-modes '(not fundamental-mode)))
  2905. (fundamental-mode))
  2906. (org-set-local 'font-lock-global-modes (list 'not major-mode))
  2907. (org-set-local 'org-pos pos)
  2908. (org-set-local 'org-window-configuration wc)
  2909. (org-set-local 'org-selected-window sel-win)
  2910. (use-local-map org-table-fedit-map)
  2911. (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
  2912. (easy-menu-add org-table-fedit-menu)
  2913. (setq startline (org-current-line))
  2914. (while (setq entry (pop eql))
  2915. (setq type (cond
  2916. ((string-match "\\`$[<>]" (car entry)) 'column)
  2917. ((equal (string-to-char (car entry)) ?@) 'field)
  2918. ((string-match "^[0-9]" (car entry)) 'column)
  2919. (t 'named)))
  2920. (when (setq title (assq type titles))
  2921. (or (bobp) (insert "\n"))
  2922. (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
  2923. (setq titles (remove title titles)))
  2924. (if (equal key (car entry)) (setq startline (org-current-line)))
  2925. (setq s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
  2926. (car entry) " = " (cdr entry) "\n"))
  2927. (remove-text-properties 0 (length s) '(face nil) s)
  2928. (insert s))
  2929. (if (eq org-table-use-standard-references t)
  2930. (org-table-fedit-toggle-ref-type))
  2931. (org-goto-line startline)
  2932. (message "Edit formulas, finish with `C-c C-c' or `C-c ' '. See menu for more commands.")))
  2933. (defun org-table-fedit-post-command ()
  2934. (when (not (memq this-command '(lisp-complete-symbol)))
  2935. (let ((win (selected-window)))
  2936. (save-excursion
  2937. (condition-case nil
  2938. (org-table-show-reference)
  2939. (error nil))
  2940. (select-window win)))))
  2941. (defun org-table-formula-to-user (s)
  2942. "Convert a formula from internal to user representation."
  2943. (if (eq org-table-use-standard-references t)
  2944. (org-table-convert-refs-to-an s)
  2945. s))
  2946. (defun org-table-formula-from-user (s)
  2947. "Convert a formula from user to internal representation."
  2948. (if org-table-use-standard-references
  2949. (org-table-convert-refs-to-rc s)
  2950. s))
  2951. (defun org-table-convert-refs-to-rc (s)
  2952. "Convert spreadsheet references from A7 to @7$28.
  2953. Works for single references, but also for entire formulas and even the
  2954. full TBLFM line."
  2955. (let ((start 0))
  2956. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^)]*)\\)" s start)
  2957. (cond
  2958. ((match-end 3)
  2959. ;; format match, just advance
  2960. (setq start (match-end 0)))
  2961. ((and (> (match-beginning 0) 0)
  2962. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  2963. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  2964. ;; 3.e5 or something like this.
  2965. (setq start (match-end 0)))
  2966. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  2967. ;; (member (match-string 1 s)
  2968. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  2969. )
  2970. ;; function name, just advance
  2971. (setq start (match-end 0)))
  2972. (t
  2973. (setq start (match-beginning 0)
  2974. s (replace-match
  2975. (if (equal (match-string 2 s) "&")
  2976. (format "$%d" (org-letters-to-number (match-string 1 s)))
  2977. (format "@%d$%d"
  2978. (string-to-number (match-string 2 s))
  2979. (org-letters-to-number (match-string 1 s))))
  2980. t t s)))))
  2981. s))
  2982. (defun org-table-convert-refs-to-an (s)
  2983. "Convert spreadsheet references from to @7$28 to AB7.
  2984. Works for single references, but also for entire formulas and even the
  2985. full TBLFM line."
  2986. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  2987. (setq s (replace-match
  2988. (format "%s%d"
  2989. (org-number-to-letters
  2990. (string-to-number (match-string 2 s)))
  2991. (string-to-number (match-string 1 s)))
  2992. t t s)))
  2993. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  2994. (setq s (replace-match (concat "\\1"
  2995. (org-number-to-letters
  2996. (string-to-number (match-string 2 s))) "&")
  2997. t nil s)))
  2998. s)
  2999. (defun org-letters-to-number (s)
  3000. "Convert a base 26 number represented by letters into an integer.
  3001. For example: AB -> 28."
  3002. (let ((n 0))
  3003. (setq s (upcase s))
  3004. (while (> (length s) 0)
  3005. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3006. s (substring s 1)))
  3007. n))
  3008. (defun org-number-to-letters (n)
  3009. "Convert an integer into a base 26 number represented by letters.
  3010. For example: 28 -> AB."
  3011. (let ((s ""))
  3012. (while (> n 0)
  3013. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3014. n (/ (1- n) 26)))
  3015. s))
  3016. (defun org-table-time-string-to-seconds (s)
  3017. "Convert a time string into numerical duration in seconds.
  3018. S must be a string matching either -?HH:MM:SS or -?HH:MM."
  3019. (cond
  3020. ((and (stringp s)
  3021. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3022. (let ((minus (< 0 (length (match-string 1 s))))
  3023. (hour (string-to-number (match-string 2 s)))
  3024. (min (string-to-number (match-string 3 s)))
  3025. (sec (string-to-number (match-string 4 s))))
  3026. (if minus
  3027. (- (+ (* hour 3600) (* min 60) sec))
  3028. (+ (* hour 3600) (* min 60) sec))))
  3029. ((and (stringp s)
  3030. (not (string-match org-ts-regexp-both s))
  3031. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3032. (let ((minus (< 0 (length (match-string 1 s))))
  3033. (hour (string-to-number (match-string 2 s)))
  3034. (min (string-to-number (match-string 3 s))))
  3035. (if minus
  3036. (- (+ (* hour 3600) (* min 60)))
  3037. (+ (* hour 3600) (* min 60)))))))
  3038. (defun org-table-time-seconds-to-string (secs)
  3039. "Convert a number of seconds to a time string."
  3040. (org-format-seconds "%.2h:%.2m:%.2s" secs))
  3041. (defun org-table-fedit-convert-buffer (function)
  3042. "Convert all references in this buffer, using FUNCTION."
  3043. (let ((line (org-current-line)))
  3044. (goto-char (point-min))
  3045. (while (not (eobp))
  3046. (insert (funcall function (buffer-substring (point) (point-at-eol))))
  3047. (delete-region (point) (point-at-eol))
  3048. (or (eobp) (forward-char 1)))
  3049. (org-goto-line line)))
  3050. (defun org-table-fedit-toggle-ref-type ()
  3051. "Convert all references in the buffer from B3 to @3$2 and back."
  3052. (interactive)
  3053. (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
  3054. (org-table-fedit-convert-buffer
  3055. (if org-table-buffer-is-an
  3056. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3057. (message "Reference type switched to %s"
  3058. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3059. (defun org-table-fedit-ref-up ()
  3060. "Shift the reference at point one row/hline up."
  3061. (interactive)
  3062. (org-table-fedit-shift-reference 'up))
  3063. (defun org-table-fedit-ref-down ()
  3064. "Shift the reference at point one row/hline down."
  3065. (interactive)
  3066. (org-table-fedit-shift-reference 'down))
  3067. (defun org-table-fedit-ref-left ()
  3068. "Shift the reference at point one field to the left."
  3069. (interactive)
  3070. (org-table-fedit-shift-reference 'left))
  3071. (defun org-table-fedit-ref-right ()
  3072. "Shift the reference at point one field to the right."
  3073. (interactive)
  3074. (org-table-fedit-shift-reference 'right))
  3075. (defun org-table-fedit-shift-reference (dir)
  3076. (cond
  3077. ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
  3078. (if (memq dir '(left right))
  3079. (org-rematch-and-replace 1 (eq dir 'left))
  3080. (error "Cannot shift reference in this direction")))
  3081. ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3082. ;; A B3-like reference
  3083. (if (memq dir '(up down))
  3084. (org-rematch-and-replace 2 (eq dir 'up))
  3085. (org-rematch-and-replace 1 (eq dir 'left))))
  3086. ((org-at-regexp-p
  3087. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3088. ;; An internal reference
  3089. (if (memq dir '(up down))
  3090. (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3091. (org-rematch-and-replace 5 (eq dir 'left))))))
  3092. (defun org-rematch-and-replace (n &optional decr hline)
  3093. "Re-match the group N, and replace it with the shifted reference."
  3094. (or (match-end n) (error "Cannot shift reference in this direction"))
  3095. (goto-char (match-beginning n))
  3096. (and (looking-at (regexp-quote (match-string n)))
  3097. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  3098. t t)))
  3099. (defun org-table-shift-refpart (ref &optional decr hline)
  3100. "Shift a reference part REF.
  3101. If DECR is set, decrease the references row/column, else increase.
  3102. If HLINE is set, this may be a hline reference, it certainly is not
  3103. a translation reference."
  3104. (save-match-data
  3105. (let* ((sign (string-match "^[-+]" ref)) n)
  3106. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  3107. (cond
  3108. ((and hline (string-match "^I+" ref))
  3109. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  3110. (setq n (+ n (if decr -1 1)))
  3111. (if (= n 0) (setq n (+ n (if decr -1 1))))
  3112. (if sign
  3113. (setq sign (if (< n 0) "-" "+") n (abs n))
  3114. (setq n (max 1 n)))
  3115. (concat sign (make-string n ?I)))
  3116. ((string-match "^[0-9]+" ref)
  3117. (setq n (string-to-number (concat sign ref)))
  3118. (setq n (+ n (if decr -1 1)))
  3119. (if sign
  3120. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  3121. (number-to-string (max 1 n))))
  3122. ((string-match "^[a-zA-Z]+" ref)
  3123. (org-number-to-letters
  3124. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  3125. (t (error "Cannot shift reference"))))))
  3126. (defun org-table-fedit-toggle-coordinates ()
  3127. "Toggle the display of coordinates in the referenced table."
  3128. (interactive)
  3129. (let ((pos (marker-position org-pos)))
  3130. (with-current-buffer (marker-buffer org-pos)
  3131. (save-excursion
  3132. (goto-char pos)
  3133. (org-table-toggle-coordinate-overlays)))))
  3134. (defun org-table-fedit-finish (&optional arg)
  3135. "Parse the buffer for formula definitions and install them.
  3136. With prefix ARG, apply the new formulas to the table."
  3137. (interactive "P")
  3138. (org-table-remove-rectangle-highlight)
  3139. (if org-table-use-standard-references
  3140. (progn
  3141. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  3142. (setq org-table-buffer-is-an nil)))
  3143. (let ((pos org-pos) (sel-win org-selected-window) eql var form)
  3144. (goto-char (point-min))
  3145. (while (re-search-forward
  3146. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  3147. nil t)
  3148. (setq var (if (match-end 2) (match-string 2) (match-string 1))
  3149. form (match-string 3))
  3150. (setq form (org-trim form))
  3151. (when (not (equal form ""))
  3152. (while (string-match "[ \t]*\n[ \t]*" form)
  3153. (setq form (replace-match " " t t form)))
  3154. (when (assoc var eql)
  3155. (error "Double formulas for %s" var))
  3156. (push (cons var form) eql)))
  3157. (setq org-pos nil)
  3158. (set-window-configuration org-window-configuration)
  3159. (select-window sel-win)
  3160. (goto-char pos)
  3161. (unless (org-at-table-p)
  3162. (error "Lost table position - cannot install formulas"))
  3163. (org-table-store-formulas eql)
  3164. (move-marker pos nil)
  3165. (kill-buffer "*Edit Formulas*")
  3166. (if arg
  3167. (org-table-recalculate 'all)
  3168. (message "New formulas installed - press C-u C-c C-c to apply."))))
  3169. (defun org-table-fedit-abort ()
  3170. "Abort editing formulas, without installing the changes."
  3171. (interactive)
  3172. (org-table-remove-rectangle-highlight)
  3173. (let ((pos org-pos) (sel-win org-selected-window))
  3174. (set-window-configuration org-window-configuration)
  3175. (select-window sel-win)
  3176. (goto-char pos)
  3177. (move-marker pos nil)
  3178. (message "Formula editing aborted without installing changes")))
  3179. (defun org-table-fedit-lisp-indent ()
  3180. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  3181. (interactive)
  3182. (let ((pos (point)) beg end ind)
  3183. (beginning-of-line 1)
  3184. (cond
  3185. ((looking-at "[ \t]")
  3186. (goto-char pos)
  3187. (call-interactively 'lisp-indent-line))
  3188. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  3189. ((not (fboundp 'pp-buffer))
  3190. (error "Cannot pretty-print. Command `pp-buffer' is not available"))
  3191. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  3192. (goto-char (- (match-end 0) 2))
  3193. (setq beg (point))
  3194. (setq ind (make-string (current-column) ?\ ))
  3195. (condition-case nil (forward-sexp 1)
  3196. (error
  3197. (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  3198. (setq end (point))
  3199. (save-restriction
  3200. (narrow-to-region beg end)
  3201. (if (eq last-command this-command)
  3202. (progn
  3203. (goto-char (point-min))
  3204. (setq this-command nil)
  3205. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  3206. (replace-match " ")))
  3207. (pp-buffer)
  3208. (untabify (point-min) (point-max))
  3209. (goto-char (1+ (point-min)))
  3210. (while (re-search-forward "^." nil t)
  3211. (beginning-of-line 1)
  3212. (insert ind))
  3213. (goto-char (point-max))
  3214. (backward-delete-char 1)))
  3215. (goto-char beg))
  3216. (t nil))))
  3217. (defvar org-show-positions nil)
  3218. (defun org-table-show-reference (&optional local)
  3219. "Show the location/value of the $ expression at point."
  3220. (interactive)
  3221. (org-table-remove-rectangle-highlight)
  3222. (catch 'exit
  3223. (let ((pos (if local (point) org-pos))
  3224. (face2 'highlight)
  3225. (org-inhibit-highlight-removal t)
  3226. (win (selected-window))
  3227. (org-show-positions nil)
  3228. var name e what match dest)
  3229. (if local (org-table-get-specials))
  3230. (setq what (cond
  3231. ((org-at-regexp-p "^@[0-9]+[ \t=]")
  3232. (setq match (concat (substring (match-string 0) 0 -1)
  3233. "$1.."
  3234. (substring (match-string 0) 0 -1)
  3235. "$100"))
  3236. 'range)
  3237. ((or (org-at-regexp-p org-table-range-regexp2)
  3238. (org-at-regexp-p org-table-translate-regexp)
  3239. (org-at-regexp-p org-table-range-regexp))
  3240. (setq match
  3241. (save-match-data
  3242. (org-table-convert-refs-to-rc (match-string 0))))
  3243. 'range)
  3244. ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  3245. ((org-at-regexp-p "\\$[0-9]+") 'column)
  3246. ((not local) nil)
  3247. (t (error "No reference at point")))
  3248. match (and what (or match (match-string 0))))
  3249. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  3250. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  3251. 'secondary-selection))
  3252. (org-add-hook 'before-change-functions
  3253. 'org-table-remove-rectangle-highlight)
  3254. (if (eq what 'name) (setq var (substring match 1)))
  3255. (when (eq what 'range)
  3256. (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
  3257. (setq match (org-table-formula-substitute-names match)))
  3258. (unless local
  3259. (save-excursion
  3260. (end-of-line 1)
  3261. (re-search-backward "^\\S-" nil t)
  3262. (beginning-of-line 1)
  3263. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
  3264. (setq dest
  3265. (save-match-data
  3266. (org-table-convert-refs-to-rc (match-string 1))))
  3267. (org-table-add-rectangle-overlay
  3268. (match-beginning 1) (match-end 1) face2))))
  3269. (if (and (markerp pos) (marker-buffer pos))
  3270. (if (get-buffer-window (marker-buffer pos))
  3271. (select-window (get-buffer-window (marker-buffer pos)))
  3272. (org-switch-to-buffer-other-window (get-buffer-window
  3273. (marker-buffer pos)))))
  3274. (goto-char pos)
  3275. (org-table-force-dataline)
  3276. (when dest
  3277. (setq name (substring dest 1))
  3278. (cond
  3279. ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  3280. (setq e (assoc name org-table-named-field-locations))
  3281. (org-goto-line (nth 1 e))
  3282. (org-table-goto-column (nth 2 e)))
  3283. ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
  3284. (let ((l (string-to-number (match-string 1 dest)))
  3285. (c (string-to-number (match-string 2 dest))))
  3286. (org-goto-line (aref org-table-dlines l))
  3287. (org-table-goto-column c)))
  3288. (t (org-table-goto-column (string-to-number name))))
  3289. (move-marker pos (point))
  3290. (org-table-highlight-rectangle nil nil face2))
  3291. (cond
  3292. ((equal dest match))
  3293. ((not match))
  3294. ((eq what 'range)
  3295. (condition-case nil
  3296. (save-excursion
  3297. (org-table-get-range match nil nil 'highlight))
  3298. (error nil)))
  3299. ((setq e (assoc var org-table-named-field-locations))
  3300. (org-goto-line (nth 1 e))
  3301. (org-table-goto-column (nth 2 e))
  3302. (org-table-highlight-rectangle (point) (point))
  3303. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  3304. ((setq e (assoc var org-table-column-names))
  3305. (org-table-goto-column (string-to-number (cdr e)))
  3306. (org-table-highlight-rectangle (point) (point))
  3307. (goto-char (org-table-begin))
  3308. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  3309. (org-table-end) t)
  3310. (progn
  3311. (goto-char (match-beginning 1))
  3312. (org-table-highlight-rectangle)
  3313. (message "Named column (column %s)" (cdr e)))
  3314. (error "Column name not found")))
  3315. ((eq what 'column)
  3316. ;; column number
  3317. (org-table-goto-column (string-to-number (substring match 1)))
  3318. (org-table-highlight-rectangle (point) (point))
  3319. (message "Column %s" (substring match 1)))
  3320. ((setq e (assoc var org-table-local-parameters))
  3321. (goto-char (org-table-begin))
  3322. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  3323. (progn
  3324. (goto-char (match-beginning 1))
  3325. (org-table-highlight-rectangle)
  3326. (message "Local parameter."))
  3327. (error "Parameter not found")))
  3328. (t
  3329. (cond
  3330. ((not var) (error "No reference at point"))
  3331. ((setq e (assoc var org-table-formula-constants-local))
  3332. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  3333. var (cdr e)))
  3334. ((setq e (assoc var org-table-formula-constants))
  3335. (message "Constant: $%s=%s in `org-table-formula-constants'."
  3336. var (cdr e)))
  3337. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  3338. (message "Constant: $%s=%s, from `constants.el'%s."
  3339. var e (format " (%s units)" constants-unit-system)))
  3340. (t (error "Undefined name $%s" var)))))
  3341. (goto-char pos)
  3342. (when (and org-show-positions
  3343. (not (memq this-command '(org-table-fedit-scroll
  3344. org-table-fedit-scroll-down))))
  3345. (push pos org-show-positions)
  3346. (push org-table-current-begin-pos org-show-positions)
  3347. (let ((min (apply 'min org-show-positions))
  3348. (max (apply 'max org-show-positions)))
  3349. (goto-char min) (recenter 0)
  3350. (goto-char max)
  3351. (or (pos-visible-in-window-p max) (recenter -1))))
  3352. (select-window win))))
  3353. (defun org-table-force-dataline ()
  3354. "Make sure the cursor is in a dataline in a table."
  3355. (unless (save-excursion
  3356. (beginning-of-line 1)
  3357. (looking-at org-table-dataline-regexp))
  3358. (let* ((re org-table-dataline-regexp)
  3359. (p1 (save-excursion (re-search-forward re nil 'move)))
  3360. (p2 (save-excursion (re-search-backward re nil 'move))))
  3361. (cond ((and p1 p2)
  3362. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  3363. p1 p2)))
  3364. ((or p1 p2) (goto-char (or p1 p2)))
  3365. (t (error "No table dataline around here"))))))
  3366. (defun org-table-fedit-line-up ()
  3367. "Move cursor one line up in the window showing the table."
  3368. (interactive)
  3369. (org-table-fedit-move 'previous-line))
  3370. (defun org-table-fedit-line-down ()
  3371. "Move cursor one line down in the window showing the table."
  3372. (interactive)
  3373. (org-table-fedit-move 'next-line))
  3374. (defun org-table-fedit-move (command)
  3375. "Move the cursor in the window showing the table.
  3376. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  3377. (let ((org-table-allow-automatic-line-recalculation nil)
  3378. (pos org-pos) (win (selected-window)) p)
  3379. (select-window (get-buffer-window (marker-buffer org-pos)))
  3380. (setq p (point))
  3381. (call-interactively command)
  3382. (while (and (org-at-table-p)
  3383. (org-at-table-hline-p))
  3384. (call-interactively command))
  3385. (or (org-at-table-p) (goto-char p))
  3386. (move-marker pos (point))
  3387. (select-window win)))
  3388. (defun org-table-fedit-scroll (N)
  3389. (interactive "p")
  3390. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  3391. (scroll-other-window N)))
  3392. (defun org-table-fedit-scroll-down (N)
  3393. (interactive "p")
  3394. (org-table-fedit-scroll (- N)))
  3395. (defvar org-table-rectangle-overlays nil)
  3396. (defun org-table-add-rectangle-overlay (beg end &optional face)
  3397. "Add a new overlay."
  3398. (let ((ov (make-overlay beg end)))
  3399. (overlay-put ov 'face (or face 'secondary-selection))
  3400. (push ov org-table-rectangle-overlays)))
  3401. (defun org-table-highlight-rectangle (&optional beg end face)
  3402. "Highlight rectangular region in a table."
  3403. (setq beg (or beg (point)) end (or end (point)))
  3404. (let ((b (min beg end))
  3405. (e (max beg end))
  3406. l1 c1 l2 c2 tmp)
  3407. (and (boundp 'org-show-positions)
  3408. (setq org-show-positions (cons b (cons e org-show-positions))))
  3409. (goto-char (min beg end))
  3410. (setq l1 (org-current-line)
  3411. c1 (org-table-current-column))
  3412. (goto-char (max beg end))
  3413. (setq l2 (org-current-line)
  3414. c2 (org-table-current-column))
  3415. (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
  3416. (org-goto-line l1)
  3417. (beginning-of-line 1)
  3418. (loop for line from l1 to l2 do
  3419. (when (looking-at org-table-dataline-regexp)
  3420. (org-table-goto-column c1)
  3421. (skip-chars-backward "^|\n") (setq beg (point))
  3422. (org-table-goto-column c2)
  3423. (skip-chars-forward "^|\n") (setq end (point))
  3424. (org-table-add-rectangle-overlay beg end face))
  3425. (beginning-of-line 2))
  3426. (goto-char b))
  3427. (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
  3428. (defun org-table-remove-rectangle-highlight (&rest ignore)
  3429. "Remove the rectangle overlays."
  3430. (unless org-inhibit-highlight-removal
  3431. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  3432. (mapc 'delete-overlay org-table-rectangle-overlays)
  3433. (setq org-table-rectangle-overlays nil)))
  3434. (defvar org-table-coordinate-overlays nil
  3435. "Collects the coordinate grid overlays, so that they can be removed.")
  3436. (make-variable-buffer-local 'org-table-coordinate-overlays)
  3437. (defun org-table-overlay-coordinates ()
  3438. "Add overlays to the table at point, to show row/column coordinates."
  3439. (interactive)
  3440. (mapc 'delete-overlay org-table-coordinate-overlays)
  3441. (setq org-table-coordinate-overlays nil)
  3442. (save-excursion
  3443. (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
  3444. (goto-char (org-table-begin))
  3445. (while (org-at-table-p)
  3446. (setq eol (point-at-eol))
  3447. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  3448. (push ov org-table-coordinate-overlays)
  3449. (setq hline (looking-at org-table-hline-regexp))
  3450. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  3451. (format "%4d" (setq id (1+ id)))))
  3452. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  3453. (when hline
  3454. (setq ic 0)
  3455. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  3456. (setq beg (1+ (match-beginning 0))
  3457. ic (1+ ic)
  3458. s1 (concat "$" (int-to-string ic))
  3459. s2 (org-number-to-letters ic)
  3460. str (if (eq org-table-use-standard-references t) s2 s1))
  3461. (setq ov (make-overlay beg (+ beg (length str))))
  3462. (push ov org-table-coordinate-overlays)
  3463. (org-overlay-display ov str 'org-special-keyword 'evaporate)))
  3464. (beginning-of-line 2)))))
  3465. (defun org-table-toggle-coordinate-overlays ()
  3466. "Toggle the display of Row/Column numbers in tables."
  3467. (interactive)
  3468. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  3469. (message "Row/Column number display turned %s"
  3470. (if org-table-overlay-coordinates "on" "off"))
  3471. (if (and (org-at-table-p) org-table-overlay-coordinates)
  3472. (org-table-align))
  3473. (unless org-table-overlay-coordinates
  3474. (mapc 'delete-overlay org-table-coordinate-overlays)
  3475. (setq org-table-coordinate-overlays nil)))
  3476. (defun org-table-toggle-formula-debugger ()
  3477. "Toggle the formula debugger in tables."
  3478. (interactive)
  3479. (setq org-table-formula-debug (not org-table-formula-debug))
  3480. (message "Formula debugging has been turned %s"
  3481. (if org-table-formula-debug "on" "off")))
  3482. ;;; The orgtbl minor mode
  3483. ;; Define a minor mode which can be used in other modes in order to
  3484. ;; integrate the org-mode table editor.
  3485. ;; This is really a hack, because the org-mode table editor uses several
  3486. ;; keys which normally belong to the major mode, for example the TAB and
  3487. ;; RET keys. Here is how it works: The minor mode defines all the keys
  3488. ;; necessary to operate the table editor, but wraps the commands into a
  3489. ;; function which tests if the cursor is currently inside a table. If that
  3490. ;; is the case, the table editor command is executed. However, when any of
  3491. ;; those keys is used outside a table, the function uses `key-binding' to
  3492. ;; look up if the key has an associated command in another currently active
  3493. ;; keymap (minor modes, major mode, global), and executes that command.
  3494. ;; There might be problems if any of the keys used by the table editor is
  3495. ;; otherwise used as a prefix key.
  3496. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  3497. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  3498. ;; addresses this by checking explicitly for both bindings.
  3499. ;; The optimized version (see variable `orgtbl-optimized') takes over
  3500. ;; all keys which are bound to `self-insert-command' in the *global map*.
  3501. ;; Some modes bind other commands to simple characters, for example
  3502. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  3503. ;; active, this binding is ignored inside tables and replaced with a
  3504. ;; modified self-insert.
  3505. (defvar orgtbl-mode-map (make-keymap)
  3506. "Keymap for `orgtbl-mode'.")
  3507. ;;;###autoload
  3508. (defun turn-on-orgtbl ()
  3509. "Unconditionally turn on `orgtbl-mode'."
  3510. (orgtbl-mode 1))
  3511. (defvar org-old-auto-fill-inhibit-regexp nil
  3512. "Local variable used by `orgtbl-mode'.")
  3513. (defconst orgtbl-line-start-regexp
  3514. "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\|TBLNAME\\):\\)"
  3515. "Matches a line belonging to an orgtbl.")
  3516. (defconst orgtbl-extra-font-lock-keywords
  3517. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  3518. 0 (quote 'org-table) 'prepend))
  3519. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  3520. ;; Install it as a minor mode.
  3521. (put 'orgtbl-mode :included t)
  3522. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  3523. ;;;###autoload
  3524. (define-minor-mode orgtbl-mode
  3525. "The `org-mode' table editor as a minor mode for use in other modes."
  3526. :lighter " OrgTbl" :keymap orgtbl-mode-map
  3527. (org-load-modules-maybe)
  3528. (cond
  3529. ((org-mode-p)
  3530. ;; Exit without error, in case some hook functions calls this
  3531. ;; by accident in org-mode.
  3532. (message "Orgtbl-mode is not useful in org-mode, command ignored"))
  3533. (orgtbl-mode
  3534. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  3535. ;; Make sure we are first in minor-mode-map-alist
  3536. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  3537. ;; FIXME: maybe it should use emulation-mode-map-alists?
  3538. (and c (setq minor-mode-map-alist
  3539. (cons c (delq c minor-mode-map-alist)))))
  3540. (org-set-local (quote org-table-may-need-update) t)
  3541. (org-add-hook 'before-change-functions 'org-before-change-function
  3542. nil 'local)
  3543. (org-set-local 'org-old-auto-fill-inhibit-regexp
  3544. auto-fill-inhibit-regexp)
  3545. (org-set-local 'auto-fill-inhibit-regexp
  3546. (if auto-fill-inhibit-regexp
  3547. (concat orgtbl-line-start-regexp "\\|"
  3548. auto-fill-inhibit-regexp)
  3549. orgtbl-line-start-regexp))
  3550. (add-to-invisibility-spec '(org-cwidth))
  3551. (when (fboundp 'font-lock-add-keywords)
  3552. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  3553. (org-restart-font-lock))
  3554. (easy-menu-add orgtbl-mode-menu))
  3555. (t
  3556. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  3557. (org-table-cleanup-narrow-column-properties)
  3558. (org-remove-from-invisibility-spec '(org-cwidth))
  3559. (remove-hook 'before-change-functions 'org-before-change-function t)
  3560. (when (fboundp 'font-lock-remove-keywords)
  3561. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  3562. (org-restart-font-lock))
  3563. (easy-menu-remove orgtbl-mode-menu)
  3564. (force-mode-line-update 'all))))
  3565. (defun org-table-cleanup-narrow-column-properties ()
  3566. "Remove all properties related to narrow-column invisibility."
  3567. (let ((s (point-min)))
  3568. (while (setq s (text-property-any s (point-max)
  3569. 'display org-narrow-column-arrow))
  3570. (remove-text-properties s (1+ s) '(display t)))
  3571. (setq s (point-min))
  3572. (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
  3573. (remove-text-properties s (1+ s) '(org-cwidth t)))
  3574. (setq s (point-min))
  3575. (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
  3576. (remove-text-properties s (1+ s) '(invisible t)))))
  3577. (defun orgtbl-make-binding (fun n &rest keys)
  3578. "Create a function for binding in the table minor mode.
  3579. FUN is the command to call inside a table. N is used to create a unique
  3580. command name. KEYS are keys that should be checked in for a command
  3581. to execute outside of tables."
  3582. (eval
  3583. (list 'defun
  3584. (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
  3585. '(arg)
  3586. (concat "In tables, run `" (symbol-name fun) "'.\n"
  3587. "Outside of tables, run the binding of `"
  3588. (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
  3589. "'.")
  3590. '(interactive "p")
  3591. (list 'if
  3592. '(org-at-table-p)
  3593. (list 'call-interactively (list 'quote fun))
  3594. (list 'let '(orgtbl-mode)
  3595. (list 'call-interactively
  3596. (append '(or)
  3597. (mapcar (lambda (k)
  3598. (list 'key-binding k))
  3599. keys)
  3600. '('orgtbl-error))))))))
  3601. (defun orgtbl-error ()
  3602. "Error when there is no default binding for a table key."
  3603. (interactive)
  3604. (error "This key has no function outside tables"))
  3605. (defun orgtbl-setup ()
  3606. "Setup orgtbl keymaps."
  3607. (let ((nfunc 0)
  3608. (bindings
  3609. '(([(meta shift left)] org-table-delete-column)
  3610. ([(meta left)] org-table-move-column-left)
  3611. ([(meta right)] org-table-move-column-right)
  3612. ([(meta shift right)] org-table-insert-column)
  3613. ([(meta shift up)] org-table-kill-row)
  3614. ([(meta shift down)] org-table-insert-row)
  3615. ([(meta up)] org-table-move-row-up)
  3616. ([(meta down)] org-table-move-row-down)
  3617. ("\C-c\C-w" org-table-cut-region)
  3618. ("\C-c\M-w" org-table-copy-region)
  3619. ("\C-c\C-y" org-table-paste-rectangle)
  3620. ("\C-c-" org-table-insert-hline)
  3621. ("\C-c}" org-table-toggle-coordinate-overlays)
  3622. ("\C-c{" org-table-toggle-formula-debugger)
  3623. ("\C-m" org-table-next-row)
  3624. ([(shift return)] org-table-copy-down)
  3625. ("\C-c?" org-table-field-info)
  3626. ("\C-c " org-table-blank-field)
  3627. ("\C-c+" org-table-sum)
  3628. ("\C-c=" org-table-eval-formula)
  3629. ("\C-c'" org-table-edit-formulas)
  3630. ("\C-c`" org-table-edit-field)
  3631. ("\C-c*" org-table-recalculate)
  3632. ("\C-c^" org-table-sort-lines)
  3633. ("\M-a" org-table-beginning-of-field)
  3634. ("\M-e" org-table-end-of-field)
  3635. ([(control ?#)] org-table-rotate-recalc-marks)))
  3636. elt key fun cmd)
  3637. (while (setq elt (pop bindings))
  3638. (setq nfunc (1+ nfunc))
  3639. (setq key (org-key (car elt))
  3640. fun (nth 1 elt)
  3641. cmd (orgtbl-make-binding fun nfunc key))
  3642. (org-defkey orgtbl-mode-map key cmd))
  3643. ;; Special treatment needed for TAB and RET
  3644. (org-defkey orgtbl-mode-map [(return)]
  3645. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  3646. (org-defkey orgtbl-mode-map "\C-m"
  3647. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  3648. (org-defkey orgtbl-mode-map [(tab)]
  3649. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  3650. (org-defkey orgtbl-mode-map "\C-i"
  3651. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  3652. (org-defkey orgtbl-mode-map [(shift tab)]
  3653. (orgtbl-make-binding 'org-table-previous-field 104
  3654. [(shift tab)] [(tab)] "\C-i"))
  3655. (unless (featurep 'xemacs)
  3656. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  3657. (orgtbl-make-binding 'org-table-previous-field 107
  3658. [S-iso-lefttab] [backtab] [(shift tab)]
  3659. [(tab)] "\C-i")))
  3660. (org-defkey orgtbl-mode-map [backtab]
  3661. (orgtbl-make-binding 'org-table-previous-field 108
  3662. [backtab] [S-iso-lefttab] [(shift tab)]
  3663. [(tab)] "\C-i"))
  3664. (org-defkey orgtbl-mode-map "\M-\C-m"
  3665. (orgtbl-make-binding 'org-table-wrap-region 105
  3666. "\M-\C-m" [(meta return)]))
  3667. (org-defkey orgtbl-mode-map [(meta return)]
  3668. (orgtbl-make-binding 'org-table-wrap-region 106
  3669. [(meta return)] "\M-\C-m"))
  3670. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  3671. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  3672. (when orgtbl-optimized
  3673. ;; If the user wants maximum table support, we need to hijack
  3674. ;; some standard editing functions
  3675. (org-remap orgtbl-mode-map
  3676. 'self-insert-command 'orgtbl-self-insert-command
  3677. 'delete-char 'org-delete-char
  3678. 'delete-backward-char 'org-delete-backward-char)
  3679. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  3680. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
  3681. '("OrgTbl"
  3682. ["Create or convert" org-table-create-or-convert-from-region
  3683. :active (not (org-at-table-p)) :keys "C-c |" ]
  3684. "--"
  3685. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  3686. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  3687. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  3688. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  3689. "--"
  3690. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  3691. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  3692. ["Copy Field from Above"
  3693. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  3694. "--"
  3695. ("Column"
  3696. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  3697. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  3698. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  3699. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  3700. ("Row"
  3701. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  3702. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  3703. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  3704. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  3705. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  3706. "--"
  3707. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  3708. ("Rectangle"
  3709. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  3710. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  3711. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  3712. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  3713. "--"
  3714. ("Radio tables"
  3715. ["Insert table template" orgtbl-insert-radio-table
  3716. (assq major-mode orgtbl-radio-table-templates)]
  3717. ["Comment/uncomment table" orgtbl-toggle-comment t])
  3718. "--"
  3719. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  3720. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  3721. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  3722. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  3723. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  3724. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  3725. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  3726. ["Sum Column/Rectangle" org-table-sum
  3727. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  3728. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  3729. ["Debug Formulas"
  3730. org-table-toggle-formula-debugger :active (org-at-table-p)
  3731. :keys "C-c {"
  3732. :style toggle :selected org-table-formula-debug]
  3733. ["Show Col/Row Numbers"
  3734. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  3735. :keys "C-c }"
  3736. :style toggle :selected org-table-overlay-coordinates]
  3737. ))
  3738. t))
  3739. (defun orgtbl-ctrl-c-ctrl-c (arg)
  3740. "If the cursor is inside a table, realign the table.
  3741. If it is a table to be sent away to a receiver, do it.
  3742. With prefix arg, also recompute table."
  3743. (interactive "P")
  3744. (let ((pos (point)) action consts-str consts cst const-str)
  3745. (save-excursion
  3746. (beginning-of-line 1)
  3747. (setq action (cond
  3748. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  3749. ((looking-at "[ \t]*|") pos)
  3750. ((looking-at "[ \t]*#\\+TBLFM:") 'recalc))))
  3751. (cond
  3752. ((integerp action)
  3753. (goto-char action)
  3754. (org-table-maybe-eval-formula)
  3755. (if arg
  3756. (call-interactively 'org-table-recalculate)
  3757. (org-table-maybe-recalculate-line))
  3758. (call-interactively 'org-table-align)
  3759. (when (orgtbl-send-table 'maybe)
  3760. (run-hooks 'orgtbl-after-send-table-hook)))
  3761. ((eq action 'recalc)
  3762. (save-excursion
  3763. (goto-char (point-min))
  3764. (while (re-search-forward "^[ \t]*#\\+CONSTANTS: \\(.*\\)" nil t)
  3765. (setq const-str (substring-no-properties (match-string 1)))
  3766. (setq consts (append consts (org-split-string const-str "[ \t]+")))
  3767. (when consts
  3768. (let (e)
  3769. (while (setq e (pop consts))
  3770. (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
  3771. (push (cons (match-string 1 e) (match-string 2 e)) cst)))
  3772. (setq org-table-formula-constants-local cst)))))
  3773. (save-excursion
  3774. (beginning-of-line 1)
  3775. (skip-chars-backward " \r\n\t")
  3776. (if (org-at-table-p)
  3777. (org-call-with-arg 'org-table-recalculate t))))
  3778. (t (let (orgtbl-mode)
  3779. (call-interactively (key-binding "\C-c\C-c")))))))
  3780. (defun orgtbl-create-or-convert-from-region (arg)
  3781. "Create table or convert region to table, if no conflicting binding.
  3782. This installs the table binding `C-c |', but only if there is no
  3783. conflicting binding to this key outside orgtbl-mode."
  3784. (interactive "P")
  3785. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  3786. (if cmd
  3787. (call-interactively cmd)
  3788. (call-interactively 'org-table-create-or-convert-from-region))))
  3789. (defun orgtbl-tab (arg)
  3790. "Justification and field motion for `orgtbl-mode'."
  3791. (interactive "P")
  3792. (if arg (org-table-edit-field t)
  3793. (org-table-justify-field-maybe)
  3794. (org-table-next-field)))
  3795. (defun orgtbl-ret ()
  3796. "Justification and field motion for `orgtbl-mode'."
  3797. (interactive)
  3798. (if (bobp)
  3799. (newline)
  3800. (org-table-justify-field-maybe)
  3801. (org-table-next-row)))
  3802. (defun orgtbl-self-insert-command (N)
  3803. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  3804. If the cursor is in a table looking at whitespace, the whitespace is
  3805. overwritten, and the table is not marked as requiring realignment."
  3806. (interactive "p")
  3807. (if (and (org-at-table-p)
  3808. (or
  3809. (and org-table-auto-blank-field
  3810. (member last-command
  3811. '(orgtbl-hijacker-command-100
  3812. orgtbl-hijacker-command-101
  3813. orgtbl-hijacker-command-102
  3814. orgtbl-hijacker-command-103
  3815. orgtbl-hijacker-command-104
  3816. orgtbl-hijacker-command-105
  3817. yas/expand))
  3818. (org-table-blank-field))
  3819. t)
  3820. (eq N 1)
  3821. (looking-at "[^|\n]* +|"))
  3822. (let (org-table-may-need-update)
  3823. (goto-char (1- (match-end 0)))
  3824. (delete-char -1)
  3825. (goto-char (match-beginning 0))
  3826. (self-insert-command N))
  3827. (setq org-table-may-need-update t)
  3828. (let* (orgtbl-mode
  3829. a
  3830. (cmd (or (key-binding
  3831. (or (and (listp function-key-map)
  3832. (setq a (assoc last-input-event function-key-map))
  3833. (cdr a))
  3834. (vector last-input-event)))
  3835. 'self-insert-command)))
  3836. (call-interactively cmd)
  3837. (if (and org-self-insert-cluster-for-undo
  3838. (eq cmd 'self-insert-command))
  3839. (if (not (eq last-command 'orgtbl-self-insert-command))
  3840. (setq org-self-insert-command-undo-counter 1)
  3841. (if (>= org-self-insert-command-undo-counter 20)
  3842. (setq org-self-insert-command-undo-counter 1)
  3843. (and (> org-self-insert-command-undo-counter 0)
  3844. buffer-undo-list
  3845. (not (cadr buffer-undo-list)) ; remove nil entry
  3846. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  3847. (setq org-self-insert-command-undo-counter
  3848. (1+ org-self-insert-command-undo-counter))))))))
  3849. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  3850. "Regular expression matching exponentials as produced by calc.")
  3851. (defun orgtbl-export (table target)
  3852. (require 'org-exp)
  3853. (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
  3854. (lines (org-split-string table "[ \t]*\n[ \t]*"))
  3855. org-table-last-alignment org-table-last-column-widths
  3856. maxcol column)
  3857. (if (not (fboundp func))
  3858. (error "Cannot export orgtbl table to %s" target))
  3859. (setq lines (org-table-clean-before-export lines))
  3860. (setq table
  3861. (mapcar
  3862. (lambda (x)
  3863. (if (string-match org-table-hline-regexp x)
  3864. 'hline
  3865. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  3866. lines))
  3867. (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
  3868. table)))
  3869. (loop for i from (1- maxcol) downto 0 do
  3870. (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
  3871. (setq column (delq nil column))
  3872. (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
  3873. (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))
  3874. (funcall func table nil)))
  3875. (defun orgtbl-gather-send-defs ()
  3876. "Gather a plist of :name, :transform, :params for each destination before
  3877. a radio table."
  3878. (save-excursion
  3879. (goto-char (org-table-begin))
  3880. (let (rtn)
  3881. (beginning-of-line 0)
  3882. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  3883. (let ((name (org-no-properties (match-string 1)))
  3884. (transform (intern (match-string 2)))
  3885. (params (if (match-end 3)
  3886. (read (concat "(" (match-string 3) ")")))))
  3887. (push (list :name name :transform transform :params params)
  3888. rtn)
  3889. (beginning-of-line 0)))
  3890. rtn)))
  3891. (defun orgtbl-send-replace-tbl (name txt)
  3892. "Find and replace table NAME with TXT."
  3893. (save-excursion
  3894. (goto-char (point-min))
  3895. (unless (re-search-forward
  3896. (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
  3897. (error "Don't know where to insert translated table"))
  3898. (goto-char (match-beginning 0))
  3899. (beginning-of-line 2)
  3900. (save-excursion
  3901. (let ((beg (point)))
  3902. (unless (re-search-forward
  3903. (concat "END RECEIVE ORGTBL +" name) nil t)
  3904. (error "Cannot find end of insertion region"))
  3905. (beginning-of-line 1)
  3906. (delete-region beg (point))))
  3907. (insert txt "\n")))
  3908. ;;;###autoload
  3909. (defun org-table-to-lisp (&optional txt)
  3910. "Convert the table at point to a Lisp structure.
  3911. The structure will be a list. Each item is either the symbol `hline'
  3912. for a horizontal separator line, or a list of field values as strings.
  3913. The table is taken from the parameter TXT, or from the buffer at point."
  3914. (unless txt
  3915. (unless (org-at-table-p)
  3916. (error "No table at point")))
  3917. (let* ((txt (or txt
  3918. (buffer-substring-no-properties (org-table-begin)
  3919. (org-table-end))))
  3920. (lines (org-split-string txt "[ \t]*\n[ \t]*")))
  3921. (mapcar
  3922. (lambda (x)
  3923. (if (string-match org-table-hline-regexp x)
  3924. 'hline
  3925. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  3926. lines)))
  3927. (defun orgtbl-send-table (&optional maybe)
  3928. "Send a transformed version of this table to the receiver position.
  3929. With argument MAYBE, fail quietly if no transformation is defined for
  3930. this table."
  3931. (interactive)
  3932. (catch 'exit
  3933. (unless (org-at-table-p) (error "Not at a table"))
  3934. ;; when non-interactive, we assume align has just happened.
  3935. (when (org-called-interactively-p 'any) (org-table-align))
  3936. (let ((dests (orgtbl-gather-send-defs))
  3937. (txt (buffer-substring-no-properties (org-table-begin)
  3938. (org-table-end)))
  3939. (ntbl 0))
  3940. (unless dests (if maybe (throw 'exit nil)
  3941. (error "Don't know how to transform this table")))
  3942. (dolist (dest dests)
  3943. (let* ((name (plist-get dest :name))
  3944. (transform (plist-get dest :transform))
  3945. (params (plist-get dest :params))
  3946. (skip (plist-get params :skip))
  3947. (skipcols (plist-get params :skipcols))
  3948. beg
  3949. (lines (org-table-clean-before-export
  3950. (nthcdr (or skip 0)
  3951. (org-split-string txt "[ \t]*\n[ \t]*"))))
  3952. (i0 (if org-table-clean-did-remove-column 2 1))
  3953. (table (mapcar
  3954. (lambda (x)
  3955. (if (string-match org-table-hline-regexp x)
  3956. 'hline
  3957. (org-remove-by-index
  3958. (org-split-string (org-trim x) "\\s-*|\\s-*")
  3959. skipcols i0)))
  3960. lines))
  3961. (fun (if (= i0 2) 'cdr 'identity))
  3962. (org-table-last-alignment
  3963. (org-remove-by-index (funcall fun org-table-last-alignment)
  3964. skipcols i0))
  3965. (org-table-last-column-widths
  3966. (org-remove-by-index (funcall fun org-table-last-column-widths)
  3967. skipcols i0))
  3968. (txt (if (fboundp transform)
  3969. (funcall transform table params)
  3970. (error "No such transformation function %s" transform))))
  3971. (orgtbl-send-replace-tbl name txt))
  3972. (setq ntbl (1+ ntbl)))
  3973. (message "Table converted and installed at %d receiver location%s"
  3974. ntbl (if (> ntbl 1) "s" ""))
  3975. (if (> ntbl 0)
  3976. ntbl
  3977. nil))))
  3978. (defun org-remove-by-index (list indices &optional i0)
  3979. "Remove the elements in LIST with indices in INDICES.
  3980. First element has index 0, or I0 if given."
  3981. (if (not indices)
  3982. list
  3983. (if (integerp indices) (setq indices (list indices)))
  3984. (setq i0 (1- (or i0 0)))
  3985. (delq :rm (mapcar (lambda (x)
  3986. (setq i0 (1+ i0))
  3987. (if (memq i0 indices) :rm x))
  3988. list))))
  3989. (defun orgtbl-toggle-comment ()
  3990. "Comment or uncomment the orgtbl at point."
  3991. (interactive)
  3992. (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  3993. (re2 (concat "^" orgtbl-line-start-regexp))
  3994. (commented (save-excursion (beginning-of-line 1)
  3995. (cond ((looking-at re1) t)
  3996. ((looking-at re2) nil)
  3997. (t (error "Not at an org table")))))
  3998. (re (if commented re1 re2))
  3999. beg end)
  4000. (save-excursion
  4001. (beginning-of-line 1)
  4002. (while (looking-at re) (beginning-of-line 0))
  4003. (beginning-of-line 2)
  4004. (setq beg (point))
  4005. (while (looking-at re) (beginning-of-line 2))
  4006. (setq end (point)))
  4007. (comment-region beg end (if commented '(4) nil))))
  4008. (defun orgtbl-insert-radio-table ()
  4009. "Insert a radio table template appropriate for this major mode."
  4010. (interactive)
  4011. (let* ((e (assq major-mode orgtbl-radio-table-templates))
  4012. (txt (nth 1 e))
  4013. name pos)
  4014. (unless e (error "No radio table setup defined for %s" major-mode))
  4015. (setq name (read-string "Table name: "))
  4016. (while (string-match "%n" txt)
  4017. (setq txt (replace-match name t t txt)))
  4018. (or (bolp) (insert "\n"))
  4019. (setq pos (point))
  4020. (insert txt)
  4021. (goto-char pos)))
  4022. ;; Dynamically bound input and output for table formatting.
  4023. (defvar *orgtbl-table* nil
  4024. "Carries the current table through formatting routines.")
  4025. (defvar *orgtbl-rtn* nil
  4026. "Formatting routines push the output lines here.")
  4027. ;; Formatting parameters for the current table section.
  4028. (defvar *orgtbl-hline* nil "Text used for horizontal lines.")
  4029. (defvar *orgtbl-sep* nil "Text used as a column separator.")
  4030. (defvar *orgtbl-default-fmt* nil "Default format for each entry.")
  4031. (defvar *orgtbl-fmt* nil "Format for each entry.")
  4032. (defvar *orgtbl-efmt* nil "Format for numbers.")
  4033. (defvar *orgtbl-lfmt* nil "Format for an entire line, overrides fmt.")
  4034. (defvar *orgtbl-llfmt* nil "Specializes lfmt for the last row.")
  4035. (defvar *orgtbl-lstart* nil "Text starting a row.")
  4036. (defvar *orgtbl-llstart* nil "Specializes lstart for the last row.")
  4037. (defvar *orgtbl-lend* nil "Text ending a row.")
  4038. (defvar *orgtbl-llend* nil "Specializes lend for the last row.")
  4039. (defsubst orgtbl-get-fmt (fmt i)
  4040. "Retrieve the format from FMT corresponding to the Ith column."
  4041. (if (and (not (functionp fmt)) (consp fmt))
  4042. (plist-get fmt i)
  4043. fmt))
  4044. (defsubst orgtbl-apply-fmt (fmt &rest args)
  4045. "Apply format FMT to the arguments. NIL FMTs return the first argument."
  4046. (cond ((functionp fmt) (apply fmt args))
  4047. (fmt (apply 'format fmt args))
  4048. (args (car args))
  4049. (t args)))
  4050. (defsubst orgtbl-eval-str (str)
  4051. "If STR is a function, evaluate it with no arguments."
  4052. (if (functionp str)
  4053. (funcall str)
  4054. str))
  4055. (defun orgtbl-format-line (line)
  4056. "Format LINE as a table row."
  4057. (if (eq line 'hline) (if *orgtbl-hline* (push *orgtbl-hline* *orgtbl-rtn*))
  4058. (let* ((i 0)
  4059. (line
  4060. (mapcar
  4061. (lambda (f)
  4062. (setq i (1+ i))
  4063. (let* ((efmt (orgtbl-get-fmt *orgtbl-efmt* i))
  4064. (f (if (and efmt (string-match orgtbl-exp-regexp f))
  4065. (orgtbl-apply-fmt efmt (match-string 1 f)
  4066. (match-string 2 f))
  4067. f)))
  4068. (orgtbl-apply-fmt (or (orgtbl-get-fmt *orgtbl-fmt* i)
  4069. *orgtbl-default-fmt*)
  4070. f)))
  4071. line)))
  4072. (push (if *orgtbl-lfmt*
  4073. (orgtbl-apply-fmt *orgtbl-lfmt* line)
  4074. (concat (orgtbl-eval-str *orgtbl-lstart*)
  4075. (mapconcat 'identity line *orgtbl-sep*)
  4076. (orgtbl-eval-str *orgtbl-lend*)))
  4077. *orgtbl-rtn*))))
  4078. (defun orgtbl-format-section (section-stopper)
  4079. "Format lines until the first occurrence of SECTION-STOPPER."
  4080. (let (prevline)
  4081. (progn
  4082. (while (not (eq (car *orgtbl-table*) section-stopper))
  4083. (if prevline (orgtbl-format-line prevline))
  4084. (setq prevline (pop *orgtbl-table*)))
  4085. (if prevline (let ((*orgtbl-lstart* *orgtbl-llstart*)
  4086. (*orgtbl-lend* *orgtbl-llend*)
  4087. (*orgtbl-lfmt* *orgtbl-llfmt*))
  4088. (orgtbl-format-line prevline))))))
  4089. (defun orgtbl-to-generic (table params)
  4090. "Convert the orgtbl-mode TABLE to some other format.
  4091. This generic routine can be used for many standard cases.
  4092. TABLE is a list, each entry either the symbol `hline' for a horizontal
  4093. separator line, or a list of fields for that line.
  4094. PARAMS is a property list of parameters that can influence the conversion.
  4095. For the generic converter, some parameters are obligatory: you need to
  4096. specify either :lfmt, or all of (:lstart :lend :sep).
  4097. Valid parameters are
  4098. :splice When set to t, return only table body lines, don't wrap
  4099. them into :tstart and :tend. Default is nil. When :splice
  4100. is non-nil, this also means that the exporter should not look
  4101. for and interpret header and footer sections.
  4102. :hline String to be inserted on horizontal separation lines.
  4103. May be nil to ignore hlines.
  4104. :sep Separator between two fields
  4105. :remove-nil-lines Do not include lines that evaluate to nil.
  4106. Each in the following group may be either a string or a function
  4107. of no arguments returning a string:
  4108. :tstart String to start the table. Ignored when :splice is t.
  4109. :tend String to end the table. Ignored when :splice is t.
  4110. :lstart String to start a new table line.
  4111. :llstart String to start the last table line, defaults to :lstart.
  4112. :lend String to end a table line
  4113. :llend String to end the last table line, defaults to :lend.
  4114. Each in the following group may be a string, a function of one
  4115. argument (the field or line) returning a string, or a plist
  4116. mapping columns to either of the above:
  4117. :lfmt Format for entire line, with enough %s to capture all fields.
  4118. If this is present, :lstart, :lend, and :sep are ignored.
  4119. :llfmt Format for the entire last line, defaults to :lfmt.
  4120. :fmt A format to be used to wrap the field, should contain
  4121. %s for the original field value. For example, to wrap
  4122. everything in dollars, you could use :fmt \"$%s$\".
  4123. This may also be a property list with column numbers and
  4124. formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
  4125. :hlstart :hllstart :hlend :hllend :hlsep :hlfmt :hllfmt :hfmt
  4126. Same as above, specific for the header lines in the table.
  4127. All lines before the first hline are treated as header.
  4128. If any of these is not present, the data line value is used.
  4129. This may be either a string or a function of two arguments:
  4130. :efmt Use this format to print numbers with exponentials.
  4131. The format should have %s twice for inserting mantissa
  4132. and exponent, for example \"%s\\\\times10^{%s}\". This
  4133. may also be a property list with column numbers and
  4134. formats. :fmt will still be applied after :efmt.
  4135. In addition to this, the parameters :skip and :skipcols are always handled
  4136. directly by `orgtbl-send-table'. See manual."
  4137. (interactive)
  4138. (let* ((splicep (plist-get params :splice))
  4139. (hline (plist-get params :hline))
  4140. (remove-nil-linesp (plist-get params :remove-nil-lines))
  4141. (remove-newlines (plist-get params :remove-newlines))
  4142. (*orgtbl-hline* hline)
  4143. (*orgtbl-table* table)
  4144. (*orgtbl-sep* (plist-get params :sep))
  4145. (*orgtbl-efmt* (plist-get params :efmt))
  4146. (*orgtbl-lstart* (plist-get params :lstart))
  4147. (*orgtbl-llstart* (or (plist-get params :llstart) *orgtbl-lstart*))
  4148. (*orgtbl-lend* (plist-get params :lend))
  4149. (*orgtbl-llend* (or (plist-get params :llend) *orgtbl-lend*))
  4150. (*orgtbl-lfmt* (plist-get params :lfmt))
  4151. (*orgtbl-llfmt* (or (plist-get params :llfmt) *orgtbl-lfmt*))
  4152. (*orgtbl-fmt* (plist-get params :fmt))
  4153. *orgtbl-rtn*)
  4154. ;; Put header
  4155. (unless splicep
  4156. (when (plist-member params :tstart)
  4157. (let ((tstart (orgtbl-eval-str (plist-get params :tstart))))
  4158. (if tstart (push tstart *orgtbl-rtn*)))))
  4159. ;; Do we have a heading section? If so, format it and handle the
  4160. ;; trailing hline.
  4161. (if (and (not splicep)
  4162. (or (consp (car *orgtbl-table*))
  4163. (consp (nth 1 *orgtbl-table*)))
  4164. (memq 'hline (cdr *orgtbl-table*)))
  4165. (progn
  4166. (when (eq 'hline (car *orgtbl-table*))
  4167. ;; there is a hline before the first data line
  4168. (and hline (push hline *orgtbl-rtn*))
  4169. (pop *orgtbl-table*))
  4170. (let* ((*orgtbl-lstart* (or (plist-get params :hlstart)
  4171. *orgtbl-lstart*))
  4172. (*orgtbl-llstart* (or (plist-get params :hllstart)
  4173. *orgtbl-llstart*))
  4174. (*orgtbl-lend* (or (plist-get params :hlend) *orgtbl-lend*))
  4175. (*orgtbl-llend* (or (plist-get params :hllend)
  4176. (plist-get params :hlend) *orgtbl-llend*))
  4177. (*orgtbl-lfmt* (or (plist-get params :hlfmt) *orgtbl-lfmt*))
  4178. (*orgtbl-llfmt* (or (plist-get params :hllfmt)
  4179. (plist-get params :hlfmt) *orgtbl-llfmt*))
  4180. (*orgtbl-sep* (or (plist-get params :hlsep) *orgtbl-sep*))
  4181. (*orgtbl-fmt* (or (plist-get params :hfmt) *orgtbl-fmt*)))
  4182. (orgtbl-format-section 'hline))
  4183. (if hline (push hline *orgtbl-rtn*))
  4184. (pop *orgtbl-table*)))
  4185. ;; Now format the main section.
  4186. (orgtbl-format-section nil)
  4187. (unless splicep
  4188. (when (plist-member params :tend)
  4189. (let ((tend (orgtbl-eval-str (plist-get params :tend))))
  4190. (if tend (push tend *orgtbl-rtn*)))))
  4191. (mapconcat (if remove-newlines
  4192. (lambda (tend)
  4193. (replace-regexp-in-string "[\n\r\t\f]" "\\\\n" tend))
  4194. 'identity)
  4195. (nreverse (if remove-nil-linesp
  4196. (remq nil *orgtbl-rtn*)
  4197. *orgtbl-rtn*)) "\n")))
  4198. (defun orgtbl-to-tsv (table params)
  4199. "Convert the orgtbl-mode table to TAB separated material."
  4200. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  4201. (defun orgtbl-to-csv (table params)
  4202. "Convert the orgtbl-mode table to CSV material.
  4203. This does take care of the proper quoting of fields with comma or quotes."
  4204. (orgtbl-to-generic table (org-combine-plists
  4205. '(:sep "," :fmt org-quote-csv-field)
  4206. params)))
  4207. (defun orgtbl-to-latex (table params)
  4208. "Convert the orgtbl-mode TABLE to LaTeX.
  4209. TABLE is a list, each entry either the symbol `hline' for a horizontal
  4210. separator line, or a list of fields for that line.
  4211. PARAMS is a property list of parameters that can influence the conversion.
  4212. Supports all parameters from `orgtbl-to-generic'. Most important for
  4213. LaTeX are:
  4214. :splice When set to t, return only table body lines, don't wrap
  4215. them into a tabular environment. Default is nil.
  4216. :fmt A format to be used to wrap the field, should contain %s for the
  4217. original field value. For example, to wrap everything in dollars,
  4218. use :fmt \"$%s$\". This may also be a property list with column
  4219. numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
  4220. The format may also be a function that formats its one argument.
  4221. :efmt Format for transforming numbers with exponentials. The format
  4222. should have %s twice for inserting mantissa and exponent, for
  4223. example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
  4224. This may also be a property list with column numbers and formats.
  4225. The format may also be a function that formats its two arguments.
  4226. :llend If you find too much space below the last line of a table,
  4227. pass a value of \"\" for :llend to suppress the final \\\\.
  4228. The general parameters :skip and :skipcols have already been applied when
  4229. this function is called."
  4230. (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
  4231. org-table-last-alignment ""))
  4232. (params2
  4233. (list
  4234. :tstart (concat "\\begin{tabular}{" alignment "}")
  4235. :tend "\\end{tabular}"
  4236. :lstart "" :lend " \\\\" :sep " & "
  4237. :efmt "%s\\,(%s)" :hline "\\hline")))
  4238. (orgtbl-to-generic table (org-combine-plists params2 params))))
  4239. (defun orgtbl-to-html (table params)
  4240. "Convert the orgtbl-mode TABLE to HTML.
  4241. TABLE is a list, each entry either the symbol `hline' for a horizontal
  4242. separator line, or a list of fields for that line.
  4243. PARAMS is a property list of parameters that can influence the conversion.
  4244. Currently this function recognizes the following parameters:
  4245. :splice When set to t, return only table body lines, don't wrap
  4246. them into a <table> environment. Default is nil.
  4247. The general parameters :skip and :skipcols have already been applied when
  4248. this function is called. The function does *not* use `orgtbl-to-generic',
  4249. so you cannot specify parameters for it."
  4250. (let* ((splicep (plist-get params :splice))
  4251. (html-table-tag org-export-html-table-tag)
  4252. html)
  4253. ;; Just call the formatter we already have
  4254. ;; We need to make text lines for it, so put the fields back together.
  4255. (setq html (org-format-org-table-html
  4256. (mapcar
  4257. (lambda (x)
  4258. (if (eq x 'hline)
  4259. "|----+----|"
  4260. (concat "| " (mapconcat 'org-html-expand x " | ") " |")))
  4261. table)
  4262. splicep))
  4263. (if (string-match "\n+\\'" html)
  4264. (setq html (replace-match "" t t html)))
  4265. html))
  4266. (defun orgtbl-to-texinfo (table params)
  4267. "Convert the orgtbl-mode TABLE to TeXInfo.
  4268. TABLE is a list, each entry either the symbol `hline' for a horizontal
  4269. separator line, or a list of fields for that line.
  4270. PARAMS is a property list of parameters that can influence the conversion.
  4271. Supports all parameters from `orgtbl-to-generic'. Most important for
  4272. TeXInfo are:
  4273. :splice nil/t When set to t, return only table body lines, don't wrap
  4274. them into a multitable environment. Default is nil.
  4275. :fmt fmt A format to be used to wrap the field, should contain
  4276. %s for the original field value. For example, to wrap
  4277. everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
  4278. This may also be a property list with column numbers and
  4279. formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
  4280. Each format also may be a function that formats its one
  4281. argument.
  4282. :cf \"f1 f2..\" The column fractions for the table. By default these
  4283. are computed automatically from the width of the columns
  4284. under org-mode.
  4285. The general parameters :skip and :skipcols have already been applied when
  4286. this function is called."
  4287. (let* ((total (float (apply '+ org-table-last-column-widths)))
  4288. (colfrac (or (plist-get params :cf)
  4289. (mapconcat
  4290. (lambda (x) (format "%.3f" (/ (float x) total)))
  4291. org-table-last-column-widths " ")))
  4292. (params2
  4293. (list
  4294. :tstart (concat "@multitable @columnfractions " colfrac)
  4295. :tend "@end multitable"
  4296. :lstart "@item " :lend "" :sep " @tab "
  4297. :hlstart "@headitem ")))
  4298. (orgtbl-to-generic table (org-combine-plists params2 params))))
  4299. (defun orgtbl-to-orgtbl (table params)
  4300. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  4301. Useful when slicing one table into many. The :hline, :sep,
  4302. :lstart, and :lend provide orgtbl framing. The default nil :tstart
  4303. and :tend suppress strings without splicing; they can be set to
  4304. provide ORGTBL directives for the generated table."
  4305. (let* ((params2
  4306. (list
  4307. :remove-newlines t
  4308. :tstart nil :tend nil
  4309. :hline "|---"
  4310. :sep " | "
  4311. :lstart "| "
  4312. :lend " |"))
  4313. (params (org-combine-plists params2 params)))
  4314. (orgtbl-to-generic table params)))
  4315. (defun org-table-get-remote-range (name-or-id form)
  4316. "Get a field value or a list of values in a range from table at ID.
  4317. NAME-OR-ID may be the name of a table in the current file as set by
  4318. a \"#+TBLNAME:\" directive. The first table following this line
  4319. will then be used. Alternatively, it may be an ID referring to
  4320. any entry, also in a different file. In this case, the first table
  4321. in that entry will be referenced.
  4322. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  4323. \"@I$2..@II$2\". All the references must be absolute, not relative.
  4324. The return value is either a single string for a single field, or a
  4325. list of the fields in the rectangle ."
  4326. (save-match-data
  4327. (let ((id-loc nil)
  4328. org-table-column-names org-table-column-name-regexp
  4329. org-table-local-parameters org-table-named-field-locations
  4330. org-table-current-line-types org-table-current-begin-line
  4331. org-table-current-begin-pos org-table-dlines
  4332. org-table-current-ncol
  4333. org-table-hlines org-table-last-alignment
  4334. org-table-last-column-widths org-table-last-alignment
  4335. org-table-last-column-widths tbeg
  4336. buffer loc)
  4337. (setq form (org-table-convert-refs-to-rc form))
  4338. (save-excursion
  4339. (save-restriction
  4340. (widen)
  4341. (save-excursion
  4342. (goto-char (point-min))
  4343. (if (re-search-forward
  4344. (concat "^[ \t]*#\\+TBLNAME:[ \t]*" (regexp-quote name-or-id) "[ \t]*$")
  4345. nil t)
  4346. (setq buffer (current-buffer) loc (match-beginning 0))
  4347. (setq id-loc (org-id-find name-or-id 'marker))
  4348. (unless (and id-loc (markerp id-loc))
  4349. (error "Can't find remote table \"%s\"" name-or-id))
  4350. (setq buffer (marker-buffer id-loc)
  4351. loc (marker-position id-loc))
  4352. (move-marker id-loc nil)))
  4353. (with-current-buffer buffer
  4354. (save-excursion
  4355. (save-restriction
  4356. (widen)
  4357. (goto-char loc)
  4358. (forward-char 1)
  4359. (unless (and (re-search-forward "^\\(\\*+ \\)\\|[ \t]*|" nil t)
  4360. (not (match-beginning 1)))
  4361. (error "Cannot find a table at NAME or ID %s" name-or-id))
  4362. (setq tbeg (point-at-bol))
  4363. (org-table-get-specials)
  4364. (setq form (org-table-formula-substitute-names form))
  4365. (if (and (string-match org-table-range-regexp form)
  4366. (> (length (match-string 0 form)) 1))
  4367. (save-match-data
  4368. (org-table-get-range (match-string 0 form) tbeg 1))
  4369. form)))))))))
  4370. (provide 'org-table)
  4371. ;; arch-tag: 4d21cfdd-0268-440a-84b0-09237a0fe0ef
  4372. ;;; org-table.el ends here