org-table.el 182 KB

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