org-table.el 205 KB

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