org-table.el 180 KB

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