org-table.el 205 KB

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