org-table.el 199 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351
  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 org-export-create-backend "ox")
  35. (declare-function org-export-get-backend "ox" (name))
  36. (declare-function calc-eval "calc" (str &optional separator &rest args))
  37. (defvar orgtbl-mode) ; defined below
  38. (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
  39. (defvar constants-unit-system)
  40. (defvar org-table-follow-field-mode)
  41. (defvar orgtbl-after-send-table-hook nil
  42. "Hook for functions attaching to `C-c C-c', if the table is sent.
  43. This can be used to add additional functionality after the table is sent
  44. to the receiver position, otherwise, if table is not sent, the functions
  45. are not run.")
  46. (defvar org-table-TBLFM-begin-regexp "|\n[ \t]*#\\+TBLFM: ")
  47. (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
  48. "Non-nil means use the optimized table editor version for `orgtbl-mode'.
  49. In the optimized version, the table editor takes over all simple keys that
  50. normally just insert a character. In tables, the characters are inserted
  51. in a way to minimize disturbing the table structure (i.e. in overwrite mode
  52. for empty fields). Outside tables, the correct binding of the keys is
  53. restored.
  54. The default for this option is t if the optimized version is also used in
  55. Org-mode. See the variable `org-enable-table-editor' for details. Changing
  56. this variable requires a restart of Emacs to become effective."
  57. :group 'org-table
  58. :type 'boolean)
  59. (defcustom orgtbl-radio-table-templates
  60. '((latex-mode "% BEGIN RECEIVE ORGTBL %n
  61. % END RECEIVE ORGTBL %n
  62. \\begin{comment}
  63. #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
  64. | | |
  65. \\end{comment}\n")
  66. (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
  67. @c END RECEIVE ORGTBL %n
  68. @ignore
  69. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  70. | | |
  71. @end ignore\n")
  72. (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
  73. <!-- END RECEIVE ORGTBL %n -->
  74. <!--
  75. #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
  76. | | |
  77. -->\n")
  78. (org-mode "#+ BEGIN RECEIVE ORGTBL %n
  79. #+ END RECEIVE ORGTBL %n
  80. #+ORGTBL: SEND %n orgtbl-to-orgtbl :splice nil :skip 0
  81. | | |
  82. "))
  83. "Templates for radio tables in different major modes.
  84. Each template must define lines that will be treated as a comment and that
  85. must contain the \"BEGIN RECEIVE ORGTBL %n\" and \"END RECEIVE ORGTBL\"
  86. lines where \"%n\" will be replaced with the name of the table during
  87. insertion of the template. The transformed table will later be inserted
  88. between these lines.
  89. The template should also contain a minimal table in a multiline comment.
  90. If multiline comments are not possible in the buffer language,
  91. you can pack it into a string that will not be used when the code
  92. is compiled or executed. Above the table will you need a line with
  93. the fixed string \"#+ORGTBL: SEND\", followed by instruction on how to
  94. convert the table into a data structure useful in the
  95. language of the buffer. Check the manual for the section on
  96. \"Translator functions\", and more generally check out
  97. http://orgmode.org/manual/Tables-in-arbitrary-syntax.html#Tables-in-arbitrary-syntax
  98. All occurrences of %n in a template will be replaced with the name of the
  99. table, obtained by prompting the user."
  100. :group 'org-table
  101. :type '(repeat
  102. (list (symbol :tag "Major mode")
  103. (string :tag "Format"))))
  104. (defgroup org-table-settings nil
  105. "Settings for tables in Org-mode."
  106. :tag "Org Table Settings"
  107. :group 'org-table)
  108. (defcustom org-table-default-size "5x2"
  109. "The default size for newly created tables, Columns x Rows."
  110. :group 'org-table-settings
  111. :type 'string)
  112. (defcustom org-table-number-regexp
  113. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$"
  114. "Regular expression for recognizing numbers in table columns.
  115. If a table column contains mostly numbers, it will be aligned to the
  116. right. If not, it will be aligned to the left.
  117. The default value of this option is a regular expression which allows
  118. anything which looks remotely like a number as used in scientific
  119. context. For example, all of the following will be considered a
  120. number:
  121. 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
  122. Other options offered by the customize interface are more restrictive."
  123. :group 'org-table-settings
  124. :type '(choice
  125. (const :tag "Positive Integers"
  126. "^[0-9]+$")
  127. (const :tag "Integers"
  128. "^[-+]?[0-9]+$")
  129. (const :tag "Floating Point Numbers"
  130. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
  131. (const :tag "Floating Point Number or Integer"
  132. "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
  133. (const :tag "Exponential, Floating point, Integer"
  134. "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
  135. (const :tag "Very General Number-Like, including hex and Calc radix"
  136. "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  137. (const :tag "Very General Number-Like, including hex and Calc radix, allows comma as decimal mark"
  138. "^\\([<>]?[-+^.,0-9]*[0-9][-+^.0-9eEdDx()%]*\\|[<>]?[-+]?0[xX][0-9a-fA-F.]+\\|[<>]?[-+]?[0-9]+#[0-9a-zA-Z.]+\\|nan\\|[-+u]?inf\\)$")
  139. (string :tag "Regexp:")))
  140. (defcustom org-table-number-fraction 0.5
  141. "Fraction of numbers in a column required to make the column align right.
  142. In a column all non-white fields are considered. If at least
  143. this fraction of fields is matched by `org-table-number-regexp',
  144. alignment to the right border applies."
  145. :group 'org-table-settings
  146. :type 'number)
  147. (defgroup org-table-editing nil
  148. "Behavior of tables during editing in Org-mode."
  149. :tag "Org Table Editing"
  150. :group 'org-table)
  151. (defcustom org-table-automatic-realign t
  152. "Non-nil means automatically re-align table when pressing TAB or RETURN.
  153. When nil, aligning is only done with \\[org-table-align], or after column
  154. removal/insertion."
  155. :group 'org-table-editing
  156. :type 'boolean)
  157. (defcustom org-table-auto-blank-field t
  158. "Non-nil means automatically blank table field when starting to type into it.
  159. This only happens when typing immediately after a field motion
  160. command (TAB, S-TAB or RET).
  161. Only relevant when `org-enable-table-editor' is equal to `optimized'."
  162. :group 'org-table-editing
  163. :type 'boolean)
  164. (defcustom org-table-exit-follow-field-mode-when-leaving-table t
  165. "Non-nil means automatically exit the follow mode.
  166. When nil, the follow mode will stay on and be active in any table
  167. the cursor enters. Since the table follow filed mode messes with the
  168. window configuration, it is not recommended to set this variable to nil,
  169. except maybe locally in a special file that has mostly tables with long
  170. fields."
  171. :group 'org-table
  172. :version "24.1"
  173. :type 'boolean)
  174. (defcustom org-table-fix-formulas-confirm nil
  175. "Whether the user should confirm when Org fixes formulas."
  176. :group 'org-table-editing
  177. :version "24.1"
  178. :type '(choice
  179. (const :tag "with yes-or-no" yes-or-no-p)
  180. (const :tag "with y-or-n" y-or-n-p)
  181. (const :tag "no confirmation" nil)))
  182. (put 'org-table-fix-formulas-confirm
  183. 'safe-local-variable
  184. #'(lambda (x) (member x '(yes-or-no-p y-or-n-p))))
  185. (defcustom org-table-tab-jumps-over-hlines t
  186. "Non-nil means tab in the last column of a table with jump over a hline.
  187. If a horizontal separator line is following the current line,
  188. `org-table-next-field' can either create a new row before that line, or jump
  189. over the line. When this option is nil, a new line will be created before
  190. this line."
  191. :group 'org-table-editing
  192. :type 'boolean)
  193. (defgroup org-table-calculation nil
  194. "Options concerning tables in Org-mode."
  195. :tag "Org Table Calculation"
  196. :group 'org-table)
  197. (defcustom org-table-use-standard-references 'from
  198. "Should org-mode work with table references like B3 instead of @3$2?
  199. Possible values are:
  200. nil never use them
  201. from accept as input, do not present for editing
  202. t accept as input and present for editing"
  203. :group 'org-table-calculation
  204. :type '(choice
  205. (const :tag "Never, don't even check user input for them" nil)
  206. (const :tag "Always, both as user input, and when editing" t)
  207. (const :tag "Convert user input, don't offer during editing" from)))
  208. (defcustom org-table-copy-increment t
  209. "Non-nil means increment when copying current field with \\[org-table-copy-down]."
  210. :group 'org-table-calculation
  211. :version "25.1"
  212. :package-version '(Org . "8.3")
  213. :type '(choice
  214. (const :tag "Use the difference between the current and the above fields" t)
  215. (integer :tag "Use a number" 1)
  216. (const :tag "Don't increment the value when copying a field" nil)))
  217. (defcustom org-calc-default-modes
  218. '(calc-internal-prec 12
  219. calc-float-format (float 8)
  220. calc-angle-mode deg
  221. calc-prefer-frac nil
  222. calc-symbolic-mode nil
  223. calc-date-format (YYYY "-" MM "-" DD " " Www (" " hh ":" mm))
  224. calc-display-working-message t
  225. )
  226. "List with Calc mode settings for use in `calc-eval' for table formulas.
  227. The list must contain alternating symbols (Calc modes variables and values).
  228. Don't remove any of the default settings, just change the values. Org-mode
  229. relies on the variables to be present in the list."
  230. :group 'org-table-calculation
  231. :type 'plist)
  232. (defcustom org-table-duration-custom-format 'hours
  233. "Format for the output of calc computations like $1+$2;t.
  234. The default value is 'hours, and will output the results as a
  235. number of hours. Other allowed values are 'seconds, 'minutes and
  236. 'days, and the output will be a fraction of seconds, minutes or
  237. days."
  238. :group 'org-table-calculation
  239. :version "24.1"
  240. :type '(choice (symbol :tag "Seconds" 'seconds)
  241. (symbol :tag "Minutes" 'minutes)
  242. (symbol :tag "Hours " 'hours)
  243. (symbol :tag "Days " 'days)))
  244. (defcustom org-table-formula-field-format "%s"
  245. "Format for fields which contain the result of a formula.
  246. For example, using \"~%s~\" will display the result within tilde
  247. characters. Beware that modifying the display can prevent the
  248. field from being used in another formula."
  249. :group 'org-table-settings
  250. :version "24.1"
  251. :type 'string)
  252. (defcustom org-table-formula-evaluate-inline t
  253. "Non-nil means TAB and RET evaluate a formula in current table field.
  254. If the current field starts with an equal sign, it is assumed to be a formula
  255. which should be evaluated as described in the manual and in the documentation
  256. string of the command `org-table-eval-formula'. This feature requires the
  257. Emacs calc package.
  258. When this variable is nil, formula calculation is only available through
  259. the command \\[org-table-eval-formula]."
  260. :group 'org-table-calculation
  261. :type 'boolean)
  262. (defcustom org-table-formula-use-constants t
  263. "Non-nil means interpret constants in formulas in tables.
  264. A constant looks like `$c' or `$Grav' and will be replaced before evaluation
  265. by the value given in `org-table-formula-constants', or by a value obtained
  266. from the `constants.el' package."
  267. :group 'org-table-calculation
  268. :type 'boolean)
  269. (defcustom org-table-formula-constants nil
  270. "Alist with constant names and values, for use in table formulas.
  271. The car of each element is a name of a constant, without the `$' before it.
  272. The cdr is the value as a string. For example, if you'd like to use the
  273. speed of light in a formula, you would configure
  274. (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
  275. and then use it in an equation like `$1*$c'.
  276. Constants can also be defined on a per-file basis using a line like
  277. #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
  278. :group 'org-table-calculation
  279. :type '(repeat
  280. (cons (string :tag "name")
  281. (string :tag "value"))))
  282. (defcustom org-table-allow-automatic-line-recalculation t
  283. "Non-nil means lines marked with |#| or |*| will be recomputed automatically.
  284. Automatically means when TAB or RET or C-c C-c are pressed in the line."
  285. :group 'org-table-calculation
  286. :type 'boolean)
  287. (defcustom org-table-error-on-row-ref-crossing-hline t
  288. "OBSOLETE VARIABLE, please see `org-table-relative-ref-may-cross-hline'."
  289. :group 'org-table
  290. :type 'boolean)
  291. (defcustom org-table-relative-ref-may-cross-hline t
  292. "Non-nil means relative formula references may cross hlines.
  293. Here are the allowed values:
  294. nil Relative references may not cross hlines. They will reference the
  295. field next to the hline instead. Coming from below, the reference
  296. will be to the field below the hline. Coming from above, it will be
  297. to the field above.
  298. t Relative references may cross hlines.
  299. error An attempt to cross a hline will throw an error.
  300. It is probably good to never set this variable to nil, for the sake of
  301. portability of tables."
  302. :group 'org-table-calculation
  303. :type '(choice
  304. (const :tag "Allow to cross" t)
  305. (const :tag "Stick to hline" nil)
  306. (const :tag "Error on attempt to cross" error)))
  307. (defcustom org-table-formula-create-columns nil
  308. "Non-nil means that evaluation of a field formula can add new
  309. columns if an out-of-bounds field is being set."
  310. :group 'org-table-calculation
  311. :version "25.1"
  312. :package-version '(Org . "8.3")
  313. :type '(choice
  314. (const :tag "Setting an out-of-bounds field generates an error (default)" nil)
  315. (const :tag "Setting an out-of-bounds field silently adds columns as needed" t)
  316. (const :tag "Setting an out-of-bounds field adds columns as needed, but issues a warning message" warn)
  317. (const :tag "When setting an out-of-bounds field, the user is prompted" prompt)))
  318. (defgroup org-table-import-export nil
  319. "Options concerning table import and export in Org-mode."
  320. :tag "Org Table Import Export"
  321. :group 'org-table)
  322. (defcustom org-table-export-default-format "orgtbl-to-tsv"
  323. "Default export parameters for `org-table-export'.
  324. These can be overridden for a specific table by setting the
  325. TABLE_EXPORT_FORMAT property. See the manual section on orgtbl
  326. radio tables for the different export transformations and
  327. available parameters."
  328. :group 'org-table-import-export
  329. :type 'string)
  330. (defcustom org-table-convert-region-max-lines 999
  331. "Max lines that `org-table-convert-region' will attempt to process.
  332. The function can be slow on larger regions; this safety feature
  333. prevents it from hanging emacs."
  334. :group 'org-table-import-export
  335. :type 'integer
  336. :version "25.1"
  337. :package-version '(Org . "8.3"))
  338. (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
  339. "Detects a table line marked for automatic recalculation.")
  340. (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
  341. "Detects a table line marked for automatic recalculation.")
  342. (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
  343. "Detects a table line marked for automatic recalculation.")
  344. (defconst org-table-border-regexp "^[ \t]*[^| \t]"
  345. "Searching from within a table (any type) this finds the first line outside the table.")
  346. (defvar org-table-last-highlighted-reference nil)
  347. (defvar org-table-formula-history nil)
  348. (defvar org-table-column-names nil
  349. "Alist with column names, derived from the `!' line.")
  350. (defvar org-table-column-name-regexp nil
  351. "Regular expression matching the current column names.")
  352. (defvar org-table-local-parameters nil
  353. "Alist with parameter names, derived from the `$' line.")
  354. (defvar org-table-named-field-locations nil
  355. "Alist with locations of named fields.")
  356. (defvar org-table-current-line-types nil
  357. "Table row types, non-nil only for the duration of a command.")
  358. (defvar org-table-current-begin-line nil
  359. "Table begin line, non-nil only for the duration of a command.")
  360. (defvar org-table-current-begin-pos nil
  361. "Table begin position, non-nil only for the duration of a command.")
  362. (defvar org-table-current-ncol nil
  363. "Number of columns in table, non-nil only for the duration of a command.")
  364. (defvar org-table-dlines nil
  365. "Vector of data line line numbers in the current table.")
  366. (defvar org-table-hlines nil
  367. "Vector of hline line numbers in the current table.")
  368. (defconst org-table-range-regexp
  369. "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
  370. ;; 1 2 3 4 5
  371. "Regular expression for matching ranges in formulas.")
  372. (defconst org-table-range-regexp2
  373. (concat
  374. "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
  375. "\\.\\."
  376. "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
  377. "Match a range for reference display.")
  378. (defun org-table-colgroup-line-p (line)
  379. "Is this a table line colgroup information?"
  380. (save-match-data
  381. (and (string-match "[<>]\\|&[lg]t;" line)
  382. (string-match "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lgt&;]+\\)\\'"
  383. line)
  384. (not (delq
  385. nil
  386. (mapcar
  387. (lambda (s)
  388. (not (member s '("" "<" ">" "<>" "&lt;" "&gt;" "&lt;&gt;"))))
  389. (org-split-string (match-string 1 line) "[ \t]*|[ \t]*")))))))
  390. (defun org-table-cookie-line-p (line)
  391. "Is this a table line with only alignment/width cookies?"
  392. (save-match-data
  393. (and (string-match "[<>]\\|&[lg]t;" line)
  394. (or (string-match
  395. "\\`[ \t]*|[ \t]*/[ \t]*\\(|[ \t<>0-9|lrcgt&;]+\\)\\'" line)
  396. (string-match "\\(\\`[ \t<>lrc0-9|gt&;]+\\'\\)" line))
  397. (not (delq nil (mapcar
  398. (lambda (s)
  399. (not (or (equal s "")
  400. (string-match
  401. "\\`<\\([lrc]?[0-9]+\\|[lrc]\\)>\\'" s)
  402. (string-match
  403. "\\`&lt;\\([lrc]?[0-9]+\\|[lrc]\\)&gt;\\'"
  404. s))))
  405. (org-split-string (match-string 1 line)
  406. "[ \t]*|[ \t]*")))))))
  407. (defconst org-table-translate-regexp
  408. (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
  409. "Match a reference that needs translation, for reference display.")
  410. ;;;###autoload
  411. (defun org-table-create-with-table.el ()
  412. "Use the table.el package to insert a new table.
  413. If there is already a table at point, convert between Org-mode tables
  414. and table.el tables."
  415. (interactive)
  416. (require 'table)
  417. (cond
  418. ((org-at-table.el-p)
  419. (if (y-or-n-p "Convert table to Org-mode table? ")
  420. (org-table-convert)))
  421. ((org-at-table-p)
  422. (when (y-or-n-p "Convert table to table.el table? ")
  423. (org-table-align)
  424. (org-table-convert)))
  425. (t (call-interactively 'table-insert))))
  426. ;;;###autoload
  427. (defun org-table-create-or-convert-from-region (arg)
  428. "Convert region to table, or create an empty table.
  429. If there is an active region, convert it to a table, using the function
  430. `org-table-convert-region'. See the documentation of that function
  431. to learn how the prefix argument is interpreted to determine the field
  432. separator.
  433. If there is no such region, create an empty table with `org-table-create'."
  434. (interactive "P")
  435. (if (org-region-active-p)
  436. (org-table-convert-region (region-beginning) (region-end) arg)
  437. (org-table-create arg)))
  438. ;;;###autoload
  439. (defun org-table-create (&optional size)
  440. "Query for a size and insert a table skeleton.
  441. SIZE is a string Columns x Rows like for example \"3x2\"."
  442. (interactive "P")
  443. (unless size
  444. (setq size (read-string
  445. (concat "Table size Columns x Rows [e.g. "
  446. org-table-default-size "]: ")
  447. "" nil org-table-default-size)))
  448. (let* ((pos (point))
  449. (indent (make-string (current-column) ?\ ))
  450. (split (org-split-string size " *x *"))
  451. (rows (string-to-number (nth 1 split)))
  452. (columns (string-to-number (car split)))
  453. (line (concat (apply 'concat indent "|" (make-list columns " |"))
  454. "\n")))
  455. (if (string-match "^[ \t]*$" (buffer-substring-no-properties
  456. (point-at-bol) (point)))
  457. (beginning-of-line 1)
  458. (newline))
  459. ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
  460. (dotimes (i rows) (insert line))
  461. (goto-char pos)
  462. (if (> rows 1)
  463. ;; Insert a hline after the first row.
  464. (progn
  465. (end-of-line 1)
  466. (insert "\n|-")
  467. (goto-char pos)))
  468. (org-table-align)))
  469. ;;;###autoload
  470. (defun org-table-convert-region (beg0 end0 &optional separator)
  471. "Convert region to a table.
  472. The region goes from BEG0 to END0, but these borders will be moved
  473. slightly, to make sure a beginning of line in the first line is included.
  474. SEPARATOR specifies the field separator in the lines. It can have the
  475. following values:
  476. '(4) Use the comma as a field separator
  477. '(16) Use a TAB as field separator
  478. '(64) Prompt for a regular expression as field separator
  479. integer When a number, use that many spaces as field separator
  480. regexp When a regular expression, use it to match the separator
  481. nil When nil, the command tries to be smart and figure out the
  482. separator in the following way:
  483. - when each line contains a TAB, assume TAB-separated material
  484. - when each line contains a comma, assume CSV material
  485. - else, assume one or more SPACE characters as separator."
  486. (interactive "r\nP")
  487. (let* ((beg (min beg0 end0))
  488. (end (max beg0 end0))
  489. re)
  490. (if (> (count-lines beg end) org-table-convert-region-max-lines)
  491. (user-error "Region is longer than `org-table-convert-region-max-lines' (%s) lines; not converting"
  492. org-table-convert-region-max-lines)
  493. (if (equal separator '(64))
  494. (setq separator (read-regexp "Regexp for field separator")))
  495. (goto-char beg)
  496. (beginning-of-line 1)
  497. (setq beg (point-marker))
  498. (goto-char end)
  499. (if (bolp) (backward-char 1) (end-of-line 1))
  500. (setq end (point-marker))
  501. ;; Get the right field separator
  502. (unless separator
  503. (goto-char beg)
  504. (setq separator
  505. (cond
  506. ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
  507. ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
  508. (t 1))))
  509. (goto-char beg)
  510. (if (equal separator '(4))
  511. (while (< (point) end)
  512. ;; parse the csv stuff
  513. (cond
  514. ((looking-at "^") (insert "| "))
  515. ((looking-at "[ \t]*$") (replace-match " |") (beginning-of-line 2))
  516. ((looking-at "[ \t]*\"\\([^\"\n]*\\)\"")
  517. (replace-match "\\1")
  518. (if (looking-at "\"") (insert "\"")))
  519. ((looking-at "[^,\n]+") (goto-char (match-end 0)))
  520. ((looking-at "[ \t]*,") (replace-match " | "))
  521. (t (beginning-of-line 2))))
  522. (setq re (cond
  523. ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
  524. ((equal separator '(16)) "^\\|\t")
  525. ((integerp separator)
  526. (if (< separator 1)
  527. (user-error "Number of spaces in separator must be >= 1")
  528. (format "^ *\\| *\t *\\| \\{%d,\\}" separator)))
  529. ((stringp separator)
  530. (format "^ *\\|%s" separator))
  531. (t (error "This should not happen"))))
  532. (while (re-search-forward re end t)
  533. (replace-match "| " t t)))
  534. (goto-char beg)
  535. (org-table-align))))
  536. ;;;###autoload
  537. (defun org-table-import (file arg)
  538. "Import FILE as a table.
  539. The file is assumed to be tab-separated. Such files can be produced by most
  540. spreadsheet and database applications. If no tabs (at least one per line)
  541. are found, lines will be split on whitespace into fields."
  542. (interactive "f\nP")
  543. (or (bolp) (newline))
  544. (let ((beg (point))
  545. (pm (point-max)))
  546. (insert-file-contents file)
  547. (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
  548. ;;;###autoload
  549. (defun org-table-export (&optional file format)
  550. "Export table to a file, with configurable format.
  551. Such a file can be imported into usual spreadsheet programs.
  552. FILE can be the output file name. If not given, it will be taken
  553. from a TABLE_EXPORT_FILE property in the current entry or higher
  554. up in the hierarchy, or the user will be prompted for a file
  555. name. FORMAT can be an export format, of the same kind as it
  556. used when `orgtbl-mode' sends a table in a different format.
  557. The command suggests a format depending on TABLE_EXPORT_FORMAT,
  558. whether it is set locally or up in the hierarchy, then on the
  559. extension of the given file name, and finally on the variable
  560. `org-table-export-default-format'."
  561. (interactive)
  562. (unless (org-at-table-p) (user-error "No table at point"))
  563. (org-table-align) ; Make sure we have everything we need.
  564. (let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
  565. (unless file
  566. (setq file (read-file-name "Export table to: "))
  567. (unless (or (not (file-exists-p file))
  568. (y-or-n-p (format "Overwrite file %s? " file)))
  569. (user-error "File not written")))
  570. (when (file-directory-p file)
  571. (user-error "This is a directory path, not a file"))
  572. (when (and (buffer-file-name (buffer-base-buffer))
  573. (org-file-equal-p
  574. (file-truename file)
  575. (file-truename (buffer-file-name (buffer-base-buffer)))))
  576. (user-error "Please specify a file name that is different from current"))
  577. (let ((fileext (concat (file-name-extension file) "$"))
  578. (format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
  579. (unless format
  580. (let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
  581. "orgtbl-to-html" "orgtbl-to-generic"
  582. "orgtbl-to-texinfo" "orgtbl-to-orgtbl"
  583. "orgtbl-to-unicode"))
  584. (deffmt-readable
  585. (replace-regexp-in-string
  586. "\t" "\\t"
  587. (replace-regexp-in-string
  588. "\n" "\\n"
  589. (or (car (delq nil
  590. (mapcar
  591. (lambda (f)
  592. (and (org-string-match-p fileext f) f))
  593. formats)))
  594. org-table-export-default-format)
  595. t t) t t)))
  596. (setq format
  597. (org-completing-read
  598. "Format: " formats nil nil deffmt-readable))))
  599. (if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
  600. (let ((transform (intern (match-string 1 format)))
  601. (params (and (match-end 2)
  602. (read (concat "(" (match-string 2 format) ")"))))
  603. (table (org-table-to-lisp
  604. (buffer-substring-no-properties
  605. (org-table-begin) (org-table-end)))))
  606. (unless (fboundp transform)
  607. (user-error "No such transformation function %s" transform))
  608. (let (buf)
  609. (with-current-buffer (find-file-noselect file)
  610. (setq buf (current-buffer))
  611. (erase-buffer)
  612. (fundamental-mode)
  613. (insert (funcall transform table params) "\n")
  614. (save-buffer))
  615. (kill-buffer buf))
  616. (message "Export done."))
  617. (user-error "TABLE_EXPORT_FORMAT invalid")))))
  618. (defvar org-table-aligned-begin-marker (make-marker)
  619. "Marker at the beginning of the table last aligned.
  620. Used to check if cursor still is in that table, to minimize realignment.")
  621. (defvar org-table-aligned-end-marker (make-marker)
  622. "Marker at the end of the table last aligned.
  623. Used to check if cursor still is in that table, to minimize realignment.")
  624. (defvar org-table-last-alignment nil
  625. "List of flags for flushright alignment, from the last re-alignment.
  626. This is being used to correctly align a single field after TAB or RET.")
  627. (defvar org-table-last-column-widths nil
  628. "List of max width of fields in each column.
  629. This is being used to correctly align a single field after TAB or RET.")
  630. (defvar org-table-formula-debug nil
  631. "Non-nil means debug table formulas.
  632. When nil, simply write \"#ERROR\" in corrupted fields.")
  633. (make-variable-buffer-local 'org-table-formula-debug)
  634. (defvar org-table-overlay-coordinates nil
  635. "Overlay coordinates after each align of a table.")
  636. (make-variable-buffer-local 'org-table-overlay-coordinates)
  637. (defvar org-last-recalc-line nil)
  638. (defvar org-table-do-narrow t) ; for dynamic scoping
  639. (defconst org-narrow-column-arrow "=>"
  640. "Used as display property in narrowed table columns.")
  641. ;;;###autoload
  642. (defun org-table-align ()
  643. "Align the table at point by aligning all vertical bars."
  644. (interactive)
  645. (let* (
  646. ;; Limits of table
  647. (beg (org-table-begin))
  648. (end (org-table-end))
  649. ;; Current cursor position
  650. (linepos (org-current-line))
  651. (colpos (org-table-current-column))
  652. (winstart (window-start))
  653. (winstartline (org-current-line (min winstart (1- (point-max)))))
  654. lines (new "") lengths l typenums ty fields maxfields i
  655. column
  656. (indent "") cnt frac
  657. rfmt hfmt
  658. (spaces '(1 . 1))
  659. (sp1 (car spaces))
  660. (sp2 (cdr spaces))
  661. (rfmt1 (concat
  662. (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
  663. (hfmt1 (concat
  664. (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
  665. emptystrings links dates emph raise narrow
  666. falign falign1 fmax f1 f2 len c e space)
  667. (untabify beg end)
  668. (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
  669. ;; Check if we have links or dates
  670. (goto-char beg)
  671. (setq links (re-search-forward org-bracket-link-regexp end t))
  672. (goto-char beg)
  673. (setq emph (and org-hide-emphasis-markers
  674. (re-search-forward org-emph-re end t)))
  675. (goto-char beg)
  676. (setq raise (and org-use-sub-superscripts
  677. (re-search-forward org-match-substring-regexp end t)))
  678. (goto-char beg)
  679. (setq dates (and org-display-custom-times
  680. (re-search-forward org-ts-regexp-both end t)))
  681. ;; Make sure the link properties are right
  682. (when links (goto-char beg) (while (org-activate-bracket-links end)))
  683. ;; Make sure the date properties are right
  684. (when dates (goto-char beg) (while (org-activate-dates end)))
  685. (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
  686. (when raise (goto-char beg) (while (org-raise-scripts end)))
  687. ;; Check if we are narrowing any columns
  688. (goto-char beg)
  689. (setq narrow (and org-table-do-narrow
  690. org-format-transports-properties-p
  691. (re-search-forward "<[lrc]?[0-9]+>" end t)))
  692. (goto-char beg)
  693. (setq falign (re-search-forward "<[lrc][0-9]*>" end t))
  694. (goto-char beg)
  695. ;; Get the rows
  696. (setq lines (org-split-string
  697. (buffer-substring beg end) "\n"))
  698. ;; Store the indentation of the first line
  699. (if (string-match "^ *" (car lines))
  700. (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
  701. ;; Mark the hlines by setting the corresponding element to nil
  702. ;; At the same time, we remove trailing space.
  703. (setq lines (mapcar (lambda (l)
  704. (if (string-match "^ *|-" l)
  705. nil
  706. (if (string-match "[ \t]+$" l)
  707. (substring l 0 (match-beginning 0))
  708. l)))
  709. lines))
  710. ;; Get the data fields by splitting the lines.
  711. (setq fields (mapcar
  712. (lambda (l)
  713. (org-split-string l " *| *"))
  714. (delq nil (copy-sequence lines))))
  715. ;; How many fields in the longest line?
  716. (condition-case nil
  717. (setq maxfields (apply 'max (mapcar 'length fields)))
  718. (error
  719. (kill-region beg end)
  720. (org-table-create org-table-default-size)
  721. (user-error "Empty table - created default table")))
  722. ;; A list of empty strings to fill any short rows on output
  723. (setq emptystrings (make-list maxfields ""))
  724. ;; Check for special formatting.
  725. (setq i -1)
  726. (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
  727. (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
  728. ;; Check if there is an explicit width specified
  729. (setq fmax nil)
  730. (when (or narrow falign)
  731. (setq c column fmax nil falign1 nil)
  732. (while c
  733. (setq e (pop c))
  734. (when (and (stringp e) (string-match "^<\\([lrc]\\)?\\([0-9]+\\)?>$" e))
  735. (if (match-end 1) (setq falign1 (match-string 1 e)))
  736. (if (and org-table-do-narrow (match-end 2))
  737. (setq fmax (string-to-number (match-string 2 e)) c nil))))
  738. ;; Find fields that are wider than fmax, and shorten them
  739. (when fmax
  740. (loop for xx in column do
  741. (when (and (stringp xx)
  742. (> (org-string-width xx) fmax))
  743. (org-add-props xx nil
  744. 'help-echo
  745. (concat "Clipped table field, use C-c ` to edit. Full value is:\n"
  746. (org-no-properties (copy-sequence xx))))
  747. (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
  748. (unless (> f1 1)
  749. (user-error "Cannot narrow field starting with wide link \"%s\""
  750. (match-string 0 xx)))
  751. (setq f2 (length xx))
  752. (if (= (org-string-width xx)
  753. f2)
  754. (setq f2 f1)
  755. (setq f2 1)
  756. (while (< (org-string-width (substring xx 0 f2))
  757. f1)
  758. (setq f2 (1+ f2))))
  759. (add-text-properties f2 (length xx) (list 'org-cwidth t) xx)
  760. (add-text-properties (if (>= (string-width (substring xx (1- f2) f2)) 2)
  761. (1- f2) (- f2 2)) f2
  762. (list 'display org-narrow-column-arrow)
  763. xx)))))
  764. ;; Get the maximum width for each column
  765. (push (apply 'max (or fmax 1) 1 (mapcar 'org-string-width column))
  766. lengths)
  767. ;; Get the fraction of numbers, to decide about alignment of the column
  768. (if falign1
  769. (push (equal (downcase falign1) "r") typenums)
  770. (setq cnt 0 frac 0.0)
  771. (loop for x in column do
  772. (if (equal x "")
  773. nil
  774. (setq frac ( / (+ (* frac cnt)
  775. (if (string-match org-table-number-regexp x) 1 0))
  776. (setq cnt (1+ cnt))))))
  777. (push (>= frac org-table-number-fraction) typenums)))
  778. (setq lengths (nreverse lengths) typenums (nreverse typenums))
  779. ;; Store the alignment of this table, for later editing of single fields
  780. (setq org-table-last-alignment typenums
  781. org-table-last-column-widths lengths)
  782. ;; With invisible characters, `format' does not get the field width right
  783. ;; So we need to make these fields wide by hand.
  784. (when (or links emph raise)
  785. (loop for i from 0 upto (1- maxfields) do
  786. (setq len (nth i lengths))
  787. (loop for j from 0 upto (1- (length fields)) do
  788. (setq c (nthcdr i (car (nthcdr j fields))))
  789. (if (and (stringp (car c))
  790. (or (text-property-any 0 (length (car c))
  791. 'invisible 'org-link (car c))
  792. (text-property-any 0 (length (car c))
  793. 'org-dwidth t (car c)))
  794. (< (org-string-width (car c)) len))
  795. (progn
  796. (setq space (make-string (- len (org-string-width (car c))) ?\ ))
  797. (setcar c (if (nth i typenums)
  798. (concat space (car c))
  799. (concat (car c) space))))))))
  800. ;; Compute the formats needed for output of the table
  801. (setq rfmt (concat indent "|") hfmt (concat indent "|"))
  802. (while (setq l (pop lengths))
  803. (setq ty (if (pop typenums) "" "-")) ; number types flushright
  804. (setq rfmt (concat rfmt (format rfmt1 ty l))
  805. hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
  806. (setq rfmt (concat rfmt "\n")
  807. hfmt (concat (substring hfmt 0 -1) "|\n"))
  808. (setq new (mapconcat
  809. (lambda (l)
  810. (if l (apply 'format rfmt
  811. (append (pop fields) emptystrings))
  812. hfmt))
  813. lines ""))
  814. (move-marker org-table-aligned-begin-marker (point))
  815. (insert new)
  816. ;; Replace the old one
  817. (delete-region (point) end)
  818. (move-marker end nil)
  819. (move-marker org-table-aligned-end-marker (point))
  820. (when (and orgtbl-mode (not (derived-mode-p 'org-mode)))
  821. (goto-char org-table-aligned-begin-marker)
  822. (while (org-hide-wide-columns org-table-aligned-end-marker)))
  823. ;; Try to move to the old location
  824. (org-goto-line winstartline)
  825. (setq winstart (point-at-bol))
  826. (org-goto-line linepos)
  827. (when (eq (window-buffer (selected-window)) (current-buffer))
  828. (set-window-start (selected-window) winstart 'noforce))
  829. (org-table-goto-column colpos)
  830. (and org-table-overlay-coordinates (org-table-overlay-coordinates))
  831. (setq org-table-may-need-update nil)
  832. ))
  833. ;;;###autoload
  834. (defun org-table-begin (&optional table-type)
  835. "Find the beginning of the table and return its position.
  836. With argument TABLE-TYPE, go to the beginning of a table.el-type table."
  837. (save-excursion
  838. (if (not (re-search-backward
  839. (if table-type org-table-any-border-regexp
  840. org-table-border-regexp)
  841. nil t))
  842. (progn (goto-char (point-min)) (point))
  843. (goto-char (match-beginning 0))
  844. (beginning-of-line 2)
  845. (point))))
  846. ;;;###autoload
  847. (defun org-table-end (&optional table-type)
  848. "Find the end of the table and return its position.
  849. With argument TABLE-TYPE, go to the end of a table.el-type table."
  850. (save-excursion
  851. (if (not (re-search-forward
  852. (if table-type org-table-any-border-regexp
  853. org-table-border-regexp)
  854. nil t))
  855. (goto-char (point-max))
  856. (goto-char (match-beginning 0)))
  857. (point-marker)))
  858. ;;;###autoload
  859. (defun org-table-justify-field-maybe (&optional new)
  860. "Justify the current field, text to left, number to right.
  861. Optional argument NEW may specify text to replace the current field content."
  862. (cond
  863. ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
  864. ((org-at-table-hline-p))
  865. ((and (not new)
  866. (or (not (equal (marker-buffer org-table-aligned-begin-marker)
  867. (current-buffer)))
  868. (< (point) org-table-aligned-begin-marker)
  869. (>= (point) org-table-aligned-end-marker)))
  870. ;; This is not the same table, force a full re-align
  871. (setq org-table-may-need-update t))
  872. (t ;; realign the current field, based on previous full realign
  873. (let* ((pos (point)) s
  874. (col (org-table-current-column))
  875. (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
  876. l f n o e)
  877. (when (> col 0)
  878. (skip-chars-backward "^|\n")
  879. (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
  880. (progn
  881. (setq s (match-string 1)
  882. o (match-string 0)
  883. l (max 1
  884. (- (org-string-width
  885. (buffer-substring-no-properties
  886. (match-end 0) (match-beginning 0))) 3))
  887. e (not (= (match-beginning 2) (match-end 2))))
  888. (setq f (format (if num " %%%ds %s" " %%-%ds %s")
  889. l (if e "|" (setq org-table-may-need-update t) ""))
  890. n (format f s))
  891. (if new
  892. (if (<= (org-string-width new) l)
  893. (setq n (format f new))
  894. (setq n (concat new "|") org-table-may-need-update t)))
  895. (if (equal (string-to-char n) ?-) (setq n (concat " " n)))
  896. (or (equal n o)
  897. (let (org-table-may-need-update)
  898. (replace-match n t t))))
  899. (setq org-table-may-need-update t))
  900. (goto-char pos))))))
  901. ;;;###autoload
  902. (defun org-table-next-field ()
  903. "Go to the next field in the current table, creating new lines as needed.
  904. Before doing so, re-align the table if necessary."
  905. (interactive)
  906. (org-table-maybe-eval-formula)
  907. (org-table-maybe-recalculate-line)
  908. (if (and org-table-automatic-realign
  909. org-table-may-need-update)
  910. (org-table-align))
  911. (let ((end (org-table-end)))
  912. (if (org-at-table-hline-p)
  913. (end-of-line 1))
  914. (condition-case nil
  915. (progn
  916. (re-search-forward "|" end)
  917. (if (looking-at "[ \t]*$")
  918. (re-search-forward "|" end))
  919. (if (and (looking-at "-")
  920. org-table-tab-jumps-over-hlines
  921. (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
  922. (goto-char (match-beginning 1)))
  923. (if (looking-at "-")
  924. (progn
  925. (beginning-of-line 0)
  926. (org-table-insert-row 'below))
  927. (if (looking-at " ") (forward-char 1))))
  928. (error
  929. (org-table-insert-row 'below)))))
  930. ;;;###autoload
  931. (defun org-table-previous-field ()
  932. "Go to the previous field in the table.
  933. Before doing so, re-align the table if necessary."
  934. (interactive)
  935. (org-table-justify-field-maybe)
  936. (org-table-maybe-recalculate-line)
  937. (if (and org-table-automatic-realign
  938. org-table-may-need-update)
  939. (org-table-align))
  940. (if (org-at-table-hline-p)
  941. (end-of-line 1))
  942. (condition-case nil
  943. (progn
  944. (re-search-backward "|" (org-table-begin))
  945. (re-search-backward "|" (org-table-begin)))
  946. (error (user-error "Cannot move to previous table field")))
  947. (while (looking-at "|\\(-\\|[ \t]*$\\)")
  948. (re-search-backward "|" (org-table-begin)))
  949. (if (looking-at "| ?")
  950. (goto-char (match-end 0))))
  951. (defun org-table-beginning-of-field (&optional n)
  952. "Move to the end of the current table field.
  953. If already at or after the end, move to the end of the next table field.
  954. With numeric argument N, move N-1 fields forward first."
  955. (interactive "p")
  956. (let ((pos (point)))
  957. (while (> n 1)
  958. (setq n (1- n))
  959. (org-table-previous-field))
  960. (if (not (re-search-backward "|" (point-at-bol 0) t))
  961. (user-error "No more table fields before the current")
  962. (goto-char (match-end 0))
  963. (and (looking-at " ") (forward-char 1)))
  964. (if (>= (point) pos) (org-table-beginning-of-field 2))))
  965. (defun org-table-end-of-field (&optional n)
  966. "Move to the beginning of the current table field.
  967. If already at or before the beginning, move to the beginning of the
  968. previous field.
  969. With numeric argument N, move N-1 fields backward first."
  970. (interactive "p")
  971. (let ((pos (point)))
  972. (while (> n 1)
  973. (setq n (1- n))
  974. (org-table-next-field))
  975. (when (re-search-forward "|" (point-at-eol 1) t)
  976. (backward-char 1)
  977. (skip-chars-backward " ")
  978. (if (and (equal (char-before (point)) ?|) (looking-at " "))
  979. (forward-char 1)))
  980. (if (<= (point) pos) (org-table-end-of-field 2))))
  981. ;;;###autoload
  982. (defun org-table-next-row ()
  983. "Go to the next row (same column) in the current table.
  984. Before doing so, re-align the table if necessary."
  985. (interactive)
  986. (org-table-maybe-eval-formula)
  987. (org-table-maybe-recalculate-line)
  988. (if (or (looking-at "[ \t]*$")
  989. (save-excursion (skip-chars-backward " \t") (bolp)))
  990. (newline)
  991. (if (and org-table-automatic-realign
  992. org-table-may-need-update)
  993. (org-table-align))
  994. (let ((col (org-table-current-column)))
  995. (beginning-of-line 2)
  996. (if (or (not (org-at-table-p))
  997. (org-at-table-hline-p))
  998. (progn
  999. (beginning-of-line 0)
  1000. (org-table-insert-row 'below)))
  1001. (org-table-goto-column col)
  1002. (skip-chars-backward "^|\n\r")
  1003. (if (looking-at " ") (forward-char 1)))))
  1004. ;;;###autoload
  1005. (defun org-table-copy-down (n)
  1006. "Copy the value of the current field one row below.
  1007. If the field at the cursor is empty, copy the content of the
  1008. nearest non-empty field above. With argument N, use the Nth
  1009. non-empty field.
  1010. If the current field is not empty, it is copied down to the next
  1011. row, and the cursor is moved with it. Therefore, repeating this
  1012. command causes the column to be filled row-by-row.
  1013. If the variable `org-table-copy-increment' is non-nil and the
  1014. field is an integer or a timestamp, it will be incremented while
  1015. copying. By default, increment by the difference between the
  1016. value in the current field and the one in the field above. To
  1017. increment using a fixed integer, set `org-table-copy-increment'
  1018. to a number. In the case of a timestamp, increment by days."
  1019. (interactive "p")
  1020. (let* ((colpos (org-table-current-column))
  1021. (col (current-column))
  1022. (field (save-excursion (org-table-get-field)))
  1023. (field-up (or (save-excursion
  1024. (org-table-get (1- (org-table-current-line))
  1025. (org-table-current-column))) ""))
  1026. (non-empty (string-match "[^ \t]" field))
  1027. (non-empty-up (string-match "[^ \t]" field-up))
  1028. (beg (org-table-begin))
  1029. (orig-n n)
  1030. txt txt-up inc)
  1031. (org-table-check-inside-data-field)
  1032. (if (not non-empty)
  1033. (save-excursion
  1034. (setq txt
  1035. (catch 'exit
  1036. (while (progn (beginning-of-line 1)
  1037. (re-search-backward org-table-dataline-regexp
  1038. beg t))
  1039. (org-table-goto-column colpos t)
  1040. (if (and (looking-at
  1041. "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
  1042. (<= (setq n (1- n)) 0))
  1043. (throw 'exit (match-string 1))))))
  1044. (setq field-up
  1045. (catch 'exit
  1046. (while (progn (beginning-of-line 1)
  1047. (re-search-backward org-table-dataline-regexp
  1048. beg t))
  1049. (org-table-goto-column colpos t)
  1050. (if (and (looking-at
  1051. "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
  1052. (<= (setq n (1- n)) 0))
  1053. (throw 'exit (match-string 1))))))
  1054. (setq non-empty-up (and field-up (string-match "[^ \t]" field-up))))
  1055. ;; Above field was not empty, go down to the next row
  1056. (setq txt (org-trim field))
  1057. (org-table-next-row)
  1058. (org-table-blank-field))
  1059. (if non-empty-up (setq txt-up (org-trim field-up)))
  1060. (setq inc (cond
  1061. ((numberp org-table-copy-increment) org-table-copy-increment)
  1062. (txt-up (cond ((and (string-match org-ts-regexp3 txt-up)
  1063. (string-match org-ts-regexp3 txt))
  1064. (- (org-time-string-to-absolute txt)
  1065. (org-time-string-to-absolute txt-up)))
  1066. ((string-match org-ts-regexp3 txt) 1)
  1067. ((string-match "^[0-9]+\\(\.[0-9]+\\)?" txt-up)
  1068. (- (string-to-number txt)
  1069. (string-to-number (match-string 0 txt-up))))
  1070. (t 1)))
  1071. (t 1)))
  1072. (if (not txt)
  1073. (user-error "No non-empty field found")
  1074. (if (and org-table-copy-increment
  1075. (not (equal orig-n 0))
  1076. (string-match "^[-+^/*0-9eE.]+$" txt)
  1077. (< (string-to-number txt) 100000000))
  1078. (setq txt (calc-eval (concat txt "+" (number-to-string inc)))))
  1079. (insert txt)
  1080. (org-move-to-column col)
  1081. (if (and org-table-copy-increment (org-at-timestamp-p t))
  1082. (org-timestamp-up-day inc)
  1083. (org-table-maybe-recalculate-line))
  1084. (org-table-align)
  1085. (org-move-to-column col))))
  1086. (defun org-table-check-inside-data-field (&optional noerror)
  1087. "Is point inside a table data field?
  1088. I.e. not on a hline or before the first or after the last column?
  1089. This actually throws an error, so it aborts the current command."
  1090. (if (or (not (org-at-table-p))
  1091. (= (org-table-current-column) 0)
  1092. (org-at-table-hline-p)
  1093. (looking-at "[ \t]*$"))
  1094. (if noerror
  1095. nil
  1096. (user-error "Not in table data field"))
  1097. t))
  1098. (defvar org-table-clip nil
  1099. "Clipboard for table regions.")
  1100. (defun org-table-get (line column)
  1101. "Get the field in table line LINE, column COLUMN.
  1102. If LINE is larger than the number of data lines in the table, the function
  1103. returns nil. However, if COLUMN is too large, we will simply return an
  1104. empty string.
  1105. If LINE is nil, use the current line.
  1106. If COLUMN is nil, use the current column."
  1107. (setq column (or column (org-table-current-column)))
  1108. (save-excursion
  1109. (and (or (not line) (org-table-goto-line line))
  1110. (org-trim (org-table-get-field column)))))
  1111. (defun org-table-put (line column value &optional align)
  1112. "Put VALUE into line LINE, column COLUMN.
  1113. When ALIGN is set, also realign the table."
  1114. (setq column (or column (org-table-current-column)))
  1115. (prog1 (save-excursion
  1116. (and (or (not line) (org-table-goto-line line))
  1117. (progn (org-table-goto-column column nil 'force) t)
  1118. (org-table-get-field column value)))
  1119. (and align (org-table-align))))
  1120. (defun org-table-current-line ()
  1121. "Return the index of the current data line."
  1122. (let ((pos (point)) (end (org-table-end)) (cnt 0))
  1123. (save-excursion
  1124. (goto-char (org-table-begin))
  1125. (while (and (re-search-forward org-table-dataline-regexp end t)
  1126. (setq cnt (1+ cnt))
  1127. (< (point-at-eol) pos))))
  1128. cnt))
  1129. (defun org-table-goto-line (N)
  1130. "Go to the Nth data line in the current table.
  1131. Return t when the line exists, nil if it does not exist."
  1132. (goto-char (org-table-begin))
  1133. (let ((end (org-table-end)) (cnt 0))
  1134. (while (and (re-search-forward org-table-dataline-regexp end t)
  1135. (< (setq cnt (1+ cnt)) N)))
  1136. (= cnt N)))
  1137. ;;;###autoload
  1138. (defun org-table-blank-field ()
  1139. "Blank the current table field or active region."
  1140. (interactive)
  1141. (org-table-check-inside-data-field)
  1142. (if (and (org-called-interactively-p 'any) (org-region-active-p))
  1143. (let (org-table-clip)
  1144. (org-table-cut-region (region-beginning) (region-end)))
  1145. (skip-chars-backward "^|")
  1146. (backward-char 1)
  1147. (if (looking-at "|[^|\n]+")
  1148. (let* ((pos (match-beginning 0))
  1149. (match (match-string 0))
  1150. (len (org-string-width match)))
  1151. (replace-match (concat "|" (make-string (1- len) ?\ )))
  1152. (goto-char (+ 2 pos))
  1153. (substring match 1)))))
  1154. (defun org-table-get-field (&optional n replace)
  1155. "Return the value of the field in column N of current row.
  1156. N defaults to current field.
  1157. If REPLACE is a string, replace field with this value. The return value
  1158. is always the old value."
  1159. (and n (org-table-goto-column n))
  1160. (skip-chars-backward "^|\n")
  1161. (backward-char 1)
  1162. (if (looking-at "|[^|\r\n]*")
  1163. (let* ((pos (match-beginning 0))
  1164. (val (buffer-substring (1+ pos) (match-end 0))))
  1165. (if replace
  1166. (replace-match (concat "|" (if (equal replace "") " " replace))
  1167. t t))
  1168. (goto-char (min (point-at-eol) (+ 2 pos)))
  1169. val)
  1170. (forward-char 1) ""))
  1171. ;;;###autoload
  1172. (defun org-table-field-info (arg)
  1173. "Show info about the current field, and highlight any reference at point."
  1174. (interactive "P")
  1175. (unless (org-at-table-p) (user-error "Not at a table"))
  1176. (org-table-get-specials)
  1177. (save-excursion
  1178. (let* ((pos (point))
  1179. (col (org-table-current-column))
  1180. (cname (car (rassoc (int-to-string col) org-table-column-names)))
  1181. (name (car (rassoc (list (org-current-line) col)
  1182. org-table-named-field-locations)))
  1183. (eql (org-table-expand-lhs-ranges
  1184. (mapcar
  1185. (lambda (e)
  1186. (cons (org-table-formula-handle-first/last-rc
  1187. (car e)) (cdr e)))
  1188. (org-table-get-stored-formulas))))
  1189. (dline (org-table-current-dline))
  1190. (ref (format "@%d$%d" dline col))
  1191. (ref1 (org-table-convert-refs-to-an ref))
  1192. (fequation (or (assoc name eql) (assoc ref eql)))
  1193. (cequation (assoc (int-to-string col) eql))
  1194. (eqn (or fequation cequation)))
  1195. (if (and eqn (get-text-property 0 :orig-eqn (car eqn)))
  1196. (setq eqn (get-text-property 0 :orig-eqn (car eqn))))
  1197. (goto-char pos)
  1198. (condition-case nil
  1199. (org-table-show-reference 'local)
  1200. (error nil))
  1201. (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
  1202. dline col
  1203. (if cname (concat " or $" cname) "")
  1204. dline col ref1
  1205. (if name (concat " or $" name) "")
  1206. ;; FIXME: formula info not correct if special table line
  1207. (if eqn
  1208. (concat ", formula: "
  1209. (org-table-formula-to-user
  1210. (concat
  1211. (if (string-match "^[$@]"(car eqn)) "" "$")
  1212. (car eqn) "=" (cdr eqn))))
  1213. "")))))
  1214. (defun org-table-current-column ()
  1215. "Find out which column we are in."
  1216. (interactive)
  1217. (if (org-called-interactively-p 'any) (org-table-check-inside-data-field))
  1218. (save-excursion
  1219. (let ((cnt 0) (pos (point)))
  1220. (beginning-of-line 1)
  1221. (while (search-forward "|" pos t)
  1222. (setq cnt (1+ cnt)))
  1223. (when (org-called-interactively-p 'interactive)
  1224. (message "In table column %d" cnt))
  1225. cnt)))
  1226. ;;;###autoload
  1227. (defun org-table-current-dline ()
  1228. "Find out what table data line we are in.
  1229. Only data lines count for this."
  1230. (interactive)
  1231. (when (org-called-interactively-p 'any)
  1232. (org-table-check-inside-data-field))
  1233. (save-excursion
  1234. (let ((cnt 0) (pos (point)))
  1235. (goto-char (org-table-begin))
  1236. (while (<= (point) pos)
  1237. (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
  1238. (beginning-of-line 2))
  1239. (when (org-called-interactively-p 'any)
  1240. (message "This is table line %d" cnt))
  1241. cnt)))
  1242. ;;;###autoload
  1243. (defun org-table-goto-column (n &optional on-delim force)
  1244. "Move the cursor to the Nth column in the current table line.
  1245. With optional argument ON-DELIM, stop with point before the left delimiter
  1246. of the field.
  1247. If there are less than N fields, just go to after the last delimiter.
  1248. However, when FORCE is non-nil, create new columns if necessary."
  1249. (interactive "p")
  1250. (beginning-of-line 1)
  1251. (when (> n 0)
  1252. (while (and (> (setq n (1- n)) -1)
  1253. (or (search-forward "|" (point-at-eol) t)
  1254. (and force
  1255. (progn (end-of-line 1)
  1256. (skip-chars-backward "^|")
  1257. (insert " | ")
  1258. t)))))
  1259. (when (and force (not (looking-at ".*|")))
  1260. (save-excursion (end-of-line 1) (insert " | ")))
  1261. (if on-delim
  1262. (backward-char 1)
  1263. (if (looking-at " ") (forward-char 1)))))
  1264. ;;;###autoload
  1265. (defun org-table-insert-column ()
  1266. "Insert a new column into the table."
  1267. (interactive)
  1268. (if (not (org-at-table-p))
  1269. (user-error "Not at a table"))
  1270. (org-table-find-dataline)
  1271. (let* ((col (max 1 (org-table-current-column)))
  1272. (beg (org-table-begin))
  1273. (end (org-table-end))
  1274. ;; Current cursor position
  1275. (linepos (org-current-line))
  1276. (colpos col))
  1277. (goto-char beg)
  1278. (while (< (point) end)
  1279. (if (org-at-table-hline-p)
  1280. nil
  1281. (org-table-goto-column col t)
  1282. (insert "| "))
  1283. (beginning-of-line 2))
  1284. (move-marker end nil)
  1285. (org-goto-line linepos)
  1286. (org-table-goto-column colpos)
  1287. (org-table-align)
  1288. (when (or (not org-table-fix-formulas-confirm)
  1289. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1290. (org-table-fix-formulas "$" nil (1- col) 1)
  1291. (org-table-fix-formulas "$LR" nil (1- col) 1))))
  1292. (defun org-table-find-dataline ()
  1293. "Find a data line in the current table, which is needed for column commands."
  1294. (if (and (org-at-table-p)
  1295. (not (org-at-table-hline-p)))
  1296. t
  1297. (let ((col (current-column))
  1298. (end (org-table-end)))
  1299. (org-move-to-column col)
  1300. (while (and (< (point) end)
  1301. (or (not (= (current-column) col))
  1302. (org-at-table-hline-p)))
  1303. (beginning-of-line 2)
  1304. (org-move-to-column col))
  1305. (if (and (org-at-table-p)
  1306. (not (org-at-table-hline-p)))
  1307. t
  1308. (user-error
  1309. "Please position cursor in a data line for column operations")))))
  1310. (defun org-table-line-to-dline (line &optional above)
  1311. "Turn a buffer line number into a data line number.
  1312. If there is no data line in this line, return nil.
  1313. If there is no matching dline (most likely te reference was a hline), the
  1314. first dline below it is used. When ABOVE is non-nil, the one above is used."
  1315. (catch 'exit
  1316. (let ((ll (length org-table-dlines))
  1317. i)
  1318. (if above
  1319. (progn
  1320. (setq i (1- ll))
  1321. (while (> i 0)
  1322. (if (<= (aref org-table-dlines i) line)
  1323. (throw 'exit i))
  1324. (setq i (1- i))))
  1325. (setq i 1)
  1326. (while (< i ll)
  1327. (if (>= (aref org-table-dlines i) line)
  1328. (throw 'exit i))
  1329. (setq i (1+ i)))))
  1330. nil))
  1331. ;;;###autoload
  1332. (defun org-table-delete-column ()
  1333. "Delete a column from the table."
  1334. (interactive)
  1335. (if (not (org-at-table-p))
  1336. (user-error "Not at a table"))
  1337. (org-table-find-dataline)
  1338. (org-table-check-inside-data-field)
  1339. (let* ((col (org-table-current-column))
  1340. (beg (org-table-begin))
  1341. (end (org-table-end))
  1342. ;; Current cursor position
  1343. (linepos (org-current-line))
  1344. (colpos col))
  1345. (goto-char beg)
  1346. (while (< (point) end)
  1347. (if (org-at-table-hline-p)
  1348. nil
  1349. (org-table-goto-column col t)
  1350. (and (looking-at "|[^|\n]+|")
  1351. (replace-match "|")))
  1352. (beginning-of-line 2))
  1353. (move-marker end nil)
  1354. (org-goto-line linepos)
  1355. (org-table-goto-column colpos)
  1356. (org-table-align)
  1357. (when (or (not org-table-fix-formulas-confirm)
  1358. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1359. (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
  1360. col -1 col)
  1361. (org-table-fix-formulas "$LR" (list (cons (number-to-string col) "INVALID"))
  1362. col -1 col))))
  1363. ;;;###autoload
  1364. (defun org-table-move-column-right ()
  1365. "Move column to the right."
  1366. (interactive)
  1367. (org-table-move-column nil))
  1368. ;;;###autoload
  1369. (defun org-table-move-column-left ()
  1370. "Move column to the left."
  1371. (interactive)
  1372. (org-table-move-column 'left))
  1373. ;;;###autoload
  1374. (defun org-table-move-column (&optional left)
  1375. "Move the current column to the right. With arg LEFT, move to the left."
  1376. (interactive "P")
  1377. (if (not (org-at-table-p))
  1378. (user-error "Not at a table"))
  1379. (org-table-find-dataline)
  1380. (org-table-check-inside-data-field)
  1381. (let* ((col (org-table-current-column))
  1382. (col1 (if left (1- col) col))
  1383. (beg (org-table-begin))
  1384. (end (org-table-end))
  1385. ;; Current cursor position
  1386. (linepos (org-current-line))
  1387. (colpos (if left (1- col) (1+ col))))
  1388. (if (and left (= col 1))
  1389. (user-error "Cannot move column further left"))
  1390. (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
  1391. (user-error "Cannot move column further right"))
  1392. (goto-char beg)
  1393. (while (< (point) end)
  1394. (if (org-at-table-hline-p)
  1395. nil
  1396. (org-table-goto-column col1 t)
  1397. (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
  1398. (replace-match "|\\2|\\1|")))
  1399. (beginning-of-line 2))
  1400. (move-marker end nil)
  1401. (org-goto-line linepos)
  1402. (org-table-goto-column colpos)
  1403. (org-table-align)
  1404. (when (or (not org-table-fix-formulas-confirm)
  1405. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1406. (org-table-fix-formulas
  1407. "$" (list (cons (number-to-string col) (number-to-string colpos))
  1408. (cons (number-to-string colpos) (number-to-string col))))
  1409. (org-table-fix-formulas
  1410. "$LR" (list (cons (number-to-string col) (number-to-string colpos))
  1411. (cons (number-to-string colpos) (number-to-string col)))))))
  1412. ;;;###autoload
  1413. (defun org-table-move-row-down ()
  1414. "Move table row down."
  1415. (interactive)
  1416. (org-table-move-row nil))
  1417. ;;;###autoload
  1418. (defun org-table-move-row-up ()
  1419. "Move table row up."
  1420. (interactive)
  1421. (org-table-move-row 'up))
  1422. ;;;###autoload
  1423. (defun org-table-move-row (&optional up)
  1424. "Move the current table line down. With arg UP, move it up."
  1425. (interactive "P")
  1426. (let* ((col (current-column))
  1427. (pos (point))
  1428. (hline1p (save-excursion (beginning-of-line 1)
  1429. (looking-at org-table-hline-regexp)))
  1430. (dline1 (org-table-current-dline))
  1431. (dline2 (+ dline1 (if up -1 1)))
  1432. (tonew (if up 0 2))
  1433. txt hline2p)
  1434. (beginning-of-line tonew)
  1435. (unless (org-at-table-p)
  1436. (goto-char pos)
  1437. (user-error "Cannot move row further"))
  1438. (setq hline2p (looking-at org-table-hline-regexp))
  1439. (goto-char pos)
  1440. (beginning-of-line 1)
  1441. (setq pos (point))
  1442. (setq txt (buffer-substring (point) (1+ (point-at-eol))))
  1443. (delete-region (point) (1+ (point-at-eol)))
  1444. (beginning-of-line tonew)
  1445. (insert txt)
  1446. (beginning-of-line 0)
  1447. (org-move-to-column col)
  1448. (unless (or hline1p hline2p
  1449. (not (or (not org-table-fix-formulas-confirm)
  1450. (funcall org-table-fix-formulas-confirm
  1451. "Fix formulas? "))))
  1452. (org-table-fix-formulas
  1453. "@" (list (cons (number-to-string dline1) (number-to-string dline2))
  1454. (cons (number-to-string dline2) (number-to-string dline1)))))))
  1455. ;;;###autoload
  1456. (defun org-table-insert-row (&optional arg)
  1457. "Insert a new row above the current line into the table.
  1458. With prefix ARG, insert below the current line."
  1459. (interactive "P")
  1460. (if (not (org-at-table-p))
  1461. (user-error "Not at a table"))
  1462. (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
  1463. (new (org-table-clean-line line)))
  1464. ;; Fix the first field if necessary
  1465. (if (string-match "^[ \t]*| *[#$] *|" line)
  1466. (setq new (replace-match (match-string 0 line) t t new)))
  1467. (beginning-of-line (if arg 2 1))
  1468. (let (org-table-may-need-update) (insert-before-markers new "\n"))
  1469. (beginning-of-line 0)
  1470. (re-search-forward "| ?" (point-at-eol) t)
  1471. (and (or org-table-may-need-update org-table-overlay-coordinates)
  1472. (org-table-align))
  1473. (when (or (not org-table-fix-formulas-confirm)
  1474. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1475. (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1))))
  1476. ;;;###autoload
  1477. (defun org-table-insert-hline (&optional above)
  1478. "Insert a horizontal-line below the current line into the table.
  1479. With prefix ABOVE, insert above the current line."
  1480. (interactive "P")
  1481. (if (not (org-at-table-p))
  1482. (user-error "Not at a table"))
  1483. (when (eobp) (insert "\n") (backward-char 1))
  1484. (if (not (string-match "|[ \t]*$" (org-current-line-string)))
  1485. (org-table-align))
  1486. (let ((line (org-table-clean-line
  1487. (buffer-substring (point-at-bol) (point-at-eol))))
  1488. (col (current-column)))
  1489. (while (string-match "|\\( +\\)|" line)
  1490. (setq line (replace-match
  1491. (concat "+" (make-string (- (match-end 1) (match-beginning 1))
  1492. ?-) "|") t t line)))
  1493. (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
  1494. (beginning-of-line (if above 1 2))
  1495. (insert line "\n")
  1496. (beginning-of-line (if above 1 -1))
  1497. (org-move-to-column col)
  1498. (and org-table-overlay-coordinates (org-table-align))))
  1499. ;;;###autoload
  1500. (defun org-table-hline-and-move (&optional same-column)
  1501. "Insert a hline and move to the row below that line."
  1502. (interactive "P")
  1503. (let ((col (org-table-current-column)))
  1504. (org-table-maybe-eval-formula)
  1505. (org-table-maybe-recalculate-line)
  1506. (org-table-insert-hline)
  1507. (end-of-line 2)
  1508. (if (looking-at "\n[ \t]*|-")
  1509. (progn (insert "\n|") (org-table-align))
  1510. (org-table-next-field))
  1511. (if same-column (org-table-goto-column col))))
  1512. (defun org-table-clean-line (s)
  1513. "Convert a table line S into a string with only \"|\" and space.
  1514. In particular, this does handle wide and invisible characters."
  1515. (if (string-match "^[ \t]*|-" s)
  1516. ;; It's a hline, just map the characters
  1517. (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
  1518. (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
  1519. (setq s (replace-match
  1520. (concat "|" (make-string (org-string-width (match-string 1 s))
  1521. ?\ ) "|")
  1522. t t s)))
  1523. s))
  1524. ;;;###autoload
  1525. (defun org-table-kill-row ()
  1526. "Delete the current row or horizontal line from the table."
  1527. (interactive)
  1528. (if (not (org-at-table-p))
  1529. (user-error "Not at a table"))
  1530. (let ((col (current-column))
  1531. (dline (org-table-current-dline)))
  1532. (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
  1533. (if (not (org-at-table-p)) (beginning-of-line 0))
  1534. (org-move-to-column col)
  1535. (when (or (not org-table-fix-formulas-confirm)
  1536. (funcall org-table-fix-formulas-confirm "Fix formulas? "))
  1537. (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
  1538. dline -1 dline))))
  1539. ;;;###autoload
  1540. (defun org-table-sort-lines (with-case &optional sorting-type)
  1541. "Sort table lines according to the column at point.
  1542. The position of point indicates the column to be used for
  1543. sorting, and the range of lines is the range between the nearest
  1544. horizontal separator lines, or the entire table of no such lines
  1545. exist. If point is before the first column, you will be prompted
  1546. for the sorting column. If there is an active region, the mark
  1547. specifies the first line and the sorting column, while point
  1548. should be in the last line to be included into the sorting.
  1549. The command then prompts for the sorting type which can be
  1550. alphabetically, numerically, or by time (as given in a time stamp
  1551. in the field, or as a HH:MM value). Sorting in reverse order is
  1552. also possible.
  1553. With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
  1554. If SORTING-TYPE is specified when this function is called from a Lisp
  1555. program, no prompting will take place. SORTING-TYPE must be a character,
  1556. any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
  1557. should be done in reverse order."
  1558. (interactive "P")
  1559. (let* ((thisline (org-current-line))
  1560. (thiscol (org-table-current-column))
  1561. (otc org-table-overlay-coordinates)
  1562. beg end bcol ecol tend tbeg column lns pos)
  1563. (when (equal thiscol 0)
  1564. (if (org-called-interactively-p 'any)
  1565. (setq thiscol
  1566. (string-to-number
  1567. (read-string "Use column N for sorting: ")))
  1568. (setq thiscol 1))
  1569. (org-table-goto-column thiscol))
  1570. (org-table-check-inside-data-field)
  1571. (if (org-region-active-p)
  1572. (progn
  1573. (setq beg (region-beginning) end (region-end))
  1574. (goto-char beg)
  1575. (setq column (org-table-current-column)
  1576. beg (point-at-bol))
  1577. (goto-char end)
  1578. (setq end (point-at-bol 2)))
  1579. (setq column (org-table-current-column)
  1580. pos (point)
  1581. tbeg (org-table-begin)
  1582. tend (org-table-end))
  1583. (if (re-search-backward org-table-hline-regexp tbeg t)
  1584. (setq beg (point-at-bol 2))
  1585. (goto-char tbeg)
  1586. (setq beg (point-at-bol 1)))
  1587. (goto-char pos)
  1588. (if (re-search-forward org-table-hline-regexp tend t)
  1589. (setq end (point-at-bol 1))
  1590. (goto-char tend)
  1591. (setq end (point-at-bol))))
  1592. (setq beg (move-marker (make-marker) beg)
  1593. end (move-marker (make-marker) end))
  1594. (untabify beg end)
  1595. (goto-char beg)
  1596. (org-table-goto-column column)
  1597. (skip-chars-backward "^|")
  1598. (setq bcol (current-column))
  1599. (org-table-goto-column (1+ column))
  1600. (skip-chars-backward "^|")
  1601. (setq ecol (1- (current-column)))
  1602. (org-table-goto-column column)
  1603. (setq lns (mapcar (lambda(x) (cons
  1604. (org-sort-remove-invisible
  1605. (nth (1- column)
  1606. (org-split-string x "[ \t]*|[ \t]*")))
  1607. x))
  1608. (org-split-string (buffer-substring beg end) "\n")))
  1609. (setq lns (org-do-sort lns "Table" with-case sorting-type))
  1610. (when org-table-overlay-coordinates
  1611. (org-table-toggle-coordinate-overlays))
  1612. (delete-region beg end)
  1613. (move-marker beg nil)
  1614. (move-marker end nil)
  1615. (insert (mapconcat 'cdr lns "\n") "\n")
  1616. (org-goto-line thisline)
  1617. (org-table-goto-column thiscol)
  1618. (when otc (org-table-toggle-coordinate-overlays))
  1619. (message "%d lines sorted, based on column %d" (length lns) column)))
  1620. ;;;###autoload
  1621. (defun org-table-cut-region (beg end)
  1622. "Copy region in table to the clipboard and blank all relevant fields.
  1623. If there is no active region, use just the field at point."
  1624. (interactive (list
  1625. (if (org-region-active-p) (region-beginning) (point))
  1626. (if (org-region-active-p) (region-end) (point))))
  1627. (org-table-copy-region beg end 'cut))
  1628. ;;;###autoload
  1629. (defun org-table-copy-region (beg end &optional cut)
  1630. "Copy rectangular region in table to clipboard.
  1631. A special clipboard is used which can only be accessed
  1632. with `org-table-paste-rectangle'."
  1633. (interactive (list
  1634. (if (org-region-active-p) (region-beginning) (point))
  1635. (if (org-region-active-p) (region-end) (point))
  1636. current-prefix-arg))
  1637. (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
  1638. region cols
  1639. (rpl (if cut " " nil)))
  1640. (goto-char beg)
  1641. (org-table-check-inside-data-field)
  1642. (setq l01 (org-current-line)
  1643. c01 (org-table-current-column))
  1644. (goto-char end)
  1645. (org-table-check-inside-data-field)
  1646. (setq l02 (org-current-line)
  1647. c02 (org-table-current-column))
  1648. (setq l1 (min l01 l02) l2 (max l01 l02)
  1649. c1 (min c01 c02) c2 (max c01 c02))
  1650. (catch 'exit
  1651. (while t
  1652. (catch 'nextline
  1653. (if (> l1 l2) (throw 'exit t))
  1654. (org-goto-line l1)
  1655. (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
  1656. (setq cols nil ic1 c1 ic2 c2)
  1657. (while (< ic1 (1+ ic2))
  1658. (push (org-table-get-field ic1 rpl) cols)
  1659. (setq ic1 (1+ ic1)))
  1660. (push (nreverse cols) region)
  1661. (setq l1 (1+ l1)))))
  1662. (setq org-table-clip (nreverse region))
  1663. (if cut (org-table-align))
  1664. org-table-clip))
  1665. ;;;###autoload
  1666. (defun org-table-paste-rectangle ()
  1667. "Paste a rectangular region into a table.
  1668. The upper right corner ends up in the current field. All involved fields
  1669. will be overwritten. If the rectangle does not fit into the present table,
  1670. the table is enlarged as needed. The process ignores horizontal separator
  1671. lines."
  1672. (interactive)
  1673. (unless (and org-table-clip (listp org-table-clip))
  1674. (user-error "First cut/copy a region to paste!"))
  1675. (org-table-check-inside-data-field)
  1676. (let* ((clip org-table-clip)
  1677. (line (org-current-line))
  1678. (col (org-table-current-column))
  1679. (org-enable-table-editor t)
  1680. (org-table-automatic-realign nil)
  1681. c cols field)
  1682. (while (setq cols (pop clip))
  1683. (while (org-at-table-hline-p) (beginning-of-line 2))
  1684. (if (not (org-at-table-p))
  1685. (progn (end-of-line 0) (org-table-next-field)))
  1686. (setq c col)
  1687. (while (setq field (pop cols))
  1688. (org-table-goto-column c nil 'force)
  1689. (org-table-get-field nil field)
  1690. (setq c (1+ c)))
  1691. (beginning-of-line 2))
  1692. (org-goto-line line)
  1693. (org-table-goto-column col)
  1694. (org-table-align)))
  1695. ;;;###autoload
  1696. (defun org-table-convert ()
  1697. "Convert from `org-mode' table to table.el and back.
  1698. Obviously, this only works within limits. When an Org-mode table is
  1699. converted to table.el, all horizontal separator lines get lost, because
  1700. table.el uses these as cell boundaries and has no notion of horizontal lines.
  1701. A table.el table can be converted to an Org-mode table only if it does not
  1702. do row or column spanning. Multiline cells will become multiple cells.
  1703. Beware, Org-mode does not test if the table can be successfully converted - it
  1704. blindly applies a recipe that works for simple tables."
  1705. (interactive)
  1706. (require 'table)
  1707. (if (org-at-table.el-p)
  1708. ;; convert to Org-mode table
  1709. (let ((beg (move-marker (make-marker) (org-table-begin t)))
  1710. (end (move-marker (make-marker) (org-table-end t))))
  1711. (table-unrecognize-region beg end)
  1712. (goto-char beg)
  1713. (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
  1714. (replace-match ""))
  1715. (goto-char beg))
  1716. (if (org-at-table-p)
  1717. ;; convert to table.el table
  1718. (let ((beg (move-marker (make-marker) (org-table-begin)))
  1719. (end (move-marker (make-marker) (org-table-end))))
  1720. ;; first, get rid of all horizontal lines
  1721. (goto-char beg)
  1722. (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
  1723. (replace-match ""))
  1724. ;; insert a hline before first
  1725. (goto-char beg)
  1726. (org-table-insert-hline 'above)
  1727. (beginning-of-line -1)
  1728. ;; insert a hline after each line
  1729. (while (progn (beginning-of-line 3) (< (point) end))
  1730. (org-table-insert-hline))
  1731. (goto-char beg)
  1732. (setq end (move-marker end (org-table-end)))
  1733. ;; replace "+" at beginning and ending of hlines
  1734. (while (re-search-forward "^\\([ \t]*\\)|-" end t)
  1735. (replace-match "\\1+-"))
  1736. (goto-char beg)
  1737. (while (re-search-forward "-|[ \t]*$" end t)
  1738. (replace-match "-+"))
  1739. (goto-char beg)))))
  1740. (defun org-table-transpose-table-at-point ()
  1741. "Transpose Org table at point and eliminate hlines.
  1742. So a table like
  1743. | 1 | 2 | 4 | 5 |
  1744. |---+---+---+---|
  1745. | a | b | c | d |
  1746. | e | f | g | h |
  1747. will be transposed as
  1748. | 1 | a | e |
  1749. | 2 | b | f |
  1750. | 4 | c | g |
  1751. | 5 | d | h |
  1752. Note that horizontal lines disappear."
  1753. (interactive)
  1754. (let* ((table (delete 'hline (org-table-to-lisp)))
  1755. (dline_old (org-table-current-line))
  1756. (col_old (org-table-current-column))
  1757. (contents (mapcar (lambda (p)
  1758. (let ((tp table))
  1759. (mapcar
  1760. (lambda (rown)
  1761. (prog1
  1762. (pop (car tp))
  1763. (setq tp (cdr tp))))
  1764. table)))
  1765. (car table))))
  1766. (goto-char (org-table-begin))
  1767. (re-search-forward "|")
  1768. (backward-char)
  1769. (delete-region (point) (org-table-end))
  1770. (insert (mapconcat
  1771. (lambda(x)
  1772. (concat "| " (mapconcat 'identity x " | " ) " |\n" ))
  1773. contents ""))
  1774. (org-table-goto-line col_old)
  1775. (org-table-goto-column dline_old))
  1776. (org-table-align))
  1777. ;;;###autoload
  1778. (defun org-table-wrap-region (arg)
  1779. "Wrap several fields in a column like a paragraph.
  1780. This is useful if you'd like to spread the contents of a field over several
  1781. lines, in order to keep the table compact.
  1782. If there is an active region, and both point and mark are in the same column,
  1783. the text in the column is wrapped to minimum width for the given number of
  1784. lines. Generally, this makes the table more compact. A prefix ARG may be
  1785. used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
  1786. formats the selected text to two lines. If the region was longer than two
  1787. lines, the remaining lines remain empty. A negative prefix argument reduces
  1788. the current number of lines by that amount. The wrapped text is pasted back
  1789. into the table. If you formatted it to more lines than it was before, fields
  1790. further down in the table get overwritten - so you might need to make space in
  1791. the table first.
  1792. If there is no region, the current field is split at the cursor position and
  1793. the text fragment to the right of the cursor is prepended to the field one
  1794. line down.
  1795. If there is no region, but you specify a prefix ARG, the current field gets
  1796. blank, and the content is appended to the field above."
  1797. (interactive "P")
  1798. (org-table-check-inside-data-field)
  1799. (if (org-region-active-p)
  1800. ;; There is a region: fill as a paragraph
  1801. (let* ((beg (region-beginning))
  1802. (cline (save-excursion (goto-char beg) (org-current-line)))
  1803. (ccol (save-excursion (goto-char beg) (org-table-current-column)))
  1804. nlines)
  1805. (org-table-cut-region (region-beginning) (region-end))
  1806. (if (> (length (car org-table-clip)) 1)
  1807. (user-error "Region must be limited to single column"))
  1808. (setq nlines (if arg
  1809. (if (< arg 1)
  1810. (+ (length org-table-clip) arg)
  1811. arg)
  1812. (length org-table-clip)))
  1813. (setq org-table-clip
  1814. (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
  1815. nil nlines)))
  1816. (org-goto-line cline)
  1817. (org-table-goto-column ccol)
  1818. (org-table-paste-rectangle))
  1819. ;; No region, split the current field at point
  1820. (unless (org-get-alist-option org-M-RET-may-split-line 'table)
  1821. (skip-chars-forward "^\r\n|"))
  1822. (if arg
  1823. ;; combine with field above
  1824. (let ((s (org-table-blank-field))
  1825. (col (org-table-current-column)))
  1826. (beginning-of-line 0)
  1827. (while (org-at-table-hline-p) (beginning-of-line 0))
  1828. (org-table-goto-column col)
  1829. (skip-chars-forward "^|")
  1830. (skip-chars-backward " ")
  1831. (insert " " (org-trim s))
  1832. (org-table-align))
  1833. ;; split field
  1834. (if (looking-at "\\([^|]+\\)+|")
  1835. (let ((s (match-string 1)))
  1836. (replace-match " |")
  1837. (goto-char (match-beginning 0))
  1838. (org-table-next-row)
  1839. (insert (org-trim s) " ")
  1840. (org-table-align))
  1841. (org-table-next-row)))))
  1842. (defvar org-field-marker nil)
  1843. ;;;###autoload
  1844. (defun org-table-edit-field (arg)
  1845. "Edit table field in a different window.
  1846. This is mainly useful for fields that contain hidden parts.
  1847. When called with a \\[universal-argument] prefix, just make the full field visible so that
  1848. it can be edited in place."
  1849. (interactive "P")
  1850. (cond
  1851. ((equal arg '(16))
  1852. (org-table-follow-field-mode (if org-table-follow-field-mode -1 1)))
  1853. (arg
  1854. (let ((b (save-excursion (skip-chars-backward "^|") (point)))
  1855. (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
  1856. (remove-text-properties b e '(org-cwidth t invisible t
  1857. display t intangible t))
  1858. (if (and (boundp 'font-lock-mode) font-lock-mode)
  1859. (font-lock-fontify-block))))
  1860. (t
  1861. (let ((pos (point-marker))
  1862. (coord
  1863. (if (eq org-table-use-standard-references t)
  1864. (concat (org-number-to-letters (org-table-current-column))
  1865. (int-to-string (org-table-current-dline)))
  1866. (concat "@" (int-to-string (org-table-current-dline))
  1867. "$" (int-to-string (org-table-current-column)))))
  1868. (field (org-table-get-field))
  1869. (cw (current-window-configuration))
  1870. p)
  1871. (goto-char pos)
  1872. (org-switch-to-buffer-other-window "*Org Table Edit Field*")
  1873. (when (and (local-variable-p 'org-field-marker)
  1874. (markerp org-field-marker))
  1875. (move-marker org-field-marker nil))
  1876. (erase-buffer)
  1877. (insert "#\n# Edit field " coord " and finish with C-c C-c\n#\n")
  1878. (let ((org-inhibit-startup t)) (org-mode))
  1879. (auto-fill-mode -1)
  1880. (setq truncate-lines nil)
  1881. (setq word-wrap t)
  1882. (goto-char (setq p (point-max)))
  1883. (insert (org-trim field))
  1884. (remove-text-properties p (point-max)
  1885. '(invisible t org-cwidth t display t
  1886. intangible t))
  1887. (goto-char p)
  1888. (org-set-local 'org-finish-function 'org-table-finish-edit-field)
  1889. (org-set-local 'org-window-configuration cw)
  1890. (org-set-local 'org-field-marker pos)
  1891. (message "Edit and finish with C-c C-c")))))
  1892. (defun org-table-finish-edit-field ()
  1893. "Finish editing a table data field.
  1894. Remove all newline characters, insert the result into the table, realign
  1895. the table and kill the editing buffer."
  1896. (let ((pos org-field-marker)
  1897. (cw org-window-configuration)
  1898. (cb (current-buffer))
  1899. text)
  1900. (goto-char (point-min))
  1901. (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
  1902. (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
  1903. (replace-match " "))
  1904. (setq text (org-trim (buffer-string)))
  1905. (set-window-configuration cw)
  1906. (kill-buffer cb)
  1907. (select-window (get-buffer-window (marker-buffer pos)))
  1908. (goto-char pos)
  1909. (move-marker pos nil)
  1910. (org-table-check-inside-data-field)
  1911. (org-table-get-field nil text)
  1912. (org-table-align)
  1913. (message "New field value inserted")))
  1914. (define-minor-mode org-table-follow-field-mode
  1915. "Minor mode to make the table field editor window follow the cursor.
  1916. When this mode is active, the field editor window will always show the
  1917. current field. The mode exits automatically when the cursor leaves the
  1918. table (but see `org-table-exit-follow-field-mode-when-leaving-table')."
  1919. nil " TblFollow" nil
  1920. (if org-table-follow-field-mode
  1921. (org-add-hook 'post-command-hook 'org-table-follow-fields-with-editor
  1922. 'append 'local)
  1923. (remove-hook 'post-command-hook 'org-table-follow-fields-with-editor 'local)
  1924. (let* ((buf (get-buffer "*Org Table Edit Field*"))
  1925. (win (and buf (get-buffer-window buf))))
  1926. (when win (delete-window win))
  1927. (when buf
  1928. (with-current-buffer buf
  1929. (move-marker org-field-marker nil))
  1930. (kill-buffer buf)))))
  1931. (defun org-table-follow-fields-with-editor ()
  1932. (if (and org-table-exit-follow-field-mode-when-leaving-table
  1933. (not (org-at-table-p)))
  1934. ;; We have left the table, exit the follow mode
  1935. (org-table-follow-field-mode -1)
  1936. (when (org-table-check-inside-data-field 'noerror)
  1937. (let ((win (selected-window)))
  1938. (org-table-edit-field nil)
  1939. (org-fit-window-to-buffer)
  1940. (select-window win)))))
  1941. (defvar org-timecnt) ; dynamically scoped parameter
  1942. ;;;###autoload
  1943. (defun org-table-sum (&optional beg end nlast)
  1944. "Sum numbers in region of current table column.
  1945. The result will be displayed in the echo area, and will be available
  1946. as kill to be inserted with \\[yank].
  1947. If there is an active region, it is interpreted as a rectangle and all
  1948. numbers in that rectangle will be summed. If there is no active
  1949. region and point is located in a table column, sum all numbers in that
  1950. column.
  1951. If at least one number looks like a time HH:MM or HH:MM:SS, all other
  1952. numbers are assumed to be times as well (in decimal hours) and the
  1953. numbers are added as such.
  1954. If NLAST is a number, only the NLAST fields will actually be summed."
  1955. (interactive)
  1956. (save-excursion
  1957. (let (col (org-timecnt 0) diff h m s org-table-clip)
  1958. (cond
  1959. ((and beg end)) ; beg and end given explicitly
  1960. ((org-region-active-p)
  1961. (setq beg (region-beginning) end (region-end)))
  1962. (t
  1963. (setq col (org-table-current-column))
  1964. (goto-char (org-table-begin))
  1965. (unless (re-search-forward "^[ \t]*|[^-]" nil t)
  1966. (user-error "No table data"))
  1967. (org-table-goto-column col)
  1968. (setq beg (point))
  1969. (goto-char (org-table-end))
  1970. (unless (re-search-backward "^[ \t]*|[^-]" nil t)
  1971. (user-error "No table data"))
  1972. (org-table-goto-column col)
  1973. (setq end (point))))
  1974. (let* ((items (apply 'append (org-table-copy-region beg end)))
  1975. (items1 (cond ((not nlast) items)
  1976. ((>= nlast (length items)) items)
  1977. (t (setq items (reverse items))
  1978. (setcdr (nthcdr (1- nlast) items) nil)
  1979. (nreverse items))))
  1980. (numbers (delq nil (mapcar 'org-table-get-number-for-summing
  1981. items1)))
  1982. (res (apply '+ numbers))
  1983. (sres (if (= org-timecnt 0)
  1984. (number-to-string res)
  1985. (setq diff (* 3600 res)
  1986. h (floor (/ diff 3600)) diff (mod diff 3600)
  1987. m (floor (/ diff 60)) diff (mod diff 60)
  1988. s diff)
  1989. (format "%.0f:%02.0f:%02.0f" h m s))))
  1990. (kill-new sres)
  1991. (if (org-called-interactively-p 'interactive)
  1992. (message "%s"
  1993. (substitute-command-keys
  1994. (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
  1995. (length numbers) sres))))
  1996. sres))))
  1997. (defun org-table-get-number-for-summing (s)
  1998. (let (n)
  1999. (if (string-match "^ *|? *" s)
  2000. (setq s (replace-match "" nil nil s)))
  2001. (if (string-match " *|? *$" s)
  2002. (setq s (replace-match "" nil nil s)))
  2003. (setq n (string-to-number s))
  2004. (cond
  2005. ((and (string-match "0" s)
  2006. (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
  2007. ((string-match "\\`[ \t]+\\'" s) nil)
  2008. ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
  2009. (let ((h (string-to-number (or (match-string 1 s) "0")))
  2010. (m (string-to-number (or (match-string 2 s) "0")))
  2011. (s (string-to-number (or (match-string 4 s) "0"))))
  2012. (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
  2013. (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
  2014. ((equal n 0) nil)
  2015. (t n))))
  2016. (defun org-table-current-field-formula (&optional key noerror)
  2017. "Return the formula active for the current field.
  2018. Assumes that specials are in place.
  2019. If KEY is given, return the key to this formula.
  2020. Otherwise return the formula preceded with \"=\" or \":=\"."
  2021. (let* ((name (car (rassoc (list (org-current-line)
  2022. (org-table-current-column))
  2023. org-table-named-field-locations)))
  2024. (col (org-table-current-column))
  2025. (scol (int-to-string col))
  2026. (ref (format "@%d$%d" (org-table-current-dline) col))
  2027. (stored-list (org-table-get-stored-formulas noerror))
  2028. (ass (or (assoc name stored-list)
  2029. (assoc ref stored-list)
  2030. (assoc scol stored-list))))
  2031. (if key
  2032. (car ass)
  2033. (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
  2034. (cdr ass))))))
  2035. (defun org-table-get-formula (&optional equation named)
  2036. "Read a formula from the minibuffer, offer stored formula as default.
  2037. When NAMED is non-nil, look for a named equation."
  2038. (let* ((stored-list (org-table-get-stored-formulas))
  2039. (name (car (rassoc (list (org-current-line)
  2040. (org-table-current-column))
  2041. org-table-named-field-locations)))
  2042. (ref (format "@%d$%d" (org-table-current-dline)
  2043. (org-table-current-column)))
  2044. (refass (assoc ref stored-list))
  2045. (nameass (assoc name stored-list))
  2046. (scol (if named
  2047. (if (and name (not (string-match "^LR[0-9]+$" name)))
  2048. name
  2049. ref)
  2050. (int-to-string (org-table-current-column))))
  2051. (dummy (and (or nameass refass) (not named)
  2052. (not (y-or-n-p "Replace existing field formula with column formula? " ))
  2053. (message "Formula not replaced")))
  2054. (name (or name ref))
  2055. (org-table-may-need-update nil)
  2056. (stored (cdr (assoc scol stored-list)))
  2057. (eq (cond
  2058. ((and stored equation (string-match "^ *=? *$" equation))
  2059. stored)
  2060. ((stringp equation)
  2061. equation)
  2062. (t (org-table-formula-from-user
  2063. (read-string
  2064. (org-table-formula-to-user
  2065. (format "%s formula %s%s="
  2066. (if named "Field" "Column")
  2067. (if (member (string-to-char scol) '(?$ ?@)) "" "$")
  2068. scol))
  2069. (if stored (org-table-formula-to-user stored) "")
  2070. 'org-table-formula-history
  2071. )))))
  2072. mustsave)
  2073. (when (not (string-match "\\S-" eq))
  2074. ;; remove formula
  2075. (setq stored-list (delq (assoc scol stored-list) stored-list))
  2076. (org-table-store-formulas stored-list)
  2077. (user-error "Formula removed"))
  2078. (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  2079. (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  2080. (if (and name (not named))
  2081. ;; We set the column equation, delete the named one.
  2082. (setq stored-list (delq (assoc name stored-list) stored-list)
  2083. mustsave t))
  2084. (if stored
  2085. (setcdr (assoc scol stored-list) eq)
  2086. (setq stored-list (cons (cons scol eq) stored-list)))
  2087. (if (or mustsave (not (equal stored eq)))
  2088. (org-table-store-formulas stored-list))
  2089. eq))
  2090. (defun org-table-store-formulas (alist)
  2091. "Store the list of formulas below the current table."
  2092. (setq alist (sort alist 'org-table-formula-less-p))
  2093. (let ((case-fold-search t))
  2094. (save-excursion
  2095. (goto-char (org-table-end))
  2096. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
  2097. (progn
  2098. ;; don't overwrite TBLFM, we might use text properties to store stuff
  2099. (goto-char (match-beginning 3))
  2100. (delete-region (match-beginning 3) (match-end 0)))
  2101. (org-indent-line)
  2102. (insert (or (match-string 2) "#+TBLFM:")))
  2103. (insert " "
  2104. (mapconcat (lambda (x)
  2105. (concat
  2106. (if (equal (string-to-char (car x)) ?@) "" "$")
  2107. (car x) "=" (cdr x)))
  2108. alist "::")
  2109. "\n"))))
  2110. (defsubst org-table-formula-make-cmp-string (a)
  2111. (when (string-match "\\`$[<>]" a)
  2112. (let ((arrow (string-to-char (substring a 1))))
  2113. ;; Fake a high number to make sure this is sorted at the end.
  2114. (setq a (org-table-formula-handle-first/last-rc a))
  2115. (setq a (format "$%d" (+ 10000
  2116. (if (= arrow ?<) -1000 0)
  2117. (string-to-number (substring a 1)))))))
  2118. (when (string-match
  2119. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  2120. a)
  2121. (concat
  2122. (if (match-end 2)
  2123. (format "@%05d" (string-to-number (match-string 2 a))) "")
  2124. (if (match-end 4)
  2125. (format "$%05d" (string-to-number (match-string 4 a))) "")
  2126. (if (match-end 5)
  2127. (concat "@@" (match-string 5 a))))))
  2128. (defun org-table-formula-less-p (a b)
  2129. "Compare two formulas for sorting."
  2130. (let ((as (org-table-formula-make-cmp-string (car a)))
  2131. (bs (org-table-formula-make-cmp-string (car b))))
  2132. (and as bs (string< as bs))))
  2133. ;;;###autoload
  2134. (defun org-table-get-stored-formulas (&optional noerror)
  2135. "Return an alist with the stored formulas directly after current table."
  2136. (interactive) ;; FIXME interactive?
  2137. (let ((case-fold-search t) scol eq eq-alist strings string seen)
  2138. (save-excursion
  2139. (goto-char (org-table-end))
  2140. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+tblfm: *\\(.*\\)")
  2141. (setq strings (org-split-string (org-match-string-no-properties 2)
  2142. " *:: *"))
  2143. (while (setq string (pop strings))
  2144. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
  2145. (setq scol (if (match-end 2)
  2146. (match-string 2 string)
  2147. (match-string 1 string))
  2148. scol (if (member (string-to-char scol) '(?< ?>))
  2149. (concat "$" scol) scol)
  2150. eq (match-string 3 string)
  2151. eq-alist (cons (cons scol eq) eq-alist))
  2152. (if (member scol seen)
  2153. (if noerror
  2154. (progn
  2155. (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
  2156. (ding)
  2157. (sit-for 2))
  2158. (user-error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
  2159. (push scol seen))))))
  2160. (nreverse eq-alist)))
  2161. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2162. "Modify the equations after the table structure has been edited.
  2163. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2164. For all numbers larger than LIMIT, shift them by DELTA."
  2165. (save-excursion
  2166. (goto-char (org-table-end))
  2167. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2168. (let ((msg "The formulas in #+TBLFM have been updated")
  2169. (re (concat key "\\([0-9]+\\)"))
  2170. (re2
  2171. (when remove
  2172. (if (or (equal key "$") (equal key "$LR"))
  2173. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2174. (regexp-quote key) remove)
  2175. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2176. s n a)
  2177. (when remove
  2178. (while (re-search-forward re2 (point-at-eol) t)
  2179. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2180. (if (equal (char-before (match-beginning 0)) ?.)
  2181. (user-error
  2182. "Change makes TBLFM term %s invalid, use undo to recover"
  2183. (match-string 0))
  2184. (replace-match "")))))
  2185. (while (re-search-forward re (point-at-eol) t)
  2186. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2187. (setq s (match-string 1) n (string-to-number s))
  2188. (cond
  2189. ((setq a (assoc s replace))
  2190. (replace-match (concat key (cdr a)) t t)
  2191. (message msg))
  2192. ((and limit (> n limit))
  2193. (replace-match (concat key (int-to-string (+ n delta))) t t)
  2194. (message msg))))))
  2195. (forward-line))))
  2196. (defun org-table-get-specials ()
  2197. "Get the column names and local parameters for this table."
  2198. (save-excursion
  2199. (let ((beg (org-table-begin)) (end (org-table-end))
  2200. names name fields fields1 field cnt
  2201. c v l line col types dlines hlines last-dline)
  2202. (setq org-table-column-names nil
  2203. org-table-local-parameters nil
  2204. org-table-named-field-locations nil
  2205. org-table-current-begin-line nil
  2206. org-table-current-begin-pos nil
  2207. org-table-current-line-types nil
  2208. org-table-current-ncol 0)
  2209. (goto-char beg)
  2210. (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
  2211. (setq names (org-split-string (match-string 1) " *| *")
  2212. cnt 1)
  2213. (while (setq name (pop names))
  2214. (setq cnt (1+ cnt))
  2215. (if (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" name)
  2216. (push (cons name (int-to-string cnt)) org-table-column-names))))
  2217. (setq org-table-column-names (nreverse org-table-column-names))
  2218. (setq org-table-column-name-regexp
  2219. (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
  2220. (goto-char beg)
  2221. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  2222. (setq fields (org-split-string (match-string 1) " *| *"))
  2223. (while (setq field (pop fields))
  2224. (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  2225. (push (cons (match-string 1 field) (match-string 2 field))
  2226. org-table-local-parameters))))
  2227. (goto-char beg)
  2228. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  2229. (setq c (match-string 1)
  2230. fields (org-split-string (match-string 2) " *| *"))
  2231. (save-excursion
  2232. (beginning-of-line (if (equal c "_") 2 0))
  2233. (setq line (org-current-line) col 1)
  2234. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  2235. (setq fields1 (org-split-string (match-string 1) " *| *"))))
  2236. (while (and fields1 (setq field (pop fields)))
  2237. (setq v (pop fields1) col (1+ col))
  2238. (when (and (stringp field) (stringp v)
  2239. (string-match "^[a-zA-Z][_a-zA-Z0-9]*$" field))
  2240. (push (cons field v) org-table-local-parameters)
  2241. (push (list field line col) org-table-named-field-locations))))
  2242. ;; Analyse the line types
  2243. (goto-char beg)
  2244. (setq org-table-current-begin-line (org-current-line)
  2245. org-table-current-begin-pos (point)
  2246. l org-table-current-begin-line)
  2247. (while (looking-at "[ \t]*|\\(-\\)?")
  2248. (push (if (match-end 1) 'hline 'dline) types)
  2249. (if (match-end 1) (push l hlines) (push l dlines))
  2250. (beginning-of-line 2)
  2251. (setq l (1+ l)))
  2252. (push 'hline types) ;; add an imaginary extra hline to the end
  2253. (setq org-table-current-line-types (apply 'vector (nreverse types))
  2254. last-dline (car dlines)
  2255. org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
  2256. org-table-hlines (apply 'vector (cons nil (nreverse hlines))))
  2257. (org-goto-line last-dline)
  2258. (let* ((l last-dline)
  2259. (fields (org-split-string
  2260. (buffer-substring (point-at-bol) (point-at-eol))
  2261. "[ \t]*|[ \t]*"))
  2262. (nfields (length fields))
  2263. al al2)
  2264. (setq org-table-current-ncol nfields)
  2265. (loop for i from 1 to nfields do
  2266. (push (list (format "LR%d" i) l i) al)
  2267. (push (cons (format "LR%d" i) (nth (1- i) fields)) al2))
  2268. (setq org-table-named-field-locations
  2269. (append org-table-named-field-locations al))
  2270. (setq org-table-local-parameters
  2271. (append org-table-local-parameters al2))))))
  2272. ;;;###autoload
  2273. (defun org-table-maybe-eval-formula ()
  2274. "Check if the current field starts with \"=\" or \":=\".
  2275. If yes, store the formula and apply it."
  2276. ;; We already know we are in a table. Get field will only return a formula
  2277. ;; when appropriate. It might return a separator line, but no problem.
  2278. (when org-table-formula-evaluate-inline
  2279. (let* ((field (org-trim (or (org-table-get-field) "")))
  2280. named eq)
  2281. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2282. (setq named (equal (string-to-char field) ?:)
  2283. eq (match-string 1 field))
  2284. (if (or (fboundp 'calc-eval)
  2285. (equal (substring eq 0 (min 2 (length eq))) "'("))
  2286. (org-table-eval-formula (if named '(4) nil)
  2287. (org-table-formula-from-user eq))
  2288. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
  2289. (defvar org-recalc-commands nil
  2290. "List of commands triggering the recalculation of a line.
  2291. Will be filled automatically during use.")
  2292. (defvar org-recalc-marks
  2293. '((" " . "Unmarked: no special line, no automatic recalculation")
  2294. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  2295. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  2296. ("!" . "Column name definition line. Reference in formula as $name.")
  2297. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  2298. ("_" . "Names for values in row below this one.")
  2299. ("^" . "Names for values in row above this one.")))
  2300. ;;;###autoload
  2301. (defun org-table-rotate-recalc-marks (&optional newchar)
  2302. "Rotate the recalculation mark in the first column.
  2303. If in any row, the first field is not consistent with a mark,
  2304. insert a new column for the markers.
  2305. When there is an active region, change all the lines in the region,
  2306. after prompting for the marking character.
  2307. After each change, a message will be displayed indicating the meaning
  2308. of the new mark."
  2309. (interactive)
  2310. (unless (org-at-table-p) (user-error "Not at a table"))
  2311. (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
  2312. (beg (org-table-begin))
  2313. (end (org-table-end))
  2314. (l (org-current-line))
  2315. (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
  2316. (l2 (if (org-region-active-p) (org-current-line (region-end))))
  2317. (have-col
  2318. (save-excursion
  2319. (goto-char beg)
  2320. (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
  2321. (col (org-table-current-column))
  2322. (forcenew (car (assoc newchar org-recalc-marks)))
  2323. epos new)
  2324. (when l1
  2325. (message "Change region to what mark? Type # * ! $ or SPC: ")
  2326. (setq newchar (char-to-string (read-char-exclusive))
  2327. forcenew (car (assoc newchar org-recalc-marks))))
  2328. (if (and newchar (not forcenew))
  2329. (user-error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
  2330. newchar))
  2331. (if l1 (org-goto-line l1))
  2332. (save-excursion
  2333. (beginning-of-line 1)
  2334. (unless (looking-at org-table-dataline-regexp)
  2335. (user-error "Not at a table data line")))
  2336. (unless have-col
  2337. (org-table-goto-column 1)
  2338. (org-table-insert-column)
  2339. (org-table-goto-column (1+ col)))
  2340. (setq epos (point-at-eol))
  2341. (save-excursion
  2342. (beginning-of-line 1)
  2343. (org-table-get-field
  2344. 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
  2345. (concat " "
  2346. (setq new (or forcenew
  2347. (cadr (member (match-string 1) marks))))
  2348. " ")
  2349. " # ")))
  2350. (if (and l1 l2)
  2351. (progn
  2352. (org-goto-line l1)
  2353. (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
  2354. (and (looking-at org-table-dataline-regexp)
  2355. (org-table-get-field 1 (concat " " new " "))))
  2356. (org-goto-line l1)))
  2357. (if (not (= epos (point-at-eol))) (org-table-align))
  2358. (org-goto-line l)
  2359. (and (org-called-interactively-p 'interactive)
  2360. (message "%s" (cdr (assoc new org-recalc-marks))))))
  2361. ;;;###autoload
  2362. (defun org-table-maybe-recalculate-line ()
  2363. "Recompute the current line if marked for it, and if we haven't just done it."
  2364. (interactive)
  2365. (and org-table-allow-automatic-line-recalculation
  2366. (not (and (memq last-command org-recalc-commands)
  2367. (equal org-last-recalc-line (org-current-line))))
  2368. (save-excursion (beginning-of-line 1)
  2369. (looking-at org-table-auto-recalculate-regexp))
  2370. (org-table-recalculate) t))
  2371. (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
  2372. (defsubst org-set-calc-mode (var &optional value)
  2373. (if (stringp var)
  2374. (setq var (assoc var '(("D" calc-angle-mode deg)
  2375. ("R" calc-angle-mode rad)
  2376. ("F" calc-prefer-frac t)
  2377. ("S" calc-symbolic-mode t)))
  2378. value (nth 2 var) var (nth 1 var)))
  2379. (if (memq var org-tbl-calc-modes)
  2380. (setcar (cdr (memq var org-tbl-calc-modes)) value)
  2381. (cons var (cons value org-tbl-calc-modes)))
  2382. org-tbl-calc-modes)
  2383. ;;;###autoload
  2384. (defun org-table-eval-formula (&optional arg equation
  2385. suppress-align suppress-const
  2386. suppress-store suppress-analysis)
  2387. "Replace the table field value at the cursor by the result of a calculation.
  2388. This function makes use of Dave Gillespie's Calc package, in my view the
  2389. most exciting program ever written for GNU Emacs. So you need to have Calc
  2390. installed in order to use this function.
  2391. In a table, this command replaces the value in the current field with the
  2392. result of a formula. It also installs the formula as the \"current\" column
  2393. formula, by storing it in a special line below the table. When called
  2394. with a `C-u' prefix, the current field must be a named field, and the
  2395. formula is installed as valid in only this specific field.
  2396. When called with two `C-u' prefixes, insert the active equation
  2397. for the field back into the current field, so that it can be
  2398. edited there. This is useful in order to use \\[org-table-show-reference]
  2399. to check the referenced fields.
  2400. When called, the command first prompts for a formula, which is read in
  2401. the minibuffer. Previously entered formulas are available through the
  2402. history list, and the last used formula is offered as a default.
  2403. These stored formulas are adapted correctly when moving, inserting, or
  2404. deleting columns with the corresponding commands.
  2405. The formula can be any algebraic expression understood by the Calc package.
  2406. For details, see the Org-mode manual.
  2407. This function can also be called from Lisp programs and offers
  2408. additional arguments: EQUATION can be the formula to apply. If this
  2409. argument is given, the user will not be prompted. SUPPRESS-ALIGN is
  2410. used to speed-up recursive calls by by-passing unnecessary aligns.
  2411. SUPPRESS-CONST suppresses the interpretation of constants in the
  2412. formula, assuming that this has been done already outside the function.
  2413. SUPPRESS-STORE means the formula should not be stored, either because
  2414. it is already stored, or because it is a modified equation that should
  2415. not overwrite the stored one."
  2416. (interactive "P")
  2417. (org-table-check-inside-data-field)
  2418. (or suppress-analysis (org-table-get-specials))
  2419. (if (equal arg '(16))
  2420. (let ((eq (org-table-current-field-formula)))
  2421. (or eq (user-error "No equation active for current field"))
  2422. (org-table-get-field nil eq)
  2423. (org-table-align)
  2424. (setq org-table-may-need-update t))
  2425. (let* (fields
  2426. (ndown (if (integerp arg) arg 1))
  2427. (org-table-automatic-realign nil)
  2428. (case-fold-search nil)
  2429. (down (> ndown 1))
  2430. (formula (if (and equation suppress-store)
  2431. equation
  2432. (org-table-get-formula equation (equal arg '(4)))))
  2433. (n0 (org-table-current-column))
  2434. (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
  2435. (numbers nil) ; was a variable, now fixed default
  2436. (keep-empty nil)
  2437. n form form0 formrpl formrg bw fmt x ev orig c lispp literal
  2438. duration duration-output-format)
  2439. ;; Parse the format string. Since we have a lot of modes, this is
  2440. ;; a lot of work. However, I think calc still uses most of the time.
  2441. (if (string-match ";" formula)
  2442. (let ((tmp (org-split-string formula ";")))
  2443. (setq formula (car tmp)
  2444. fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2445. (nth 1 tmp)))
  2446. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2447. (setq c (string-to-char (match-string 1 fmt))
  2448. n (string-to-number (match-string 2 fmt)))
  2449. (if (= c ?p)
  2450. (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
  2451. (setq org-tbl-calc-modes
  2452. (org-set-calc-mode
  2453. 'calc-float-format
  2454. (list (cdr (assoc c '((?n . float) (?f . fix)
  2455. (?s . sci) (?e . eng))))
  2456. n))))
  2457. (setq fmt (replace-match "" t t fmt)))
  2458. (if (string-match "T" fmt)
  2459. (setq duration t numbers t
  2460. duration-output-format nil
  2461. fmt (replace-match "" t t fmt)))
  2462. (if (string-match "t" fmt)
  2463. (setq duration t
  2464. duration-output-format org-table-duration-custom-format
  2465. numbers t
  2466. fmt (replace-match "" t t fmt)))
  2467. (if (string-match "N" fmt)
  2468. (setq numbers t
  2469. fmt (replace-match "" t t fmt)))
  2470. (if (string-match "L" fmt)
  2471. (setq literal t
  2472. fmt (replace-match "" t t fmt)))
  2473. (if (string-match "E" fmt)
  2474. (setq keep-empty t
  2475. fmt (replace-match "" t t fmt)))
  2476. (while (string-match "[DRFS]" fmt)
  2477. (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
  2478. (setq fmt (replace-match "" t t fmt)))
  2479. (unless (string-match "\\S-" fmt)
  2480. (setq fmt nil))))
  2481. (if (and (not suppress-const) org-table-formula-use-constants)
  2482. (setq formula (org-table-formula-substitute-names formula)))
  2483. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2484. (while (> ndown 0)
  2485. (setq fields (org-split-string
  2486. (buffer-substring-no-properties (point-at-bol) (point-at-eol))
  2487. " *| *"))
  2488. ;; replace fields with duration values if relevant
  2489. (if duration
  2490. (setq fields
  2491. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2492. fields)))
  2493. (if (eq numbers t)
  2494. (setq fields (mapcar
  2495. (lambda (x)
  2496. (if (string-match "\\S-" x)
  2497. (number-to-string (string-to-number x))
  2498. x))
  2499. fields)))
  2500. (setq ndown (1- ndown))
  2501. (setq form (copy-sequence formula)
  2502. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2503. (if (and lispp literal) (setq lispp 'literal))
  2504. ;; Insert row and column number of formula result field
  2505. (while (string-match "[@$]#" form)
  2506. (setq form
  2507. (replace-match
  2508. (format "%d"
  2509. (save-match-data
  2510. (if (equal (substring form (match-beginning 0)
  2511. (1+ (match-beginning 0)))
  2512. "@")
  2513. (org-table-current-dline)
  2514. (org-table-current-column))))
  2515. t t form)))
  2516. ;; Check for old vertical references
  2517. (org-table--error-on-old-row-references form)
  2518. ;; Insert remote references
  2519. (setq form (org-table-remote-reference-indirection form))
  2520. (while (string-match "\\<remote([ \t]*\\([-_a-zA-Z0-9]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2521. (setq form
  2522. (replace-match
  2523. (save-match-data
  2524. (org-table-make-reference
  2525. (let ((rmtrng (org-table-get-remote-range
  2526. (match-string 1 form) (match-string 2 form))))
  2527. (if duration
  2528. (if (listp rmtrng)
  2529. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2530. (org-table-time-string-to-seconds rmtrng))
  2531. rmtrng))
  2532. keep-empty numbers lispp))
  2533. t t form)))
  2534. ;; Insert complex ranges
  2535. (while (and (string-match org-table-range-regexp form)
  2536. (> (length (match-string 0 form)) 1))
  2537. (setq formrg (save-match-data
  2538. (org-table-get-range (match-string 0 form) nil n0)))
  2539. (setq formrpl
  2540. (save-match-data
  2541. (org-table-make-reference
  2542. ;; possibly handle durations
  2543. (if duration
  2544. (if (listp formrg)
  2545. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2546. (org-table-time-string-to-seconds formrg))
  2547. formrg)
  2548. keep-empty numbers lispp)))
  2549. (if (not (save-match-data
  2550. (string-match (regexp-quote form) formrpl)))
  2551. (setq form (replace-match formrpl t t form))
  2552. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2553. ;; Insert simple ranges
  2554. (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
  2555. (setq form
  2556. (replace-match
  2557. (save-match-data
  2558. (org-table-make-reference
  2559. (org-sublist
  2560. fields (string-to-number (match-string 1 form))
  2561. (string-to-number (match-string 2 form)))
  2562. keep-empty numbers lispp))
  2563. t t form)))
  2564. (setq form0 form)
  2565. ;; Insert the references to fields in same row
  2566. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2567. (setq n (+ (string-to-number (match-string 1 form))
  2568. (if (match-end 2) n0 0))
  2569. x (nth (1- (if (= n 0) n0 (max n 1))) fields)
  2570. formrpl (save-match-data
  2571. (org-table-make-reference
  2572. x keep-empty numbers lispp)))
  2573. (when (or (not x)
  2574. (save-match-data
  2575. (string-match (regexp-quote formula) formrpl)))
  2576. (user-error "Invalid field specifier \"%s\""
  2577. (match-string 0 form)))
  2578. (setq form (replace-match formrpl t t form)))
  2579. (if lispp
  2580. (setq ev (condition-case nil
  2581. (eval (eval (read form)))
  2582. (error "#ERROR"))
  2583. ev (if (numberp ev) (number-to-string ev) ev)
  2584. ev (if duration (org-table-time-seconds-to-string
  2585. (string-to-number ev)
  2586. duration-output-format) ev))
  2587. (or (fboundp 'calc-eval)
  2588. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
  2589. ;; Use <...> time-stamps so that Calc can handle them
  2590. (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
  2591. (setq form (replace-match "<\\1>" nil nil form)))
  2592. ;; I18n-ize local time-stamps by setting (system-time-locale "C")
  2593. (when (string-match org-ts-regexp2 form)
  2594. (let* ((ts (match-string 0 form))
  2595. (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
  2596. (system-time-locale "C")
  2597. (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2598. (cdr org-time-stamp-formats))
  2599. (car org-time-stamp-formats))))
  2600. (setq form (replace-match (format-time-string tf tsp) t t form))))
  2601. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2602. form
  2603. (calc-eval (cons form org-tbl-calc-modes)
  2604. (when (and (not keep-empty) numbers) 'num)))
  2605. ev (if duration (org-table-time-seconds-to-string
  2606. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2607. (string-to-number (org-table-time-string-to-seconds ev))
  2608. (string-to-number ev))
  2609. duration-output-format)
  2610. ev)))
  2611. (when org-table-formula-debug
  2612. (with-output-to-temp-buffer "*Substitution History*"
  2613. (princ (format "Substitution history of formula
  2614. Orig: %s
  2615. $xyz-> %s
  2616. @r$c-> %s
  2617. $1-> %s\n" orig formula form0 form))
  2618. (if (consp ev)
  2619. (princ (format " %s^\nError: %s"
  2620. (make-string (car ev) ?\-) (nth 1 ev)))
  2621. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2622. ev (or fmt "NONE")
  2623. (if fmt (format fmt (string-to-number ev)) ev)))))
  2624. (setq bw (get-buffer-window "*Substitution History*"))
  2625. (org-fit-window-to-buffer bw)
  2626. (unless (and (org-called-interactively-p 'any) (not ndown))
  2627. (unless (let (inhibit-redisplay)
  2628. (y-or-n-p "Debugging Formula. Continue to next? "))
  2629. (org-table-align)
  2630. (user-error "Abort"))
  2631. (delete-window bw)
  2632. (message "")))
  2633. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2634. (org-table-justify-field-maybe
  2635. (format org-table-formula-field-format
  2636. (if fmt (format fmt (string-to-number ev)) ev)))
  2637. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2638. (call-interactively 'org-return)
  2639. (setq ndown 0)))
  2640. (and down (org-table-maybe-recalculate-line))
  2641. (or suppress-align (and org-table-may-need-update
  2642. (org-table-align))))))
  2643. (defun org-table-put-field-property (prop value)
  2644. (save-excursion
  2645. (put-text-property (progn (skip-chars-backward "^|") (point))
  2646. (progn (skip-chars-forward "^|") (point))
  2647. prop value)))
  2648. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2649. "Get a calc vector from a column, according to descriptor DESC.
  2650. Optional arguments TBEG and COL can give the beginning of the table and
  2651. the current column, to avoid unnecessary parsing.
  2652. HIGHLIGHT means just highlight the range.
  2653. When CORNERS-ONLY is set, only return the corners of the range as
  2654. a list (line1 column1 line2 column2) where line1 and line2 are line numbers
  2655. in the buffer and column1 and column2 are table column numbers."
  2656. (if (not (equal (string-to-char desc) ?@))
  2657. (setq desc (concat "@" desc)))
  2658. (save-excursion
  2659. (or tbeg (setq tbeg (org-table-begin)))
  2660. (or col (setq col (org-table-current-column)))
  2661. (let ((thisline (org-current-line))
  2662. beg end c1 c2 r1 r2 rangep tmp)
  2663. (unless (string-match org-table-range-regexp desc)
  2664. (user-error "Invalid table range specifier `%s'" desc))
  2665. (setq rangep (match-end 3)
  2666. r1 (and (match-end 1) (match-string 1 desc))
  2667. r2 (and (match-end 4) (match-string 4 desc))
  2668. c1 (and (match-end 2) (substring (match-string 2 desc) 1))
  2669. c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
  2670. (and c1 (setq c1 (+ (string-to-number c1)
  2671. (if (memq (string-to-char c1) '(?- ?+)) col 0))))
  2672. (and c2 (setq c2 (+ (string-to-number c2)
  2673. (if (memq (string-to-char c2) '(?- ?+)) col 0))))
  2674. (if (equal r1 "") (setq r1 nil))
  2675. (if (equal r2 "") (setq r2 nil))
  2676. (if r1 (setq r1 (org-table-get-descriptor-line r1)))
  2677. (if r2 (setq r2 (org-table-get-descriptor-line r2)))
  2678. ; (setq r2 (or r2 r1) c2 (or c2 c1))
  2679. (if (not r1) (setq r1 thisline))
  2680. (if (not r2) (setq r2 thisline))
  2681. (if (or (not c1) (= 0 c1)) (setq c1 col))
  2682. (if (or (not c2) (= 0 c2)) (setq c2 col))
  2683. (if (and (not corners-only)
  2684. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2685. ;; just one field
  2686. (progn
  2687. (org-goto-line r1)
  2688. (while (not (looking-at org-table-dataline-regexp))
  2689. (beginning-of-line 2))
  2690. (prog1 (org-trim (org-table-get-field c1))
  2691. (if highlight (org-table-highlight-rectangle (point) (point)))))
  2692. ;; A range, return a vector
  2693. ;; First sort the numbers to get a regular rectangle
  2694. (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
  2695. (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
  2696. (if corners-only
  2697. ;; Only return the corners of the range
  2698. (list r1 c1 r2 c2)
  2699. ;; Copy the range values into a list
  2700. (org-goto-line r1)
  2701. (while (not (looking-at org-table-dataline-regexp))
  2702. (beginning-of-line 2))
  2703. (org-table-goto-column c1)
  2704. (setq beg (point))
  2705. (org-goto-line r2)
  2706. (while (not (looking-at org-table-dataline-regexp))
  2707. (beginning-of-line 0))
  2708. (org-table-goto-column c2)
  2709. (setq end (point))
  2710. (if highlight
  2711. (org-table-highlight-rectangle
  2712. beg (progn (skip-chars-forward "^|\n") (point))))
  2713. ;; return string representation of calc vector
  2714. (mapcar 'org-trim
  2715. (apply 'append (org-table-copy-region beg end))))))))
  2716. (defun org-table-get-descriptor-line (desc &optional cline bline table)
  2717. "Analyze descriptor DESC and retrieve the corresponding line number.
  2718. The cursor is currently in line CLINE, the table begins in line BLINE,
  2719. and TABLE is a vector with line types."
  2720. (if (string-match "^[0-9]+$" desc)
  2721. (aref org-table-dlines (string-to-number desc))
  2722. (setq cline (or cline (org-current-line))
  2723. bline (or bline org-table-current-begin-line)
  2724. table (or table org-table-current-line-types))
  2725. (if (or
  2726. (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
  2727. ;; 1 2 3 4 5 6
  2728. (and (not (match-end 3)) (not (match-end 6)))
  2729. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2730. (user-error "Invalid row descriptor `%s'" desc))
  2731. (let* ((hdir (and (match-end 2) (match-string 2 desc)))
  2732. (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
  2733. (odir (and (match-end 5) (match-string 5 desc)))
  2734. (on (if (match-end 6) (string-to-number (match-string 6 desc))))
  2735. (i (- cline bline))
  2736. (rel (and (match-end 6)
  2737. (or (and (match-end 1) (not (match-end 3)))
  2738. (match-end 5)))))
  2739. (if (and hn (not hdir))
  2740. (progn
  2741. (setq i 0 hdir "+")
  2742. (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
  2743. (if (and (not hn) on (not odir))
  2744. (user-error "Should never happen");;(aref org-table-dlines on)
  2745. (if (and hn (> hn 0))
  2746. (setq i (org-table-find-row-type table i 'hline (equal hdir "-")
  2747. nil hn cline desc)))
  2748. (if on
  2749. (setq i (org-table-find-row-type table i 'dline (equal odir "-")
  2750. rel on cline desc)))
  2751. (+ bline i)))))
  2752. (defun org-table-find-row-type (table i type backwards relative n cline desc)
  2753. "FIXME: Needs more documentation."
  2754. (let ((l (length table)))
  2755. (while (> n 0)
  2756. (while (and (setq i (+ i (if backwards -1 1)))
  2757. (>= i 0) (< i l)
  2758. (not (eq (aref table i) type))
  2759. (if (and relative (eq (aref table i) 'hline))
  2760. (cond
  2761. ((eq org-table-relative-ref-may-cross-hline t) t)
  2762. ((eq org-table-relative-ref-may-cross-hline 'error)
  2763. (user-error "Row descriptor %s used in line %d crosses hline" desc cline))
  2764. (t (setq i (- i (if backwards -1 1))
  2765. n 1)
  2766. nil))
  2767. t)))
  2768. (setq n (1- n)))
  2769. (if (or (< i 0) (>= i l))
  2770. (user-error "Row descriptor %s used in line %d leads outside table"
  2771. desc cline)
  2772. i)))
  2773. (defun org-table--error-on-old-row-references (s)
  2774. (when (string-match "&[-+0-9I]" s)
  2775. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2776. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2777. "Convert list ELEMENTS to something appropriate to insert into formula.
  2778. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2779. NUMBERS indicates that everything should be converted to numbers.
  2780. LISPP non-nil means to return something appropriate for a Lisp
  2781. list, 'literal is for the format specifier L."
  2782. ;; Calc nan (not a number) is used for the conversion of the empty
  2783. ;; field to a reference for several reasons: (i) It is accepted in a
  2784. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2785. ;; (ii) In a single field (not in range) it can be distinguished
  2786. ;; from "(nan)" which is the reference made from a single field
  2787. ;; containing "nan".
  2788. (if (stringp elements)
  2789. ;; field reference
  2790. (if lispp
  2791. (if (eq lispp 'literal)
  2792. elements
  2793. (if (and (eq elements "") (not keep-empty))
  2794. ""
  2795. (prin1-to-string
  2796. (if numbers (string-to-number elements) elements))))
  2797. (if (string-match "\\S-" elements)
  2798. (progn
  2799. (when numbers (setq elements (number-to-string
  2800. (string-to-number elements))))
  2801. (concat "(" elements ")"))
  2802. (if (or (not keep-empty) numbers) "(0)" "nan")))
  2803. ;; range reference
  2804. (unless keep-empty
  2805. (setq elements
  2806. (delq nil
  2807. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2808. elements))))
  2809. (setq elements (or elements '())) ; if delq returns nil then we need '()
  2810. (if lispp
  2811. (mapconcat
  2812. (lambda (x)
  2813. (if (eq lispp 'literal)
  2814. x
  2815. (prin1-to-string (if numbers (string-to-number x) x))))
  2816. elements " ")
  2817. (concat "[" (mapconcat
  2818. (lambda (x)
  2819. (if (string-match "\\S-" x)
  2820. (if numbers
  2821. (number-to-string (string-to-number x))
  2822. x)
  2823. (if (or (not keep-empty) numbers) "0" "nan")))
  2824. elements
  2825. ",") "]"))))
  2826. (defun org-table-message-once-per-second (t1 &rest args)
  2827. "If there has been more than one second since T1, display message.
  2828. ARGS are passed as arguments to the `message' function. Returns
  2829. current time if a message is printed, otherwise returns T1. If
  2830. T1 is nil, always messages."
  2831. (let ((curtime (current-time)))
  2832. (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
  2833. (progn (apply 'message args)
  2834. curtime)
  2835. t1)))
  2836. ;;;###autoload
  2837. (defun org-table-recalculate (&optional all noalign)
  2838. "Recalculate the current table line by applying all stored formulas.
  2839. With prefix arg ALL, do this for all lines in the table.
  2840. With the prefix argument ALL is `(16)' \
  2841. \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
  2842. it is the symbol `iterate', recompute the table until it no longer changes.
  2843. If NOALIGN is not nil, do not re-align the table after the computations
  2844. are done. This is typically used internally to save time, if it is
  2845. known that the table will be realigned a little later anyway."
  2846. (interactive "P")
  2847. (or (memq this-command org-recalc-commands)
  2848. (setq org-recalc-commands (cons this-command org-recalc-commands)))
  2849. (unless (org-at-table-p) (user-error "Not at a table"))
  2850. (if (or (eq all 'iterate) (equal all '(16)))
  2851. (org-table-iterate)
  2852. (org-table-get-specials)
  2853. (let* ((eqlist (sort (org-table-get-stored-formulas)
  2854. (lambda (a b) (string< (car a) (car b)))))
  2855. (eqlist1 (copy-sequence eqlist))
  2856. (inhibit-redisplay (not debug-on-error))
  2857. (line-re org-table-dataline-regexp)
  2858. (thisline (org-current-line))
  2859. (thiscol (org-table-current-column))
  2860. (log-first-time (current-time))
  2861. (log-last-time log-first-time)
  2862. seen-fields lhs1
  2863. beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name name1)
  2864. ;; Insert constants in all formulas
  2865. (when eqlist
  2866. (setq eqlist
  2867. (mapcar
  2868. (lambda (x)
  2869. (if (string-match "^@-?I+" (car x))
  2870. (user-error "Can't assign to hline relative reference"))
  2871. (when (string-match "\\`$[<>]" (car x))
  2872. (setq lhs1 (car x))
  2873. (setq x (cons (substring
  2874. (org-table-formula-handle-first/last-rc
  2875. (car x)) 1)
  2876. (cdr x)))
  2877. (if (assoc (car x) eqlist1)
  2878. (user-error "\"%s=\" formula tries to overwrite existing formula for column %s"
  2879. lhs1 (car x))))
  2880. (cons
  2881. (org-table-formula-handle-first/last-rc (car x))
  2882. (org-table-formula-substitute-names
  2883. (org-table-formula-handle-first/last-rc (cdr x)))))
  2884. eqlist))
  2885. ;; Split the equation list
  2886. (while (setq eq (pop eqlist))
  2887. (if (<= (string-to-char (car eq)) ?9)
  2888. (push eq eqlnum)
  2889. (push eq eqlname)))
  2890. (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
  2891. ;; Expand ranges in lhs of formulas
  2892. (setq eqlname (org-table-expand-lhs-ranges eqlname))
  2893. ;; Get the correct line range to process
  2894. (if all
  2895. (progn
  2896. (setq end (move-marker (make-marker) (1+ (org-table-end))))
  2897. (goto-char (setq beg (org-table-begin)))
  2898. (if (re-search-forward org-table-calculate-mark-regexp end t)
  2899. ;; This is a table with marked lines, compute selected lines
  2900. (setq line-re org-table-recalculate-regexp)
  2901. ;; Move forward to the first non-header line
  2902. (if (and (re-search-forward org-table-dataline-regexp end t)
  2903. (re-search-forward org-table-hline-regexp end t)
  2904. (re-search-forward org-table-dataline-regexp end t))
  2905. (setq beg (match-beginning 0))
  2906. nil))) ;; just leave beg where it is
  2907. (setq beg (point-at-bol)
  2908. end (move-marker (make-marker) (1+ (point-at-eol)))))
  2909. (goto-char beg)
  2910. ;; First find the named fields, and mark them untouchable.
  2911. ;; Also check if several field/range formulas try to set the same field.
  2912. (remove-text-properties beg end '(org-untouchable t))
  2913. (while (setq eq (pop eqlname))
  2914. (setq name (car eq)
  2915. a (assoc name org-table-named-field-locations))
  2916. (setq name1 name)
  2917. (if a (setq name1 (format "@%d$%d" (org-table-line-to-dline (nth 1 a))
  2918. (nth 2 a))))
  2919. (when (member name1 seen-fields)
  2920. (user-error "Several field/range formulas try to set %s" name1))
  2921. (push name1 seen-fields)
  2922. (and (not a)
  2923. (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
  2924. (setq a (list name
  2925. (condition-case nil
  2926. (aref org-table-dlines
  2927. (string-to-number (match-string 1 name)))
  2928. (error (user-error "Invalid row number in %s"
  2929. name)))
  2930. (string-to-number (match-string 2 name)))))
  2931. (when (and a (or all (equal (nth 1 a) thisline)))
  2932. (setq log-last-time
  2933. (org-table-message-once-per-second
  2934. (and all log-last-time)
  2935. "Re-applying formula to field: %s" name))
  2936. (org-goto-line (nth 1 a))
  2937. (org-table-goto-column (nth 2 a))
  2938. (push (append a (list (cdr eq))) eqlname1)
  2939. (org-table-put-field-property :org-untouchable t)))
  2940. (setq eqlname1 (nreverse eqlname1))
  2941. ;; Now evaluate the column formulas, but skip fields covered
  2942. ;; by field formulas
  2943. (goto-char beg)
  2944. (while (re-search-forward line-re end t)
  2945. (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
  2946. ;; Unprotected line, recalculate
  2947. (setq cnt (1+ cnt))
  2948. (and all (setq log-last-time
  2949. (org-table-message-once-per-second
  2950. log-last-time
  2951. "Re-applying formulas to full table...(line %d)" cnt)))
  2952. (setq org-last-recalc-line (org-current-line))
  2953. (setq eql eqlnum)
  2954. (while (setq entry (pop eql))
  2955. (org-goto-line org-last-recalc-line)
  2956. (org-table-goto-column (string-to-number (car entry)) nil 'force)
  2957. (unless (get-text-property (point) :org-untouchable)
  2958. (org-table-eval-formula
  2959. nil (cdr entry)
  2960. 'noalign 'nocst 'nostore 'noanalysis)))))
  2961. ;; Now evaluate the field formulas
  2962. (while (setq eq (pop eqlname1))
  2963. (setq log-last-time
  2964. (org-table-message-once-per-second
  2965. (and all log-last-time)
  2966. "Re-applying formula to field: %s" (car eq)))
  2967. (org-goto-line (nth 1 eq))
  2968. (let ((column-target (nth 2 eq)))
  2969. (when (> column-target 1000)
  2970. (user-error "Formula column target too large"))
  2971. (let* ((column-count (progn (end-of-line)
  2972. (1- (org-table-current-column))))
  2973. (create-new-column
  2974. (and (> column-target column-count)
  2975. (or (eq org-table-formula-create-columns t)
  2976. (and
  2977. (eq org-table-formula-create-columns 'warn)
  2978. (progn
  2979. (org-display-warning
  2980. "Out-of-bounds formula added columns")
  2981. t))
  2982. (and
  2983. (eq org-table-formula-create-columns 'prompt)
  2984. (yes-or-no-p
  2985. "Out-of-bounds formula. Add columns?"))))))
  2986. (org-table-goto-column column-target nil create-new-column))
  2987. (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
  2988. 'nostore 'noanalysis)))
  2989. (org-goto-line thisline)
  2990. (org-table-goto-column thiscol)
  2991. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  2992. (or noalign (and org-table-may-need-update (org-table-align))
  2993. (and all (org-table-message-once-per-second
  2994. log-first-time
  2995. "Re-applying formulas to %d lines...done" cnt)))
  2996. ;; back to initial position
  2997. (org-table-message-once-per-second
  2998. (and all log-first-time)
  2999. "Re-applying formulas...done")
  3000. (org-goto-line thisline)
  3001. (org-table-goto-column thiscol)
  3002. (or noalign (and org-table-may-need-update (org-table-align)))))))
  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. ("Plot"
  4101. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4102. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4103. t))
  4104. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4105. "If the cursor is inside a table, realign the table.
  4106. If it is a table to be sent away to a receiver, do it.
  4107. With prefix arg, also recompute table."
  4108. (interactive "P")
  4109. (let ((case-fold-search t) (pos (point)) action)
  4110. (save-excursion
  4111. (beginning-of-line 1)
  4112. (setq action (cond
  4113. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4114. ((looking-at "[ \t]*|") pos)
  4115. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4116. (cond
  4117. ((integerp action)
  4118. (goto-char action)
  4119. (org-table-maybe-eval-formula)
  4120. (if arg
  4121. (call-interactively 'org-table-recalculate)
  4122. (org-table-maybe-recalculate-line))
  4123. (call-interactively 'org-table-align)
  4124. (when (orgtbl-send-table 'maybe)
  4125. (run-hooks 'orgtbl-after-send-table-hook)))
  4126. ((eq action 'recalc)
  4127. (save-excursion
  4128. (beginning-of-line 1)
  4129. (skip-chars-backward " \r\n\t")
  4130. (if (org-at-table-p)
  4131. (org-call-with-arg 'org-table-recalculate t))))
  4132. (t (let (orgtbl-mode)
  4133. (call-interactively (key-binding "\C-c\C-c")))))))
  4134. (defun orgtbl-create-or-convert-from-region (arg)
  4135. "Create table or convert region to table, if no conflicting binding.
  4136. This installs the table binding `C-c |', but only if there is no
  4137. conflicting binding to this key outside orgtbl-mode."
  4138. (interactive "P")
  4139. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4140. (if cmd
  4141. (call-interactively cmd)
  4142. (call-interactively 'org-table-create-or-convert-from-region))))
  4143. (defun orgtbl-tab (arg)
  4144. "Justification and field motion for `orgtbl-mode'."
  4145. (interactive "P")
  4146. (if arg (org-table-edit-field t)
  4147. (org-table-justify-field-maybe)
  4148. (org-table-next-field)))
  4149. (defun orgtbl-ret ()
  4150. "Justification and field motion for `orgtbl-mode'."
  4151. (interactive)
  4152. (if (bobp)
  4153. (newline)
  4154. (org-table-justify-field-maybe)
  4155. (org-table-next-row)))
  4156. (defun orgtbl-self-insert-command (N)
  4157. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4158. If the cursor is in a table looking at whitespace, the whitespace is
  4159. overwritten, and the table is not marked as requiring realignment."
  4160. (interactive "p")
  4161. (if (and (org-at-table-p)
  4162. (or
  4163. (and org-table-auto-blank-field
  4164. (member last-command
  4165. '(orgtbl-hijacker-command-100
  4166. orgtbl-hijacker-command-101
  4167. orgtbl-hijacker-command-102
  4168. orgtbl-hijacker-command-103
  4169. orgtbl-hijacker-command-104
  4170. orgtbl-hijacker-command-105
  4171. yas/expand))
  4172. (org-table-blank-field))
  4173. t)
  4174. (eq N 1)
  4175. (looking-at "[^|\n]* +|"))
  4176. (let (org-table-may-need-update)
  4177. (goto-char (1- (match-end 0)))
  4178. (org-delete-backward-char 1)
  4179. (goto-char (match-beginning 0))
  4180. (self-insert-command N))
  4181. (setq org-table-may-need-update t)
  4182. (let* (orgtbl-mode
  4183. a
  4184. (cmd (or (key-binding
  4185. (or (and (listp function-key-map)
  4186. (setq a (assoc last-input-event function-key-map))
  4187. (cdr a))
  4188. (vector last-input-event)))
  4189. 'self-insert-command)))
  4190. (call-interactively cmd)
  4191. (if (and org-self-insert-cluster-for-undo
  4192. (eq cmd 'self-insert-command))
  4193. (if (not (eq last-command 'orgtbl-self-insert-command))
  4194. (setq org-self-insert-command-undo-counter 1)
  4195. (if (>= org-self-insert-command-undo-counter 20)
  4196. (setq org-self-insert-command-undo-counter 1)
  4197. (and (> org-self-insert-command-undo-counter 0)
  4198. buffer-undo-list
  4199. (not (cadr buffer-undo-list)) ; remove nil entry
  4200. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  4201. (setq org-self-insert-command-undo-counter
  4202. (1+ org-self-insert-command-undo-counter))))))))
  4203. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  4204. "Regular expression matching exponentials as produced by calc.")
  4205. (defun orgtbl-gather-send-defs ()
  4206. "Gather a plist of :name, :transform, :params for each destination before
  4207. a radio table."
  4208. (save-excursion
  4209. (goto-char (org-table-begin))
  4210. (let (rtn)
  4211. (beginning-of-line 0)
  4212. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  4213. (let ((name (org-no-properties (match-string 1)))
  4214. (transform (intern (match-string 2)))
  4215. (params (if (match-end 3)
  4216. (read (concat "(" (match-string 3) ")")))))
  4217. (push (list :name name :transform transform :params params)
  4218. rtn)
  4219. (beginning-of-line 0)))
  4220. rtn)))
  4221. (defun orgtbl-send-replace-tbl (name txt)
  4222. "Find and replace table NAME with TXT."
  4223. (save-excursion
  4224. (goto-char (point-min))
  4225. (unless (re-search-forward
  4226. (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
  4227. (user-error "Don't know where to insert translated table"))
  4228. (let ((beg (line-beginning-position 2)))
  4229. (unless (re-search-forward
  4230. (concat "END +RECEIVE +ORGTBL +" name) nil t)
  4231. (user-error "Cannot find end of insertion region"))
  4232. (beginning-of-line)
  4233. (delete-region beg (point)))
  4234. (insert txt "\n")))
  4235. ;;;###autoload
  4236. (defun org-table-to-lisp (&optional txt)
  4237. "Convert the table at point to a Lisp structure.
  4238. The structure will be a list. Each item is either the symbol `hline'
  4239. for a horizontal separator line, or a list of field values as strings.
  4240. The table is taken from the parameter TXT, or from the buffer at point."
  4241. (unless (or txt (org-at-table-p)) (user-error "No table at point"))
  4242. (let ((txt (or txt
  4243. (buffer-substring-no-properties (org-table-begin)
  4244. (org-table-end)))))
  4245. (mapcar (lambda (x)
  4246. (if (string-match org-table-hline-regexp x) 'hline
  4247. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  4248. (org-split-string txt "[ \t]*\n[ \t]*"))))
  4249. (defun orgtbl-send-table (&optional maybe)
  4250. "Send a transformed version of table at point to the receiver position.
  4251. With argument MAYBE, fail quietly if no transformation is defined
  4252. for this table."
  4253. (interactive)
  4254. (catch 'exit
  4255. (unless (org-at-table-p) (user-error "Not at a table"))
  4256. ;; when non-interactive, we assume align has just happened.
  4257. (when (org-called-interactively-p 'any) (org-table-align))
  4258. (let ((dests (orgtbl-gather-send-defs))
  4259. (table (org-table-to-lisp
  4260. (buffer-substring-no-properties (org-table-begin)
  4261. (org-table-end))))
  4262. (ntbl 0))
  4263. (unless dests
  4264. (if maybe (throw 'exit nil)
  4265. (user-error "Don't know how to transform this table")))
  4266. (dolist (dest dests)
  4267. (let ((name (plist-get dest :name))
  4268. (transform (plist-get dest :transform))
  4269. (params (plist-get dest :params)))
  4270. (unless (fboundp transform)
  4271. (user-error "No such transformation function %s" transform))
  4272. (orgtbl-send-replace-tbl name (funcall transform table params)))
  4273. (incf ntbl))
  4274. (message "Table converted and installed at %d receiver location%s"
  4275. ntbl (if (> ntbl 1) "s" ""))
  4276. (and (> ntbl 0) ntbl))))
  4277. (defun org-remove-by-index (list indices &optional i0)
  4278. "Remove the elements in LIST with indices in INDICES.
  4279. First element has index 0, or I0 if given."
  4280. (if (not indices)
  4281. list
  4282. (if (integerp indices) (setq indices (list indices)))
  4283. (setq i0 (1- (or i0 0)))
  4284. (delq :rm (mapcar (lambda (x)
  4285. (setq i0 (1+ i0))
  4286. (if (memq i0 indices) :rm x))
  4287. list))))
  4288. (defun orgtbl-toggle-comment ()
  4289. "Comment or uncomment the orgtbl at point."
  4290. (interactive)
  4291. (let* ((case-fold-search t)
  4292. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  4293. (re2 (concat "^" orgtbl-line-start-regexp))
  4294. (commented (save-excursion (beginning-of-line 1)
  4295. (cond ((looking-at re1) t)
  4296. ((looking-at re2) nil)
  4297. (t (user-error "Not at an org table")))))
  4298. (re (if commented re1 re2))
  4299. beg end)
  4300. (save-excursion
  4301. (beginning-of-line 1)
  4302. (while (looking-at re) (beginning-of-line 0))
  4303. (beginning-of-line 2)
  4304. (setq beg (point))
  4305. (while (looking-at re) (beginning-of-line 2))
  4306. (setq end (point)))
  4307. (comment-region beg end (if commented '(4) nil))))
  4308. (defun orgtbl-insert-radio-table ()
  4309. "Insert a radio table template appropriate for this major mode."
  4310. (interactive)
  4311. (let* ((e (assq major-mode orgtbl-radio-table-templates))
  4312. (txt (nth 1 e))
  4313. name pos)
  4314. (unless e (user-error "No radio table setup defined for %s" major-mode))
  4315. (setq name (read-string "Table name: "))
  4316. (while (string-match "%n" txt)
  4317. (setq txt (replace-match name t t txt)))
  4318. (or (bolp) (insert "\n"))
  4319. (setq pos (point))
  4320. (insert txt)
  4321. (goto-char pos)))
  4322. ;;;###autoload
  4323. (defun orgtbl-to-generic (table params)
  4324. "Convert the orgtbl-mode TABLE to some other format.
  4325. This generic routine can be used for many standard cases.
  4326. TABLE is a list, each entry either the symbol `hline' for
  4327. a horizontal separator line, or a list of fields for that
  4328. line. PARAMS is a property list of parameters that can
  4329. influence the conversion.
  4330. Valid parameters are:
  4331. :backend, :raw
  4332. Export back-end used as a basis to transcode elements of the
  4333. table, when no specific parameter applies to it. It is also
  4334. used to translate cells contents. You can prevent this by
  4335. setting :raw property to a non-nil value.
  4336. :splice
  4337. When non-nil, only convert rows, not the table itself. This is
  4338. equivalent to setting to the empty string both :tstart
  4339. and :tend, which see.
  4340. :skip
  4341. When set to an integer N, skip the first N lines of the table.
  4342. Horizontal separation lines do count for this parameter!
  4343. :skipcols
  4344. List of columns that should be skipped. If the table has
  4345. a column with calculation marks, that column is automatically
  4346. discarded beforehand.
  4347. :hline
  4348. String to be inserted on horizontal separation lines. May be
  4349. nil to ignore these lines altogether.
  4350. :sep
  4351. Separator between two fields, as a string.
  4352. Each in the following group may be either a string or a function
  4353. of no arguments returning a string:
  4354. :tstart, :tend
  4355. Strings to start and end the table. Ignored when :splice is t.
  4356. :lstart, :lend
  4357. Strings to start and end a new table line.
  4358. :llstart, :llend
  4359. Strings to start and end the last table line. Default,
  4360. respectively, to :lstart and :lend.
  4361. Each in the following group may be a string or a function of one
  4362. argument (either the cells in the current row, as a list of
  4363. strings, or the current cell) returning a string:
  4364. :lfmt
  4365. Format string for an entire row, with enough %s to capture all
  4366. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  4367. :llfmt
  4368. Format for the entire last line, defaults to :lfmt.
  4369. :fmt
  4370. A format to be used to wrap the field, should contain %s for
  4371. the original field value. For example, to wrap everything in
  4372. dollars, you could use :fmt \"$%s$\". This may also be
  4373. a property list with column numbers and format strings, or
  4374. functions, e.g.,
  4375. \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  4376. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  4377. Same as above, specific for the header lines in the table.
  4378. All lines before the first hline are treated as header. If
  4379. any of these is not present, the data line value is used.
  4380. This may be either a string or a function of two arguments:
  4381. :efmt
  4382. Use this format to print numbers with exponential. The format
  4383. should have %s twice for inserting mantissa and exponent, for
  4384. example \"%s\\\\times10^{%s}\". This may also be a property
  4385. list with column numbers and format strings or functions.
  4386. :fmt will still be applied after :efmt."
  4387. (let ((backend (plist-get params :backend)))
  4388. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  4389. (user-error "Unknown :backend value"))
  4390. (when (or (not backend) (plist-get params :raw)) (require 'ox-org))
  4391. (org-trim
  4392. (org-export-string-as
  4393. ;; Return TABLE as Org syntax. Tolerate non-string cells.
  4394. (with-output-to-string
  4395. (dolist (e table)
  4396. (cond ((eq e 'hline) (princ "|--\n"))
  4397. ((consp e)
  4398. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  4399. (princ "\n")))))
  4400. ;; Build a custom back-end according to PARAMS. Before defining
  4401. ;; a translator, check if there is anything to do. When there
  4402. ;; isn't, let BACKEND handle the element.
  4403. (org-export-create-backend
  4404. :parent (or backend 'org)
  4405. :filters
  4406. '((:filter-parse-tree
  4407. ;; Handle :skip parameter.
  4408. (lambda (tree backend info)
  4409. (let ((skip (plist-get info :skip)))
  4410. (when skip
  4411. (unless (wholenump skip) (user-error "Wrong :skip value"))
  4412. (let ((n 0))
  4413. (org-element-map tree 'table-row
  4414. (lambda (row)
  4415. (if (>= n skip) t
  4416. (org-element-extract-element row)
  4417. (incf n)
  4418. nil))
  4419. info t))
  4420. tree)))
  4421. ;; Handle :skipcols parameter.
  4422. (lambda (tree backend info)
  4423. (let ((skipcols (plist-get info :skipcols)))
  4424. (when skipcols
  4425. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  4426. (org-element-map tree 'table
  4427. (lambda (table)
  4428. (let ((specialp
  4429. (org-export-table-has-special-column-p table)))
  4430. (dolist (row (org-element-contents table))
  4431. (when (eq (org-element-property :type row) 'standard)
  4432. (let ((c 1))
  4433. (dolist (cell (nthcdr (if specialp 1 0)
  4434. (org-element-contents row)))
  4435. (when (memq c skipcols)
  4436. (org-element-extract-element cell))
  4437. (incf c)))))))
  4438. info)
  4439. tree)))))
  4440. :transcoders
  4441. `((table . ,(org-table--to-generic-table params))
  4442. (table-row . ,(org-table--to-generic-row params))
  4443. (table-cell . ,(org-table--to-generic-cell params))
  4444. ;; Section. Return contents to avoid garbage around table.
  4445. (section . (lambda (s c i) c))))
  4446. 'body-only (org-combine-plists params '(:with-tables t))))))
  4447. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  4448. (cond ((null value) nil)
  4449. ((functionp value) `(funcall ',value ,@args))
  4450. ((stringp value)
  4451. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  4452. (args `(format ,value ,@args))
  4453. (t value)))
  4454. ((and with-cons (consp value))
  4455. `(let ((val (cadr (memq column ',value))))
  4456. (cond ((null val) contents)
  4457. ((stringp val) (format val ,@args))
  4458. ((functionp val) (funcall val ,@args))
  4459. (t (user-error "Wrong %s value" ,name)))))
  4460. (t (user-error "Wrong %s value" name))))
  4461. (defun org-table--to-generic-table (params)
  4462. "Return custom table transcoder according to PARAMS.
  4463. PARAMS is a plist. See `orgtbl-to-generic' for more
  4464. information."
  4465. (let ((backend (plist-get params :backend))
  4466. (splice (plist-get params :splice))
  4467. (tstart (plist-get params :tstart))
  4468. (tend (plist-get params :tend)))
  4469. `(lambda (table contents info)
  4470. (concat
  4471. ,(and tstart (not splice)
  4472. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  4473. ,(if (or (not backend) tstart tend splice) 'contents
  4474. `(org-export-with-backend ',backend table contents info))
  4475. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  4476. (defun org-table--to-generic-row (params)
  4477. "Return custom table row transcoder according to PARAMS.
  4478. PARAMS is a plist. See `orgtbl-to-generic' for more
  4479. information."
  4480. (let* ((backend (plist-get params :backend))
  4481. (lstart (plist-get params :lstart))
  4482. (llstart (plist-get params :llstart))
  4483. (hlstart (plist-get params :hlstart))
  4484. (hllstart (plist-get params :hllstart))
  4485. (lend (plist-get params :lend))
  4486. (llend (plist-get params :llend))
  4487. (hlend (plist-get params :hlend))
  4488. (hllend (plist-get params :hllend))
  4489. (lfmt (plist-get params :lfmt))
  4490. (llfmt (plist-get params :llfmt))
  4491. (hlfmt (plist-get params :hlfmt))
  4492. (hllfmt (plist-get params :hllfmt)))
  4493. `(lambda (row contents info)
  4494. (if (eq (org-element-property :type row) 'rule)
  4495. ,(cond
  4496. ((plist-member params :hline)
  4497. (org-table--generic-apply (plist-get params :hline) ":hline"))
  4498. (backend `(org-export-with-backend ',backend row nil info)))
  4499. (let ((headerp (org-export-table-row-in-header-p row info))
  4500. (lastp (not (org-export-get-next-element row info)))
  4501. (last-header-p (org-export-table-row-ends-header-p row info)))
  4502. (when contents
  4503. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  4504. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  4505. ;; `:lstart', `:lend' and their relatives.
  4506. ,(let ((cells
  4507. '(org-element-map row 'table-cell
  4508. (lambda (cell)
  4509. ;; Export all cells, without separators.
  4510. ;;
  4511. ;; Use `org-export-data-with-backend'
  4512. ;; instead of `org-export-data' to eschew
  4513. ;; cached values, which
  4514. ;; ignore :orgtbl-ignore-sep parameter.
  4515. (org-export-data-with-backend
  4516. cell
  4517. (plist-get info :back-end)
  4518. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  4519. info)))
  4520. `(cond
  4521. ,(and hllfmt
  4522. `(last-header-p ,(org-table--generic-apply
  4523. hllfmt ":hllfmt" nil cells)))
  4524. ,(and hlfmt
  4525. `(headerp ,(org-table--generic-apply
  4526. hlfmt ":hlfmt" nil cells)))
  4527. ,(and llfmt
  4528. `(lastp ,(org-table--generic-apply
  4529. llfmt ":llfmt" nil cells)))
  4530. (t
  4531. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  4532. `(concat
  4533. (cond
  4534. ,(and
  4535. (or hllstart hllend)
  4536. `(last-header-p
  4537. (concat
  4538. ,(org-table--generic-apply hllstart ":hllstart")
  4539. contents
  4540. ,(org-table--generic-apply hllend ":hllend"))))
  4541. ,(and
  4542. (or hlstart hlend)
  4543. `(headerp
  4544. (concat
  4545. ,(org-table--generic-apply hlstart ":hlstart")
  4546. contents
  4547. ,(org-table--generic-apply hlend ":hlend"))))
  4548. ,(and
  4549. (or llstart llend)
  4550. `(lastp
  4551. (concat
  4552. ,(org-table--generic-apply llstart ":llstart")
  4553. contents
  4554. ,(org-table--generic-apply llend ":llend"))))
  4555. (t
  4556. ,(cond
  4557. ((or lstart lend)
  4558. `(concat
  4559. ,(org-table--generic-apply lstart ":lstart")
  4560. contents
  4561. ,(org-table--generic-apply lend ":lend")))
  4562. (backend
  4563. `(org-export-with-backend
  4564. ',backend row contents info))
  4565. (t 'contents)))))))))))))))
  4566. (defun org-table--to-generic-cell (params)
  4567. "Return custom table cell transcoder according to PARAMS.
  4568. PARAMS is a plist. See `orgtbl-to-generic' for more
  4569. information."
  4570. (let* ((backend (plist-get params :backend))
  4571. (efmt (plist-get params :efmt))
  4572. (fmt (plist-get params :fmt))
  4573. (hfmt (plist-get params :hfmt))
  4574. (sep (plist-get params :sep))
  4575. (hsep (plist-get params :hsep)))
  4576. `(lambda (cell contents info)
  4577. (let ((headerp (org-export-table-row-in-header-p
  4578. (org-export-get-parent-element cell) info))
  4579. (column (1+ (cdr (org-export-table-cell-address cell info)))))
  4580. ;; Make sure that contents are exported as Org data when :raw
  4581. ;; parameter is non-nil.
  4582. ,(when (and backend (plist-get params :raw))
  4583. `(setq contents
  4584. ;; Since we don't know what are the pseudo object
  4585. ;; types defined in backend, we cannot pass them to
  4586. ;; `org-element-interpret-data'. As a consequence,
  4587. ;; they will be treated as pseudo elements, and
  4588. ;; will have newlines appended instead of spaces.
  4589. ;; Therefore, we must make sure :post-blank value
  4590. ;; is really turned into spaces.
  4591. (replace-regexp-in-string
  4592. "\n" " "
  4593. (org-trim
  4594. (org-element-interpret-data
  4595. (org-element-contents cell))))))
  4596. (when contents
  4597. ;; Check if we can apply `:efmt' on CONTENTS.
  4598. ,(when efmt
  4599. `(when (string-match orgtbl-exp-regexp contents)
  4600. (let ((mantissa (match-string 1 contents))
  4601. (exponent (match-string 2 contents)))
  4602. (setq contents ,(org-table--generic-apply
  4603. efmt ":efmt" t 'mantissa 'exponent)))))
  4604. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  4605. (cond
  4606. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  4607. hfmt ":hfmt" t 'contents))))
  4608. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  4609. fmt ":fmt" t 'contents))))))
  4610. ;; If a separator is provided, use it instead of BACKEND's.
  4611. ;; Separators are ignored when LFMT (or equivalent) is
  4612. ;; provided.
  4613. ,(cond
  4614. ((or hsep sep)
  4615. `(if (or ,(and (not sep) '(not headerp))
  4616. (plist-get info :orgtbl-ignore-sep)
  4617. (not (org-export-get-next-element cell info)))
  4618. ,(if (not backend) 'contents
  4619. `(org-export-with-backend ',backend cell contents info))
  4620. (concat contents
  4621. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  4622. (or hsep sep)))))
  4623. (backend `(org-export-with-backend ',backend cell contents info))
  4624. (t 'contents))))))
  4625. ;;;###autoload
  4626. (defun orgtbl-to-tsv (table params)
  4627. "Convert the orgtbl-mode table to TAB separated material."
  4628. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  4629. ;;;###autoload
  4630. (defun orgtbl-to-csv (table params)
  4631. "Convert the orgtbl-mode table to CSV material.
  4632. This does take care of the proper quoting of fields with comma or quotes."
  4633. (orgtbl-to-generic table
  4634. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  4635. params)))
  4636. ;;;###autoload
  4637. (defun orgtbl-to-latex (table params)
  4638. "Convert the orgtbl-mode TABLE to LaTeX.
  4639. TABLE is a list, each entry either the symbol `hline' for
  4640. a horizontal separator line, or a list of fields for that line.
  4641. PARAMS is a property list of parameters that can influence the
  4642. conversion. All parameters from `orgtbl-to-generic' are
  4643. supported. It is also possible to use the following ones:
  4644. :booktabs
  4645. When non-nil, use formal \"booktabs\" style.
  4646. :environment
  4647. Specify environment to use, as a string. If you use
  4648. \"longtable\", you may also want to specify :language property,
  4649. as a string, to get proper continuation strings."
  4650. (require 'ox-latex)
  4651. (orgtbl-to-generic
  4652. table
  4653. (org-combine-plists
  4654. ;; Provide sane default values.
  4655. (list :backend 'latex
  4656. :latex-default-table-mode 'table
  4657. :latex-tables-centered nil
  4658. :latex-tables-booktabs (plist-get params :booktabs)
  4659. :latex-table-scientific-notation nil
  4660. :latex-default-table-environment
  4661. (or (plist-get params :environment) "tabular"))
  4662. params)))
  4663. ;;;###autoload
  4664. (defun orgtbl-to-html (table params)
  4665. "Convert the orgtbl-mode TABLE to HTML.
  4666. TABLE is a list, each entry either the symbol `hline' for
  4667. a horizontal separator line, or a list of fields for that line.
  4668. PARAMS is a property list of parameters that can influence the
  4669. conversion. All parameters from `orgtbl-to-generic' are
  4670. supported. It is also possible to use the following one:
  4671. :attributes
  4672. Attributes and values, as a plist, which will be used in
  4673. <table> tag."
  4674. (require 'ox-html)
  4675. (orgtbl-to-generic
  4676. table
  4677. (org-combine-plists
  4678. ;; Provide sane default values.
  4679. (list :backend 'html
  4680. :html-table-data-tags '("<td%s>" . "</td>")
  4681. :html-table-use-header-tags-for-first-column nil
  4682. :html-table-align-individual-fields t
  4683. :html-table-row-tags '("<tr>" . "</tr>")
  4684. :html-table-attributes
  4685. (if (plist-member params :attributes)
  4686. (plist-get params :attributes)
  4687. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  4688. :frame "hsides")))
  4689. params)))
  4690. ;;;###autoload
  4691. (defun orgtbl-to-texinfo (table params)
  4692. "Convert the orgtbl-mode TABLE to Texinfo.
  4693. TABLE is a list, each entry either the symbol `hline' for
  4694. a horizontal separator line, or a list of fields for that line.
  4695. PARAMS is a property list of parameters that can influence the
  4696. conversion. All parameters from `orgtbl-to-generic' are
  4697. supported. It is also possible to use the following one:
  4698. :columns
  4699. Column widths, as a string. When providing column fractions,
  4700. \"@columnfractions\" command can be omitted."
  4701. (require 'ox-texinfo)
  4702. (let ((output
  4703. (orgtbl-to-generic
  4704. table
  4705. (org-combine-plists
  4706. (list :backend 'texinfo
  4707. :texinfo-tables-verbatim nil
  4708. :texinfo-table-scientific-notation nil)
  4709. params)))
  4710. (columns (let ((w (plist-get params :columns)))
  4711. (cond ((not w) nil)
  4712. ((org-string-match-p "{\\|@columnfractions " w) w)
  4713. (t (concat "@columnfractions " w))))))
  4714. (if (not columns) output
  4715. (replace-regexp-in-string
  4716. "@multitable \\(.*\\)" columns output t nil 1))))
  4717. ;;;###autoload
  4718. (defun orgtbl-to-orgtbl (table params)
  4719. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  4720. TABLE is a list, each entry either the symbol `hline' for
  4721. a horizontal separator line, or a list of fields for that line.
  4722. PARAMS is a property list of parameters that can influence the
  4723. conversion. All parameters from `orgtbl-to-generic' are
  4724. supported.
  4725. Useful when slicing one table into many. The :hline, :sep,
  4726. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  4727. be set to provide ORGTBL directives for the generated table."
  4728. (require 'ox-org)
  4729. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  4730. (defun orgtbl-to-table.el (table params)
  4731. "Convert the orgtbl-mode TABLE into a table.el table.
  4732. TABLE is a list, each entry either the symbol `hline' for
  4733. a horizontal separator line, or a list of fields for that line.
  4734. PARAMS is a property list of parameters that can influence the
  4735. conversion. All parameters from `orgtbl-to-generic' are
  4736. supported."
  4737. (with-temp-buffer
  4738. (insert (orgtbl-to-orgtbl table params))
  4739. (org-table-align)
  4740. (replace-regexp-in-string
  4741. "-|" "-+"
  4742. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  4743. (defun orgtbl-to-unicode (table params)
  4744. "Convert the orgtbl-mode TABLE into a table with unicode characters.
  4745. TABLE is a list, each entry either the symbol `hline' for
  4746. a horizontal separator line, or a list of fields for that line.
  4747. PARAMS is a property list of parameters that can influence the
  4748. conversion. All parameters from `orgtbl-to-generic' are
  4749. supported. It is also possible to use the following ones:
  4750. :ascii-art
  4751. When non-nil, use \"ascii-art-to-unicode\" package to translate
  4752. the table. You can download it here:
  4753. http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  4754. :narrow
  4755. When non-nil, narrow columns width than provided width cookie,
  4756. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  4757. (require 'ox-ascii)
  4758. (orgtbl-to-generic
  4759. table
  4760. (org-combine-plists
  4761. (list :backend 'ascii
  4762. :ascii-charset 'utf-8
  4763. :ascii-table-keep-all-vertical-lines (plist-get params :)
  4764. :ascii-table-widen-columns (not (plist-get params :narrow))
  4765. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  4766. params)))
  4767. ;; Put the cursor in a column containing numerical values
  4768. ;; of an Org-Mode table,
  4769. ;; type C-c " a
  4770. ;; A new column is added with a bar plot.
  4771. ;; When the table is refreshed (C-u C-c *),
  4772. ;; the plot is updated to reflect the new values.
  4773. (defun orgtbl-ascii-draw (value min max &optional width characters)
  4774. "Draw an ascii bar in a table.
  4775. VALUE is a the value to plot, the width of the bar to draw. A
  4776. value equal to MIN will be displayed as empty (zero width bar).
  4777. A value equal to MAX will draw a bar filling all the WIDTH.
  4778. WIDTH is the expected width in characters of the column.
  4779. CHARACTERS is a string that will compose the bar, with shades of
  4780. grey from pure white to pure black. It defaults to a 10
  4781. characters string of regular ascii characters."
  4782. (let* ((characters (or characters " .:;c!lhVHW"))
  4783. (width (or width 12))
  4784. (value (if (numberp value) value (string-to-number value)))
  4785. (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
  4786. (cond
  4787. ((< value 0) "too small")
  4788. ((> value width) "too large")
  4789. (t
  4790. (let ((len (1- (length characters))))
  4791. (concat
  4792. (make-string (floor value) (elt characters len))
  4793. (string (elt characters
  4794. (floor (* (- value (floor value)) len))))))))))
  4795. ;;;###autoload
  4796. (defun orgtbl-ascii-plot (&optional ask)
  4797. "Draw an ascii bar plot in a column.
  4798. With cursor in a column containing numerical values, this
  4799. function will draw a plot in a new column.
  4800. ASK, if given, is a numeric prefix to override the default 12
  4801. characters width of the plot. ASK may also be the
  4802. \\[universal-argument] prefix, which will prompt for the width."
  4803. (interactive "P")
  4804. (let ((col (org-table-current-column))
  4805. (min 1e999) ; 1e999 will be converted to infinity
  4806. (max -1e999) ; which is the desired result
  4807. (table (org-table-to-lisp))
  4808. (length
  4809. (cond ((consp ask)
  4810. (read-number "Length of column " 12))
  4811. ((numberp ask) ask)
  4812. (t 12))))
  4813. ;; Skip any hline a the top of table.
  4814. (while (eq (car table) 'hline) (setq table (cdr table)))
  4815. ;; Skip table header if any.
  4816. (dolist (x (or (cdr (memq 'hline table)) table))
  4817. (when (consp x)
  4818. (setq x (nth (1- col) x))
  4819. (when (string-match
  4820. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  4821. x)
  4822. (setq x (string-to-number x))
  4823. (when (> min x) (setq min x))
  4824. (when (< max x) (setq max x)))))
  4825. (org-table-insert-column)
  4826. (org-table-move-column-right)
  4827. (org-table-store-formulas
  4828. (cons
  4829. (cons
  4830. (number-to-string (1+ col))
  4831. (format "'(%s $%s %s %s %s)"
  4832. "orgtbl-ascii-draw" col min max length))
  4833. (org-table-get-stored-formulas)))
  4834. (org-table-recalculate t)))
  4835. ;; Example of extension: unicode characters
  4836. ;; Here are two examples of different styles.
  4837. ;; Unicode block characters are used to give a smooth effect.
  4838. ;; See http://en.wikipedia.org/wiki/Block_Elements
  4839. ;; Use one of those drawing functions
  4840. ;; - orgtbl-ascii-draw (the default ascii)
  4841. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  4842. ;; - orgtbl-uc-draw-cont (smooth unicode)
  4843. ;; This is best viewed with the "DejaVu Sans Mono" font
  4844. ;; (use M-x set-default-font).
  4845. (defun orgtbl-uc-draw-grid (value min max &optional width)
  4846. "Draw a bar in a table using block unicode characters.
  4847. It is a variant of orgtbl-ascii-draw with Unicode block
  4848. characters, for a smooth display. Bars appear as grids (to the
  4849. extent the font allows)."
  4850. ;; http://en.wikipedia.org/wiki/Block_Elements
  4851. ;; best viewed with the "DejaVu Sans Mono" font.
  4852. (orgtbl-ascii-draw value min max width
  4853. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  4854. (defun orgtbl-uc-draw-cont (value min max &optional width)
  4855. "Draw a bar in a table using block unicode characters.
  4856. It is a variant of orgtbl-ascii-draw with Unicode block
  4857. characters, for a smooth display. Bars are solid (to the extent
  4858. the font allows)."
  4859. (orgtbl-ascii-draw value min max width
  4860. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  4861. (defun org-table-get-remote-range (name-or-id form)
  4862. "Get a field value or a list of values in a range from table at ID.
  4863. NAME-OR-ID may be the name of a table in the current file as set
  4864. by a \"#+NAME:\" directive. The first table following this line
  4865. will then be used. Alternatively, it may be an ID referring to
  4866. any entry, also in a different file. In this case, the first
  4867. table in that entry will be referenced.
  4868. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  4869. \"@I$2..@II$2\". All the references must be absolute, not relative.
  4870. The return value is either a single string for a single field, or a
  4871. list of the fields in the rectangle."
  4872. (save-match-data
  4873. (let ((case-fold-search t) (id-loc nil)
  4874. ;; Protect a bunch of variables from being overwritten
  4875. ;; by the context of the remote table
  4876. org-table-column-names org-table-column-name-regexp
  4877. org-table-local-parameters org-table-named-field-locations
  4878. org-table-current-line-types org-table-current-begin-line
  4879. org-table-current-begin-pos org-table-dlines
  4880. org-table-current-ncol
  4881. org-table-hlines org-table-last-alignment
  4882. org-table-last-column-widths org-table-last-alignment
  4883. org-table-last-column-widths tbeg
  4884. buffer loc)
  4885. (setq form (org-table-convert-refs-to-rc form))
  4886. (save-excursion
  4887. (save-restriction
  4888. (widen)
  4889. (save-excursion
  4890. (goto-char (point-min))
  4891. (if (re-search-forward
  4892. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  4893. (regexp-quote name-or-id) "[ \t]*$")
  4894. nil t)
  4895. (setq buffer (current-buffer) loc (match-beginning 0))
  4896. (setq id-loc (org-id-find name-or-id 'marker))
  4897. (unless (and id-loc (markerp id-loc))
  4898. (user-error "Can't find remote table \"%s\"" name-or-id))
  4899. (setq buffer (marker-buffer id-loc)
  4900. loc (marker-position id-loc))
  4901. (move-marker id-loc nil)))
  4902. (with-current-buffer buffer
  4903. (save-excursion
  4904. (save-restriction
  4905. (widen)
  4906. (goto-char loc)
  4907. (forward-char 1)
  4908. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  4909. (not (match-beginning 1)))
  4910. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  4911. (setq tbeg (point-at-bol))
  4912. (org-table-get-specials)
  4913. (setq form (org-table-formula-substitute-names
  4914. (org-table-formula-handle-first/last-rc form)))
  4915. (if (and (string-match org-table-range-regexp form)
  4916. (> (length (match-string 0 form)) 1))
  4917. (save-match-data
  4918. (org-table-get-range (match-string 0 form) tbeg 1))
  4919. form)))))))))
  4920. (defun org-table-remote-reference-indirection (form)
  4921. "Return formula with table remote references substituted by indirection.
  4922. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  4923. This indirection works only with the format @ROW$COLUMN. The
  4924. format \"B3\" is not supported because it can not be
  4925. distinguished from a plain table name or ID."
  4926. (let ((start 0))
  4927. (while (string-match (concat
  4928. ;; Same as in `org-table-eval-formula'.
  4929. "\\<remote([ \t]*\\("
  4930. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  4931. "[@$][^ \t,]+"
  4932. ;; Same as in `org-table-eval-formula'.
  4933. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")
  4934. form
  4935. start)
  4936. ;; The position of the character as far as possible to the right
  4937. ;; that will not be replaced and particularly not be shifted by
  4938. ;; `replace-match'.
  4939. (setq start (match-beginning 1))
  4940. ;; Substitute the remote reference with the value found in the
  4941. ;; field.
  4942. (setq form
  4943. (replace-match
  4944. (save-match-data
  4945. (org-table-get-range (org-table-formula-handle-first/last-rc
  4946. (match-string 1 form))))
  4947. t t form 1))))
  4948. form)
  4949. (defmacro org-define-lookup-function (mode)
  4950. (let ((mode-str (symbol-name mode))
  4951. (first-p (equal mode 'first))
  4952. (all-p (equal mode 'all)))
  4953. (let ((plural-str (if all-p "s" "")))
  4954. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  4955. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  4956. If R-LIST is nil, return matching element%s of S-LIST.
  4957. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  4958. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  4959. This function is generated by a call to the macro `org-define-lookup-function'."
  4960. mode-str plural-str plural-str plural-str)
  4961. (let ,(let ((lvars '((p (or predicate 'equal))
  4962. (sl s-list)
  4963. (rl (or r-list s-list))
  4964. (ret nil))))
  4965. (if first-p (add-to-list 'lvars '(match-p nil)))
  4966. lvars)
  4967. (while ,(if first-p '(and (not match-p) sl) 'sl)
  4968. (progn
  4969. (if (funcall p val (car sl))
  4970. (progn
  4971. ,(if first-p '(setq match-p t))
  4972. (let ((rval (car rl)))
  4973. (setq ret ,(if all-p '(append ret (list rval)) 'rval)))))
  4974. (setq sl (cdr sl) rl (cdr rl))))
  4975. ret)))))
  4976. (org-define-lookup-function first)
  4977. (org-define-lookup-function last)
  4978. (org-define-lookup-function all)
  4979. (provide 'org-table)
  4980. ;; Local variables:
  4981. ;; generated-autoload-file: "org-loaddefs.el"
  4982. ;; End:
  4983. ;;; org-table.el ends here