org-table.el 180 KB

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