org-table.el 194 KB

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