org-table.el 205 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441
  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" (org-table-current-dline)
  2035. (org-table-current-column)))
  2036. (scol (if named
  2037. (if (and name (not (string-match "^LR[0-9]+$" name)))
  2038. name
  2039. ref)
  2040. (int-to-string (org-table-current-column))))
  2041. (name (or name ref))
  2042. (org-table-may-need-update nil)
  2043. (stored (cdr (assoc scol stored-list)))
  2044. (eq (cond
  2045. ((and stored equation (string-match "^ *=? *$" equation))
  2046. stored)
  2047. ((stringp equation)
  2048. equation)
  2049. (t (org-table-formula-from-user
  2050. (read-string
  2051. (org-table-formula-to-user
  2052. (format "%s formula %s%s="
  2053. (if named "Field" "Column")
  2054. (if (member (string-to-char scol) '(?$ ?@)) "" "$")
  2055. scol))
  2056. (if stored (org-table-formula-to-user stored) "")
  2057. 'org-table-formula-history
  2058. )))))
  2059. mustsave)
  2060. (when (not (string-match "\\S-" eq))
  2061. ;; remove formula
  2062. (setq stored-list (delq (assoc scol stored-list) stored-list))
  2063. (org-table-store-formulas stored-list)
  2064. (user-error "Formula removed"))
  2065. (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
  2066. (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
  2067. (if (and name (not named))
  2068. ;; We set the column equation, delete the named one.
  2069. (setq stored-list (delq (assoc name stored-list) stored-list)
  2070. mustsave t))
  2071. (if stored
  2072. (setcdr (assoc scol stored-list) eq)
  2073. (setq stored-list (cons (cons scol eq) stored-list)))
  2074. (if (or mustsave (not (equal stored eq)))
  2075. (org-table-store-formulas stored-list))
  2076. eq))
  2077. (defun org-table-store-formulas (alist)
  2078. "Store the list of formulas below the current table."
  2079. (setq alist (sort alist 'org-table-formula-less-p))
  2080. (let ((case-fold-search t))
  2081. (save-excursion
  2082. (goto-char (org-table-end))
  2083. (if (looking-at "\\([ \t]*\n\\)*[ \t]*\\(#\\+tblfm:\\)\\(.*\n?\\)")
  2084. (progn
  2085. ;; don't overwrite TBLFM, we might use text properties to store stuff
  2086. (goto-char (match-beginning 3))
  2087. (delete-region (match-beginning 3) (match-end 0)))
  2088. (org-indent-line)
  2089. (insert (or (match-string 2) "#+TBLFM:")))
  2090. (insert " "
  2091. (mapconcat (lambda (x)
  2092. (concat
  2093. (if (equal (string-to-char (car x)) ?@) "" "$")
  2094. (car x) "=" (cdr x)))
  2095. alist "::")
  2096. "\n"))))
  2097. (defsubst org-table-formula-make-cmp-string (a)
  2098. (when (string-match "\\`$[<>]" a)
  2099. (let ((arrow (string-to-char (substring a 1))))
  2100. ;; Fake a high number to make sure this is sorted at the end.
  2101. (setq a (org-table-formula-handle-first/last-rc a))
  2102. (setq a (format "$%d" (+ 10000
  2103. (if (= arrow ?<) -1000 0)
  2104. (string-to-number (substring a 1)))))))
  2105. (when (string-match
  2106. "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?"
  2107. a)
  2108. (concat
  2109. (if (match-end 2)
  2110. (format "@%05d" (string-to-number (match-string 2 a))) "")
  2111. (if (match-end 4)
  2112. (format "$%05d" (string-to-number (match-string 4 a))) "")
  2113. (if (match-end 5)
  2114. (concat "@@" (match-string 5 a))))))
  2115. (defun org-table-formula-less-p (a b)
  2116. "Compare two formulas for sorting."
  2117. (let ((as (org-table-formula-make-cmp-string (car a)))
  2118. (bs (org-table-formula-make-cmp-string (car b))))
  2119. (and as bs (string< as bs))))
  2120. ;;;###autoload
  2121. (defun org-table-get-stored-formulas (&optional noerror)
  2122. "Return an alist with the stored formulas directly after current table."
  2123. (save-excursion
  2124. (goto-char (org-table-end))
  2125. (let ((case-fold-search t))
  2126. (when (looking-at "\\([ \t]*\n\\)*[ \t]*#\\+TBLFM: *\\(.*\\)")
  2127. (let ((strings (org-split-string (org-match-string-no-properties 2)
  2128. " *:: *"))
  2129. eq-alist seen)
  2130. (dolist (string strings (nreverse eq-alist))
  2131. (when (string-match "\\`\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\
  2132. \\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*[^ \t]\\)" string)
  2133. (let* ((lhs (match-string 1 string))
  2134. (rhs (match-string 3 string)))
  2135. (push (cons lhs rhs) eq-alist)
  2136. (cond
  2137. ((not (member lhs seen)) (push lhs seen))
  2138. (noerror
  2139. (message
  2140. "Double definition `%s=' in TBLFM line, please fix by hand"
  2141. lhs)
  2142. (ding)
  2143. (sit-for 2))
  2144. (t
  2145. (user-error
  2146. "Double definition `%s=' in TBLFM line, please fix by hand"
  2147. lhs)))))))))))
  2148. (defun org-table-fix-formulas (key replace &optional limit delta remove)
  2149. "Modify the equations after the table structure has been edited.
  2150. KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
  2151. For all numbers larger than LIMIT, shift them by DELTA."
  2152. (save-excursion
  2153. (goto-char (org-table-end))
  2154. (while (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:"))
  2155. (let ((msg "The formulas in #+TBLFM have been updated")
  2156. (re (concat key "\\([0-9]+\\)"))
  2157. (re2
  2158. (when remove
  2159. (if (or (equal key "$") (equal key "$LR"))
  2160. (format "\\(@[0-9]+\\)?%s%d=.*?\\(::\\|$\\)"
  2161. (regexp-quote key) remove)
  2162. (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
  2163. s n a)
  2164. (when remove
  2165. (while (re-search-forward re2 (point-at-eol) t)
  2166. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2167. (if (equal (char-before (match-beginning 0)) ?.)
  2168. (user-error
  2169. "Change makes TBLFM term %s invalid, use undo to recover"
  2170. (match-string 0))
  2171. (replace-match "")))))
  2172. (while (re-search-forward re (point-at-eol) t)
  2173. (unless (save-match-data (org-in-regexp "remote([^)]+?)"))
  2174. (setq s (match-string 1) n (string-to-number s))
  2175. (cond
  2176. ((setq a (assoc s replace))
  2177. (replace-match (concat key (cdr a)) t t)
  2178. (message msg))
  2179. ((and limit (> n limit))
  2180. (replace-match (concat key (int-to-string (+ n delta))) t t)
  2181. (message msg))))))
  2182. (forward-line))))
  2183. ;;;###autoload
  2184. (defun org-table-maybe-eval-formula ()
  2185. "Check if the current field starts with \"=\" or \":=\".
  2186. If yes, store the formula and apply it."
  2187. ;; We already know we are in a table. Get field will only return a formula
  2188. ;; when appropriate. It might return a separator line, but no problem.
  2189. (when org-table-formula-evaluate-inline
  2190. (let* ((field (org-trim (or (org-table-get-field) "")))
  2191. named eq)
  2192. (when (string-match "^:?=\\(.*[^=]\\)$" field)
  2193. (setq named (equal (string-to-char field) ?:)
  2194. eq (match-string 1 field))
  2195. (if (or (fboundp 'calc-eval)
  2196. (equal (substring eq 0 (min 2 (length eq))) "'("))
  2197. (org-table-eval-formula (if named '(4) nil)
  2198. (org-table-formula-from-user eq))
  2199. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
  2200. (defvar org-recalc-commands nil
  2201. "List of commands triggering the recalculation of a line.
  2202. Will be filled automatically during use.")
  2203. (defvar org-recalc-marks
  2204. '((" " . "Unmarked: no special line, no automatic recalculation")
  2205. ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
  2206. ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
  2207. ("!" . "Column name definition line. Reference in formula as $name.")
  2208. ("$" . "Parameter definition line name=value. Reference in formula as $name.")
  2209. ("_" . "Names for values in row below this one.")
  2210. ("^" . "Names for values in row above this one.")))
  2211. ;;;###autoload
  2212. (defun org-table-rotate-recalc-marks (&optional newchar)
  2213. "Rotate the recalculation mark in the first column.
  2214. If in any row, the first field is not consistent with a mark,
  2215. insert a new column for the markers.
  2216. When there is an active region, change all the lines in the region,
  2217. after prompting for the marking character.
  2218. After each change, a message will be displayed indicating the meaning
  2219. of the new mark."
  2220. (interactive)
  2221. (unless (org-at-table-p) (user-error "Not at a table"))
  2222. (let* ((region (org-region-active-p))
  2223. (l1 (and region
  2224. (save-excursion (goto-char (region-beginning))
  2225. (copy-marker (line-beginning-position)))))
  2226. (l2 (and region
  2227. (save-excursion (goto-char (region-end))
  2228. (copy-marker (line-beginning-position)))))
  2229. (l (copy-marker (line-beginning-position)))
  2230. (col (org-table-current-column))
  2231. (newchar (if region
  2232. (char-to-string
  2233. (read-char-exclusive
  2234. "Change region to what mark? Type # * ! $ or SPC: "))
  2235. newchar))
  2236. (no-special-column
  2237. (save-excursion
  2238. (goto-char (org-table-begin))
  2239. (re-search-forward
  2240. "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" (org-table-end) t))))
  2241. (when (and newchar (not (assoc newchar org-recalc-marks)))
  2242. (user-error "Invalid character `%s' in `org-table-rotate-recalc-marks'"
  2243. newchar))
  2244. (when l1 (goto-char l1))
  2245. (save-excursion
  2246. (beginning-of-line)
  2247. (unless (looking-at org-table-dataline-regexp)
  2248. (user-error "Not at a table data line")))
  2249. (when no-special-column
  2250. (org-table-goto-column 1)
  2251. (org-table-insert-column))
  2252. (let ((previous-line-end (line-end-position))
  2253. (newchar
  2254. (save-excursion
  2255. (beginning-of-line)
  2256. (cond ((not (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")) "#")
  2257. (newchar)
  2258. (t (cadr (member (match-string 1)
  2259. (append (mapcar #'car org-recalc-marks)
  2260. '(" ")))))))))
  2261. ;; Rotate mark in first row.
  2262. (org-table-get-field 1 (format " %s " newchar))
  2263. ;; Rotate marks in additional rows if a region is active.
  2264. (when region
  2265. (save-excursion
  2266. (forward-line)
  2267. (while (<= (point) l2)
  2268. (when (looking-at org-table-dataline-regexp)
  2269. (org-table-get-field 1 (format " %s " newchar)))
  2270. (forward-line))))
  2271. ;; Only align if rotation actually changed lines' length.
  2272. (when (/= previous-line-end (line-end-position)) (org-table-align)))
  2273. (goto-char l)
  2274. (org-table-goto-column (if no-special-column (1+ col) col))
  2275. (when l1 (set-marker l1 nil))
  2276. (when l2 (set-marker l2 nil))
  2277. (set-marker l nil)
  2278. (when (org-called-interactively-p 'interactive)
  2279. (message "%s" (cdr (assoc newchar org-recalc-marks))))))
  2280. ;;;###autoload
  2281. (defun org-table-analyze ()
  2282. "Analyze table at point and store results.
  2283. This function sets up the following dynamically scoped variables:
  2284. `org-table-column-name-regexp',
  2285. `org-table-column-names',
  2286. `org-table-current-begin-pos',
  2287. `org-table-current-line-types',
  2288. `org-table-current-ncol',
  2289. `org-table-dlines',
  2290. `org-table-hlines',
  2291. `org-table-local-parameters',
  2292. `org-table-named-field-locations'."
  2293. (let ((beg (org-table-begin))
  2294. (end (org-table-end)))
  2295. (save-excursion
  2296. (goto-char beg)
  2297. ;; Extract column names.
  2298. (setq org-table-column-names nil)
  2299. (when (save-excursion
  2300. (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t))
  2301. (let ((c 1))
  2302. (dolist (name (org-split-string (match-string 1) " *| *"))
  2303. (incf c)
  2304. (when (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" name)
  2305. (push (cons name (int-to-string c)) org-table-column-names)))))
  2306. (setq org-table-column-names (nreverse org-table-column-names))
  2307. (setq org-table-column-name-regexp
  2308. (format "\\$\\(%s\\)\\>"
  2309. (regexp-opt (mapcar #'car org-table-column-names) t)))
  2310. ;; Extract local parameters.
  2311. (setq org-table-local-parameters nil)
  2312. (save-excursion
  2313. (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
  2314. (dolist (field (org-split-string (match-string 1) " *| *"))
  2315. (when (string-match
  2316. "\\`\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
  2317. (push (cons (match-string 1 field) (match-string 2 field))
  2318. org-table-local-parameters)))))
  2319. ;; Update named fields locations. We minimize `count-lines'
  2320. ;; processing by storing last known number of lines in LAST.
  2321. (setq org-table-named-field-locations nil)
  2322. (save-excursion
  2323. (let ((last (cons (point) 0)))
  2324. (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
  2325. (let ((c (match-string 1))
  2326. (fields (org-split-string (match-string 2) " *| *")))
  2327. (save-excursion
  2328. (forward-line (if (equal c "_") 1 -1))
  2329. (let ((fields1
  2330. (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
  2331. (org-split-string (match-string 1) " *| *")))
  2332. (line (incf (cdr last) (count-lines (car last) (point))))
  2333. (col 1))
  2334. (setcar last (point)) ; Update last known position.
  2335. (while (and fields fields1)
  2336. (let ((field (pop fields))
  2337. (v (pop fields1)))
  2338. (incf col)
  2339. (when (and (stringp field)
  2340. (stringp v)
  2341. (string-match "\\`[a-zA-Z][_a-zA-Z0-9]*\\'"
  2342. field))
  2343. (push (cons field v) org-table-local-parameters)
  2344. (push (list field line col)
  2345. org-table-named-field-locations))))))))))
  2346. ;; Re-use existing markers when possible.
  2347. (if (markerp org-table-current-begin-pos)
  2348. (move-marker org-table-current-begin-pos (point))
  2349. (setq org-table-current-begin-pos (point-marker)))
  2350. ;; Analyze the line types.
  2351. (let ((l 0) hlines dlines types)
  2352. (while (looking-at "[ \t]*|\\(-\\)?")
  2353. (push (if (match-end 1) 'hline 'dline) types)
  2354. (if (match-end 1) (push l hlines) (push l dlines))
  2355. (forward-line)
  2356. (incf l))
  2357. (push 'hline types) ; Add an imaginary extra hline to the end.
  2358. (setq org-table-current-line-types (apply #'vector (nreverse types)))
  2359. (setq org-table-dlines (apply #'vector (cons nil (nreverse dlines))))
  2360. (setq org-table-hlines (apply #'vector (cons nil (nreverse hlines)))))
  2361. ;; Get the number of columns from the first data line in table.
  2362. (goto-char beg)
  2363. (forward-line (aref org-table-dlines 1))
  2364. (let* ((fields
  2365. (org-split-string
  2366. (buffer-substring (line-beginning-position) (line-end-position))
  2367. "[ \t]*|[ \t]*"))
  2368. (nfields (length fields))
  2369. al al2)
  2370. (setq org-table-current-ncol nfields)
  2371. (let ((last-dline
  2372. (aref org-table-dlines (1- (length org-table-dlines)))))
  2373. (dotimes (i nfields)
  2374. (let ((column (1+ i)))
  2375. (push (list (format "LR%d" column) last-dline column) al)
  2376. (push (cons (format "LR%d" column) (nth i fields)) al2))))
  2377. (setq org-table-named-field-locations
  2378. (append org-table-named-field-locations al))
  2379. (setq org-table-local-parameters
  2380. (append org-table-local-parameters al2))))))
  2381. (defun org-table-goto-field (ref &optional create-column-p)
  2382. "Move point to a specific field in the current table.
  2383. REF is either the name of a field its absolute reference, as
  2384. a string. No column is created unless CREATE-COLUMN-P is
  2385. non-nil. If it is a function, it is called with the column
  2386. number as its argument as is used as a predicate to know if the
  2387. column can be created.
  2388. This function assumes the table is already analyzed (i.e., using
  2389. `org-table-analyze')."
  2390. (let* ((coordinates
  2391. (cond
  2392. ((cdr (assoc ref org-table-named-field-locations)))
  2393. ((string-match "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'" ref)
  2394. (list (condition-case nil
  2395. (aref org-table-dlines
  2396. (string-to-number (match-string 1 ref)))
  2397. (error (user-error "Invalid row number in %s" ref)))
  2398. (string-to-number (match-string 2 ref))))
  2399. (t (user-error "Unknown field: %s" ref))))
  2400. (line (car coordinates))
  2401. (column (nth 1 coordinates))
  2402. (create-new-column (if (functionp create-column-p)
  2403. (funcall create-column-p column)
  2404. create-column-p)))
  2405. (when coordinates
  2406. (goto-char org-table-current-begin-pos)
  2407. (forward-line line)
  2408. (org-table-goto-column column nil create-new-column))))
  2409. ;;;###autoload
  2410. (defun org-table-maybe-recalculate-line ()
  2411. "Recompute the current line if marked for it, and if we haven't just done it."
  2412. (interactive)
  2413. (and org-table-allow-automatic-line-recalculation
  2414. (not (and (memq last-command org-recalc-commands)
  2415. (eq org-last-recalc-line (line-beginning-position))))
  2416. (save-excursion (beginning-of-line 1)
  2417. (looking-at org-table-auto-recalculate-regexp))
  2418. (org-table-recalculate) t))
  2419. (defvar org-tbl-calc-modes) ;; Dynamically bound in `org-table-eval-formula'
  2420. (defsubst org-set-calc-mode (var &optional value)
  2421. (if (stringp var)
  2422. (setq var (assoc var '(("D" calc-angle-mode deg)
  2423. ("R" calc-angle-mode rad)
  2424. ("F" calc-prefer-frac t)
  2425. ("S" calc-symbolic-mode t)))
  2426. value (nth 2 var) var (nth 1 var)))
  2427. (if (memq var org-tbl-calc-modes)
  2428. (setcar (cdr (memq var org-tbl-calc-modes)) value)
  2429. (cons var (cons value org-tbl-calc-modes)))
  2430. org-tbl-calc-modes)
  2431. ;;;###autoload
  2432. (defun org-table-eval-formula (&optional arg equation
  2433. suppress-align suppress-const
  2434. suppress-store suppress-analysis)
  2435. "Replace the table field value at the cursor by the result of a calculation.
  2436. This function makes use of Dave Gillespie's Calc package, in my view the
  2437. most exciting program ever written for GNU Emacs. So you need to have Calc
  2438. installed in order to use this function.
  2439. In a table, this command replaces the value in the current field with the
  2440. result of a formula. It also installs the formula as the \"current\" column
  2441. formula, by storing it in a special line below the table. When called
  2442. with a `C-u' prefix, the current field must be a named field, and the
  2443. formula is installed as valid in only this specific field.
  2444. When called with two `C-u' prefixes, insert the active equation
  2445. for the field back into the current field, so that it can be
  2446. edited there. This is useful in order to use \\[org-table-show-reference]
  2447. to check the referenced fields.
  2448. When called, the command first prompts for a formula, which is read in
  2449. the minibuffer. Previously entered formulas are available through the
  2450. history list, and the last used formula is offered as a default.
  2451. These stored formulas are adapted correctly when moving, inserting, or
  2452. deleting columns with the corresponding commands.
  2453. The formula can be any algebraic expression understood by the Calc package.
  2454. For details, see the Org-mode manual.
  2455. This function can also be called from Lisp programs and offers
  2456. additional arguments: EQUATION can be the formula to apply. If this
  2457. argument is given, the user will not be prompted. SUPPRESS-ALIGN is
  2458. used to speed-up recursive calls by by-passing unnecessary aligns.
  2459. SUPPRESS-CONST suppresses the interpretation of constants in the
  2460. formula, assuming that this has been done already outside the function.
  2461. SUPPRESS-STORE means the formula should not be stored, either because
  2462. it is already stored, or because it is a modified equation that should
  2463. not overwrite the stored one."
  2464. (interactive "P")
  2465. (org-table-check-inside-data-field)
  2466. (or suppress-analysis (org-table-analyze))
  2467. (if (equal arg '(16))
  2468. (let ((eq (org-table-current-field-formula)))
  2469. (or eq (user-error "No equation active for current field"))
  2470. (org-table-get-field nil eq)
  2471. (org-table-align)
  2472. (setq org-table-may-need-update t))
  2473. (let* (fields
  2474. (ndown (if (integerp arg) arg 1))
  2475. (org-table-automatic-realign nil)
  2476. (case-fold-search nil)
  2477. (down (> ndown 1))
  2478. (formula (if (and equation suppress-store)
  2479. equation
  2480. (org-table-get-formula equation (equal arg '(4)))))
  2481. (n0 (org-table-current-column))
  2482. (org-tbl-calc-modes (copy-sequence org-calc-default-modes))
  2483. (numbers nil) ; was a variable, now fixed default
  2484. (keep-empty nil)
  2485. n form form0 formrpl formrg bw fmt x ev orig c lispp literal
  2486. duration duration-output-format)
  2487. ;; Parse the format string. Since we have a lot of modes, this is
  2488. ;; a lot of work. However, I think calc still uses most of the time.
  2489. (if (string-match ";" formula)
  2490. (let ((tmp (org-split-string formula ";")))
  2491. (setq formula (car tmp)
  2492. fmt (concat (cdr (assoc "%" org-table-local-parameters))
  2493. (nth 1 tmp)))
  2494. (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
  2495. (setq c (string-to-char (match-string 1 fmt))
  2496. n (string-to-number (match-string 2 fmt)))
  2497. (if (= c ?p)
  2498. (setq org-tbl-calc-modes (org-set-calc-mode 'calc-internal-prec n))
  2499. (setq org-tbl-calc-modes
  2500. (org-set-calc-mode
  2501. 'calc-float-format
  2502. (list (cdr (assoc c '((?n . float) (?f . fix)
  2503. (?s . sci) (?e . eng))))
  2504. n))))
  2505. (setq fmt (replace-match "" t t fmt)))
  2506. (if (string-match "T" fmt)
  2507. (setq duration t numbers t
  2508. duration-output-format nil
  2509. fmt (replace-match "" t t fmt)))
  2510. (if (string-match "t" fmt)
  2511. (setq duration t
  2512. duration-output-format org-table-duration-custom-format
  2513. numbers t
  2514. fmt (replace-match "" t t fmt)))
  2515. (if (string-match "N" fmt)
  2516. (setq numbers t
  2517. fmt (replace-match "" t t fmt)))
  2518. (if (string-match "L" fmt)
  2519. (setq literal t
  2520. fmt (replace-match "" t t fmt)))
  2521. (if (string-match "E" fmt)
  2522. (setq keep-empty t
  2523. fmt (replace-match "" t t fmt)))
  2524. (while (string-match "[DRFS]" fmt)
  2525. (setq org-tbl-calc-modes (org-set-calc-mode (match-string 0 fmt)))
  2526. (setq fmt (replace-match "" t t fmt)))
  2527. (unless (string-match "\\S-" fmt)
  2528. (setq fmt nil))))
  2529. (if (and (not suppress-const) org-table-formula-use-constants)
  2530. (setq formula (org-table-formula-substitute-names formula)))
  2531. (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
  2532. (while (> ndown 0)
  2533. (setq fields (org-split-string
  2534. (buffer-substring-no-properties (point-at-bol) (point-at-eol))
  2535. " *| *"))
  2536. ;; replace fields with duration values if relevant
  2537. (if duration
  2538. (setq fields
  2539. (mapcar (lambda (x) (org-table-time-string-to-seconds x))
  2540. fields)))
  2541. (if (eq numbers t)
  2542. (setq fields (mapcar
  2543. (lambda (x)
  2544. (if (string-match "\\S-" x)
  2545. (number-to-string (string-to-number x))
  2546. x))
  2547. fields)))
  2548. (setq ndown (1- ndown))
  2549. (setq form (copy-sequence formula)
  2550. lispp (and (> (length form) 2) (equal (substring form 0 2) "'(")))
  2551. (if (and lispp literal) (setq lispp 'literal))
  2552. ;; Insert row and column number of formula result field
  2553. (while (string-match "[@$]#" form)
  2554. (setq form
  2555. (replace-match
  2556. (format "%d"
  2557. (save-match-data
  2558. (if (equal (substring form (match-beginning 0)
  2559. (1+ (match-beginning 0)))
  2560. "@")
  2561. (org-table-current-dline)
  2562. (org-table-current-column))))
  2563. t t form)))
  2564. ;; Check for old vertical references
  2565. (org-table--error-on-old-row-references form)
  2566. ;; Insert remote references
  2567. (setq form (org-table-remote-reference-indirection form))
  2568. (while (string-match "\\<remote([ \t]*\\([^,)]+\\)[ \t]*,[ \t]*\\([^\n)]+\\))" form)
  2569. (setq form
  2570. (replace-match
  2571. (save-match-data
  2572. (org-table-make-reference
  2573. (let ((rmtrng (org-table-get-remote-range
  2574. (match-string 1 form) (match-string 2 form))))
  2575. (if duration
  2576. (if (listp rmtrng)
  2577. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) rmtrng)
  2578. (org-table-time-string-to-seconds rmtrng))
  2579. rmtrng))
  2580. keep-empty numbers lispp))
  2581. t t form)))
  2582. ;; Insert complex ranges
  2583. (while (and (string-match org-table-range-regexp form)
  2584. (> (length (match-string 0 form)) 1))
  2585. (setq formrg
  2586. (save-match-data
  2587. (org-table-get-range
  2588. (match-string 0 form) org-table-current-begin-pos n0)))
  2589. (setq formrpl
  2590. (save-match-data
  2591. (org-table-make-reference
  2592. ;; possibly handle durations
  2593. (if duration
  2594. (if (listp formrg)
  2595. (mapcar (lambda(x) (org-table-time-string-to-seconds x)) formrg)
  2596. (org-table-time-string-to-seconds formrg))
  2597. formrg)
  2598. keep-empty numbers lispp)))
  2599. (if (not (save-match-data
  2600. (string-match (regexp-quote form) formrpl)))
  2601. (setq form (replace-match formrpl t t form))
  2602. (user-error "Spreadsheet error: invalid reference \"%s\"" form)))
  2603. ;; Insert simple ranges, i.e. included in the current row.
  2604. (while (string-match
  2605. "\\$\\(\\([-+]\\)?[0-9]+\\)\\.\\.\\$\\(\\([-+]\\)?[0-9]+\\)"
  2606. form)
  2607. (setq form
  2608. (replace-match
  2609. (save-match-data
  2610. (org-table-make-reference
  2611. (cl-subseq fields
  2612. (+ (if (match-end 2) n0 0)
  2613. (string-to-number (match-string 1 form))
  2614. -1)
  2615. (+ (if (match-end 4) n0 0)
  2616. (string-to-number (match-string 3 form))))
  2617. keep-empty numbers lispp))
  2618. t t form)))
  2619. (setq form0 form)
  2620. ;; Insert the references to fields in same row
  2621. (while (string-match "\\$\\(\\([-+]\\)?[0-9]+\\)" form)
  2622. (setq n (+ (string-to-number (match-string 1 form))
  2623. (if (match-end 2) n0 0))
  2624. x (nth (1- (if (= n 0) n0 (max n 1))) fields)
  2625. formrpl (save-match-data
  2626. (org-table-make-reference
  2627. x keep-empty numbers lispp)))
  2628. (when (or (not x)
  2629. (save-match-data
  2630. (string-match (regexp-quote formula) formrpl)))
  2631. (user-error "Invalid field specifier \"%s\""
  2632. (match-string 0 form)))
  2633. (setq form (replace-match formrpl t t form)))
  2634. (if lispp
  2635. (setq ev (condition-case nil
  2636. (eval (eval (read form)))
  2637. (error "#ERROR"))
  2638. ev (if (numberp ev) (number-to-string ev) ev)
  2639. ev (if duration (org-table-time-seconds-to-string
  2640. (string-to-number ev)
  2641. duration-output-format) ev))
  2642. (or (fboundp 'calc-eval)
  2643. (user-error "Calc does not seem to be installed, and is needed to evaluate the formula"))
  2644. ;; Use <...> time-stamps so that Calc can handle them
  2645. (while (string-match (concat "\\[" org-ts-regexp1 "\\]") form)
  2646. (setq form (replace-match "<\\1>" nil nil form)))
  2647. ;; I18n-ize local time-stamps by setting (system-time-locale "C")
  2648. (when (string-match org-ts-regexp2 form)
  2649. (let* ((ts (match-string 0 form))
  2650. (tsp (apply 'encode-time (save-match-data (org-parse-time-string ts))))
  2651. (system-time-locale "C")
  2652. (tf (or (and (save-match-data (string-match "[0-9]\\{1,2\\}:[0-9]\\{2\\}" ts))
  2653. (cdr org-time-stamp-formats))
  2654. (car org-time-stamp-formats))))
  2655. (setq form (replace-match (format-time-string tf tsp) t t form))))
  2656. (setq ev (if (and duration (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" form))
  2657. form
  2658. (calc-eval (cons form org-tbl-calc-modes)
  2659. (when (and (not keep-empty) numbers) 'num)))
  2660. ev (if duration (org-table-time-seconds-to-string
  2661. (if (string-match "^[0-9]+:[0-9]+\\(?::[0-9]+\\)?$" ev)
  2662. (string-to-number (org-table-time-string-to-seconds ev))
  2663. (string-to-number ev))
  2664. duration-output-format)
  2665. ev)))
  2666. (when org-table-formula-debug
  2667. (with-output-to-temp-buffer "*Substitution History*"
  2668. (princ (format "Substitution history of formula
  2669. Orig: %s
  2670. $xyz-> %s
  2671. @r$c-> %s
  2672. $1-> %s\n" orig formula form0 form))
  2673. (if (consp ev)
  2674. (princ (format " %s^\nError: %s"
  2675. (make-string (car ev) ?\-) (nth 1 ev)))
  2676. (princ (format "Result: %s\nFormat: %s\nFinal: %s"
  2677. ev (or fmt "NONE")
  2678. (if fmt (format fmt (string-to-number ev)) ev)))))
  2679. (setq bw (get-buffer-window "*Substitution History*"))
  2680. (org-fit-window-to-buffer bw)
  2681. (unless (and (org-called-interactively-p 'any) (not ndown))
  2682. (unless (let (inhibit-redisplay)
  2683. (y-or-n-p "Debugging Formula. Continue to next? "))
  2684. (org-table-align)
  2685. (user-error "Abort"))
  2686. (delete-window bw)
  2687. (message "")))
  2688. (when (consp ev) (setq fmt nil ev "#ERROR"))
  2689. (org-table-justify-field-maybe
  2690. (format org-table-formula-field-format
  2691. (if fmt (format fmt (string-to-number ev)) ev)))
  2692. (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
  2693. (call-interactively 'org-return)
  2694. (setq ndown 0)))
  2695. (and down (org-table-maybe-recalculate-line))
  2696. (or suppress-align (and org-table-may-need-update
  2697. (org-table-align))))))
  2698. (defun org-table-put-field-property (prop value)
  2699. (save-excursion
  2700. (put-text-property (progn (skip-chars-backward "^|") (point))
  2701. (progn (skip-chars-forward "^|") (point))
  2702. prop value)))
  2703. (defun org-table-get-range (desc &optional tbeg col highlight corners-only)
  2704. "Get a calc vector from a column, according to descriptor DESC.
  2705. Optional arguments TBEG and COL can give the beginning of the table and
  2706. the current column, to avoid unnecessary parsing.
  2707. HIGHLIGHT means just highlight the range.
  2708. When CORNERS-ONLY is set, only return the corners of the range as
  2709. a list (line1 column1 line2 column2) where line1 and line2 are
  2710. line numbers relative to beginning of table, or TBEG, and column1
  2711. and column2 are table column numbers."
  2712. (let* ((desc (if (org-string-match-p "\\`\\$[0-9]+\\.\\.\\$[0-9]+\\'" desc)
  2713. (replace-regexp-in-string "\\$" "@0$" desc)
  2714. desc))
  2715. (col (or col (org-table-current-column)))
  2716. (tbeg (or tbeg (org-table-begin)))
  2717. (thisline (count-lines tbeg (line-beginning-position))))
  2718. (unless (string-match org-table-range-regexp desc)
  2719. (user-error "Invalid table range specifier `%s'" desc))
  2720. (let ((rangep (match-end 3))
  2721. (r1 (let ((r (and (match-end 1) (match-string 1 desc))))
  2722. (or (save-match-data
  2723. (and (org-string-nw-p r)
  2724. (org-table--descriptor-line r thisline)))
  2725. thisline)))
  2726. (r2 (let ((r (and (match-end 4) (match-string 4 desc))))
  2727. (or (save-match-data
  2728. (and (org-string-nw-p r)
  2729. (org-table--descriptor-line r thisline)))
  2730. thisline)))
  2731. (c1 (let ((c (and (match-end 2) (substring (match-string 2 desc) 1))))
  2732. (if (or (not c) (= (string-to-number c) 0)) col
  2733. (+ (string-to-number c)
  2734. (if (memq (string-to-char c) '(?- ?+)) col 0)))))
  2735. (c2 (let ((c (and (match-end 5) (substring (match-string 5 desc) 1))))
  2736. (if (or (not c) (= (string-to-number c) 0)) col
  2737. (+ (string-to-number c)
  2738. (if (memq (string-to-char c) '(?- ?+)) col 0))))))
  2739. (save-excursion
  2740. (if (and (not corners-only)
  2741. (or (not rangep) (and (= r1 r2) (= c1 c2))))
  2742. ;; Just one field.
  2743. (progn
  2744. (forward-line (- r1 thisline))
  2745. (while (not (looking-at org-table-dataline-regexp))
  2746. (forward-line))
  2747. (prog1 (org-trim (org-table-get-field c1))
  2748. (when highlight (org-table-highlight-rectangle))))
  2749. ;; A range, return a vector. First sort the numbers to get
  2750. ;; a regular rectangle.
  2751. (let ((first-row (min r1 r2))
  2752. (last-row (max r1 r2))
  2753. (first-column (min c1 c2))
  2754. (last-column (max c1 c2)))
  2755. (if corners-only (list first-row first-column last-row last-column)
  2756. ;; Copy the range values into a list.
  2757. (forward-line (- first-row thisline))
  2758. (while (not (looking-at org-table-dataline-regexp))
  2759. (forward-line)
  2760. (incf first-row))
  2761. (org-table-goto-column first-column)
  2762. (let ((beg (point)))
  2763. (forward-line (- last-row first-row))
  2764. (while (not (looking-at org-table-dataline-regexp))
  2765. (forward-line -1))
  2766. (org-table-goto-column last-column)
  2767. (let ((end (point)))
  2768. (when highlight
  2769. (org-table-highlight-rectangle
  2770. beg (progn (skip-chars-forward "^|\n") (point))))
  2771. ;; Return string representation of calc vector.
  2772. (mapcar #'org-trim
  2773. (apply #'append
  2774. (org-table-copy-region beg end))))))))))))
  2775. (defun org-table--descriptor-line (desc cline)
  2776. "Return relative line number corresponding to descriptor DESC.
  2777. The cursor is currently in relative line number CLINE."
  2778. (if (string-match "\\`[0-9]+\\'" desc)
  2779. (aref org-table-dlines (string-to-number desc))
  2780. (when (or (not (string-match
  2781. "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?"
  2782. ;; 1 2 3 4 5 6
  2783. desc))
  2784. (and (not (match-end 3)) (not (match-end 6)))
  2785. (and (match-end 3) (match-end 6) (not (match-end 5))))
  2786. (user-error "Invalid row descriptor `%s'" desc))
  2787. (let* ((hn (and (match-end 3) (- (match-end 3) (match-beginning 3))))
  2788. (hdir (match-string 2 desc))
  2789. (odir (match-string 5 desc))
  2790. (on (and (match-end 6) (string-to-number (match-string 6 desc))))
  2791. (rel (and (match-end 6)
  2792. (or (and (match-end 1) (not (match-end 3)))
  2793. (match-end 5)))))
  2794. (when (and hn (not hdir))
  2795. (setq cline 0)
  2796. (setq hdir "+")
  2797. (when (eq (aref org-table-current-line-types 0) 'hline) (decf hn)))
  2798. (when (and (not hn) on (not odir)) (user-error "Should never happen"))
  2799. (when hn
  2800. (setq cline
  2801. (org-table--row-type 'hline hn cline (equal hdir "-") nil desc)))
  2802. (when on
  2803. (setq cline
  2804. (org-table--row-type 'dline on cline (equal odir "-") rel desc)))
  2805. cline)))
  2806. (defun org-table--row-type (type n i backwards relative desc)
  2807. "Return relative line of Nth row with type TYPE.
  2808. Search starts from relative line I. When BACKWARDS in non-nil,
  2809. look before I. When RELATIVE is non-nil, the reference is
  2810. relative. DESC is the original descriptor that started the
  2811. search, as a string."
  2812. (let ((l (length org-table-current-line-types)))
  2813. (catch :exit
  2814. (dotimes (_ n)
  2815. (while (and (incf i (if backwards -1 1))
  2816. (>= i 0)
  2817. (< i l)
  2818. (not (eq (aref org-table-current-line-types i) type))
  2819. ;; We are going to cross a hline. Check if this is
  2820. ;; an authorized move.
  2821. (cond
  2822. ((not relative))
  2823. ((not (eq (aref org-table-current-line-types i) 'hline)))
  2824. ((eq org-table-relative-ref-may-cross-hline t))
  2825. ((eq org-table-relative-ref-may-cross-hline 'error)
  2826. (user-error "Row descriptor %s crosses hline" desc))
  2827. (t (decf i (if backwards -1 1)) ; Step back.
  2828. (throw :exit nil)))))))
  2829. (cond ((or (< i 0) (>= i l))
  2830. (user-error "Row descriptor %s leads outside table" desc))
  2831. ;; The last hline doesn't exist. Instead, point to last row
  2832. ;; in table.
  2833. ((= i (1- l)) (1- i))
  2834. (t i))))
  2835. (defun org-table--error-on-old-row-references (s)
  2836. (when (string-match "&[-+0-9I]" s)
  2837. (user-error "Formula contains old &row reference, please rewrite using @-syntax")))
  2838. (defun org-table-make-reference (elements keep-empty numbers lispp)
  2839. "Convert list ELEMENTS to something appropriate to insert into formula.
  2840. KEEP-EMPTY indicated to keep empty fields, default is to skip them.
  2841. NUMBERS indicates that everything should be converted to numbers.
  2842. LISPP non-nil means to return something appropriate for a Lisp
  2843. list, `literal' is for the format specifier L."
  2844. ;; Calc nan (not a number) is used for the conversion of the empty
  2845. ;; field to a reference for several reasons: (i) It is accepted in a
  2846. ;; Calc formula (e. g. "" or "()" would result in a Calc error).
  2847. ;; (ii) In a single field (not in range) it can be distinguished
  2848. ;; from "(nan)" which is the reference made from a single field
  2849. ;; containing "nan".
  2850. (if (stringp elements)
  2851. ;; field reference
  2852. (if lispp
  2853. (if (eq lispp 'literal)
  2854. elements
  2855. (if (and (eq elements "") (not keep-empty))
  2856. ""
  2857. (prin1-to-string
  2858. (if numbers (string-to-number elements) elements))))
  2859. (if (string-match "\\S-" elements)
  2860. (progn
  2861. (when numbers (setq elements (number-to-string
  2862. (string-to-number elements))))
  2863. (concat "(" elements ")"))
  2864. (if (or (not keep-empty) numbers) "(0)" "nan")))
  2865. ;; range reference
  2866. (unless keep-empty
  2867. (setq elements
  2868. (delq nil
  2869. (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
  2870. elements))))
  2871. (setq elements (or elements '())) ; if delq returns nil then we need '()
  2872. (if lispp
  2873. (mapconcat
  2874. (lambda (x)
  2875. (if (eq lispp 'literal)
  2876. x
  2877. (prin1-to-string (if numbers (string-to-number x) x))))
  2878. elements " ")
  2879. (concat "[" (mapconcat
  2880. (lambda (x)
  2881. (if (string-match "\\S-" x)
  2882. (if numbers
  2883. (number-to-string (string-to-number x))
  2884. x)
  2885. (if (or (not keep-empty) numbers) "0" "nan")))
  2886. elements
  2887. ",") "]"))))
  2888. (defun org-table-message-once-per-second (t1 &rest args)
  2889. "If there has been more than one second since T1, display message.
  2890. ARGS are passed as arguments to the `message' function. Returns
  2891. current time if a message is printed, otherwise returns T1. If
  2892. T1 is nil, always messages."
  2893. (let ((curtime (current-time)))
  2894. (if (or (not t1) (< 0 (nth 1 (time-subtract curtime t1))))
  2895. (progn (apply 'message args)
  2896. curtime)
  2897. t1)))
  2898. ;;;###autoload
  2899. (defun org-table-recalculate (&optional all noalign)
  2900. "Recalculate the current table line by applying all stored formulas.
  2901. With prefix arg ALL, do this for all lines in the table.
  2902. With the prefix argument ALL is `(16)' \
  2903. \(a double \\[universal-prefix] \\[universal-prefix] prefix), or if
  2904. it is the symbol `iterate', recompute the table until it no longer changes.
  2905. If NOALIGN is not nil, do not re-align the table after the computations
  2906. are done. This is typically used internally to save time, if it is
  2907. known that the table will be realigned a little later anyway."
  2908. (interactive "P")
  2909. (unless (memq this-command org-recalc-commands)
  2910. (push this-command org-recalc-commands))
  2911. (unless (org-at-table-p) (user-error "Not at a table"))
  2912. (if (or (eq all 'iterate) (equal all '(16)))
  2913. (org-table-iterate)
  2914. (org-table-analyze)
  2915. (let* ((eqlist (sort (org-table-get-stored-formulas)
  2916. (lambda (a b) (string< (car a) (car b)))))
  2917. (eqlist1 (copy-sequence eqlist))
  2918. (inhibit-redisplay (not debug-on-error))
  2919. (line-re org-table-dataline-regexp)
  2920. (log-first-time (current-time))
  2921. (log-last-time log-first-time)
  2922. (cnt 0)
  2923. beg end eqlcol eqlfield)
  2924. ;; Insert constants in all formulas
  2925. (when eqlist
  2926. (org-table-save-field
  2927. (setq eqlist
  2928. (mapcar
  2929. (lambda (x)
  2930. (when (string-match "\\`@-?I+" (car x))
  2931. (user-error "Can't assign to hline relative reference"))
  2932. (when (string-match "\\`$[<>]" (car x))
  2933. (let ((old-lhs (car x)))
  2934. (setq x
  2935. (cons
  2936. (substring
  2937. (org-table-formula-handle-first/last-rc old-lhs)
  2938. 1)
  2939. (cdr x)))
  2940. (when (assoc (car x) eqlist1)
  2941. (user-error "\"%s=\" formula tries to overwrite \
  2942. existing formula for column %s"
  2943. old-lhs
  2944. (car x)))))
  2945. (cons (org-table-formula-handle-first/last-rc (car x))
  2946. (org-table-formula-substitute-names
  2947. (org-table-formula-handle-first/last-rc (cdr x)))))
  2948. eqlist))
  2949. ;; Split the equation list between column formulas and field
  2950. ;; formulas.
  2951. (dolist (eq eqlist)
  2952. (if (org-string-match-p "\\`\\$[0-9]+\\'" (car eq))
  2953. (push eq eqlcol)
  2954. (push eq eqlfield)))
  2955. (setq eqlcol (nreverse eqlcol))
  2956. ;; Expand ranges in lhs of formulas
  2957. (setq eqlfield (org-table-expand-lhs-ranges (nreverse eqlfield)))
  2958. ;; Get the correct line range to process.
  2959. (if all
  2960. (progn
  2961. (setq end (copy-marker (org-table-end)))
  2962. (goto-char (setq beg org-table-current-begin-pos))
  2963. (cond
  2964. ((re-search-forward org-table-calculate-mark-regexp end t)
  2965. ;; This is a table with marked lines, compute selected
  2966. ;; lines.
  2967. (setq line-re org-table-recalculate-regexp))
  2968. ;; Move forward to the first non-header line.
  2969. ((and (re-search-forward org-table-dataline-regexp end t)
  2970. (re-search-forward org-table-hline-regexp end t)
  2971. (re-search-forward org-table-dataline-regexp end t))
  2972. (setq beg (match-beginning 0)))
  2973. ;; Just leave BEG where it is.
  2974. (t (setq beg (line-beginning-position)))))
  2975. (setq beg (line-beginning-position)
  2976. end (copy-marker (line-beginning-position 2))))
  2977. (goto-char beg)
  2978. ;; Mark named fields untouchable. Also check if several
  2979. ;; field/range formulas try to set the same field.
  2980. (remove-text-properties beg end '(org-untouchable t))
  2981. (let ((current-line (count-lines org-table-current-begin-pos
  2982. (line-beginning-position)))
  2983. seen-fields)
  2984. (dolist (eq eqlfield)
  2985. (let* ((name (car eq))
  2986. (location (assoc name org-table-named-field-locations))
  2987. (eq-line (or (nth 1 location)
  2988. (and (string-match "\\`@\\([0-9]+\\)" name)
  2989. (aref org-table-dlines
  2990. (string-to-number
  2991. (match-string 1 name))))))
  2992. (reference
  2993. (if location
  2994. ;; Turn field coordinates associated to NAME
  2995. ;; into an absolute reference.
  2996. (format "@%d$%d"
  2997. (org-table-line-to-dline eq-line)
  2998. (nth 2 location))
  2999. name)))
  3000. (when (member reference seen-fields)
  3001. (user-error "Several field/range formulas try to set %s"
  3002. reference))
  3003. (push reference seen-fields)
  3004. (when (or all (eq eq-line current-line))
  3005. (org-table-goto-field name)
  3006. (org-table-put-field-property :org-untouchable t)))))
  3007. ;; Evaluate the column formulas, but skip fields covered by
  3008. ;; field formulas.
  3009. (goto-char beg)
  3010. (while (re-search-forward line-re end t)
  3011. (unless (string-match "\\` *[_^!$/] *\\'" (org-table-get-field 1))
  3012. ;; Unprotected line, recalculate.
  3013. (incf cnt)
  3014. (when all
  3015. (setq log-last-time
  3016. (org-table-message-once-per-second
  3017. log-last-time
  3018. "Re-applying formulas to full table...(line %d)" cnt)))
  3019. (if (markerp org-last-recalc-line)
  3020. (move-marker org-last-recalc-line (line-beginning-position))
  3021. (setq org-last-recalc-line
  3022. (copy-marker (line-beginning-position))))
  3023. (dolist (entry eqlcol)
  3024. (goto-char org-last-recalc-line)
  3025. (org-table-goto-column
  3026. (string-to-number (substring (car entry) 1)) nil 'force)
  3027. (unless (get-text-property (point) :org-untouchable)
  3028. (org-table-eval-formula
  3029. nil (cdr entry) 'noalign 'nocst 'nostore 'noanalysis)))))
  3030. ;; Evaluate the field formulas.
  3031. (dolist (eq eqlfield)
  3032. (let ((reference (car eq))
  3033. (formula (cdr eq)))
  3034. (setq log-last-time
  3035. (org-table-message-once-per-second
  3036. (and all log-last-time)
  3037. "Re-applying formula to field: %s" (car eq)))
  3038. (org-table-goto-field
  3039. reference
  3040. ;; Possibly create a new column, as long as
  3041. ;; `org-table-formula-create-columns' allows it.
  3042. (let ((column-count (progn (end-of-line)
  3043. (1- (org-table-current-column)))))
  3044. `(lambda (column)
  3045. (when (> column 1000)
  3046. (user-error "Formula column target too large"))
  3047. (and (> column ,column-count)
  3048. (or (eq org-table-formula-create-columns t)
  3049. (and (eq org-table-formula-create-columns 'warn)
  3050. (progn
  3051. (org-display-warning
  3052. "Out-of-bounds formula added columns")
  3053. t))
  3054. (and (eq org-table-formula-create-columns 'prompt)
  3055. (yes-or-no-p
  3056. "Out-of-bounds formula. Add columns? ")))))))
  3057. (org-table-eval-formula nil formula t t t t))))
  3058. ;; Clean up markers and internal text property.
  3059. (remove-text-properties (point-min) (point-max) '(org-untouchable t))
  3060. (set-marker end nil)
  3061. (unless noalign
  3062. (when org-table-may-need-update (org-table-align))
  3063. (when all
  3064. (org-table-message-once-per-second
  3065. log-first-time "Re-applying formulas to %d lines... done" cnt)))
  3066. (org-table-message-once-per-second
  3067. (and all log-first-time) "Re-applying formulas... done")))))
  3068. ;;;###autoload
  3069. (defun org-table-iterate (&optional arg)
  3070. "Recalculate the table until it does not change anymore.
  3071. The maximum number of iterations is 10, but you can choose a different value
  3072. with the prefix ARG."
  3073. (interactive "P")
  3074. (let ((imax (if arg (prefix-numeric-value arg) 10))
  3075. (i 0)
  3076. (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
  3077. thistbl)
  3078. (catch 'exit
  3079. (while (< i imax)
  3080. (setq i (1+ i))
  3081. (org-table-recalculate 'all)
  3082. (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
  3083. (if (not (string= lasttbl thistbl))
  3084. (setq lasttbl thistbl)
  3085. (if (> i 1)
  3086. (message "Convergence after %d iterations" i)
  3087. (message "Table was already stable"))
  3088. (throw 'exit t)))
  3089. (user-error "No convergence after %d iterations" i))))
  3090. ;;;###autoload
  3091. (defun org-table-recalculate-buffer-tables ()
  3092. "Recalculate all tables in the current buffer."
  3093. (interactive)
  3094. (save-excursion
  3095. (save-restriction
  3096. (widen)
  3097. (org-table-map-tables (lambda () (org-table-recalculate t)) t))))
  3098. ;;;###autoload
  3099. (defun org-table-iterate-buffer-tables ()
  3100. "Iterate all tables in the buffer, to converge inter-table dependencies."
  3101. (interactive)
  3102. (let* ((imax 10)
  3103. (i imax)
  3104. (checksum (md5 (buffer-string)))
  3105. c1)
  3106. (save-excursion
  3107. (save-restriction
  3108. (widen)
  3109. (catch 'exit
  3110. (while (> i 0)
  3111. (setq i (1- i))
  3112. (org-table-map-tables (lambda () (org-table-recalculate t)) t)
  3113. (if (equal checksum (setq c1 (md5 (buffer-string))))
  3114. (progn
  3115. (message "Convergence after %d iterations" (- imax i))
  3116. (throw 'exit t))
  3117. (setq checksum c1)))
  3118. (user-error "No convergence after %d iterations" imax))))))
  3119. (defun org-table-calc-current-TBLFM (&optional arg)
  3120. "Apply the #+TBLFM in the line at point to the table."
  3121. (interactive "P")
  3122. (unless (org-at-TBLFM-p) (user-error "Not at a #+TBLFM line"))
  3123. (let ((formula (buffer-substring
  3124. (line-beginning-position)
  3125. (line-end-position))))
  3126. (save-excursion
  3127. ;; Insert a temporary formula at right after the table
  3128. (goto-char (org-table-TBLFM-begin))
  3129. (let ((s (point-marker)))
  3130. (insert formula "\n")
  3131. (let ((e (point-marker)))
  3132. ;; Recalculate the table.
  3133. (beginning-of-line 0) ; move to the inserted line
  3134. (skip-chars-backward " \r\n\t")
  3135. (unwind-protect
  3136. (org-call-with-arg #'org-table-recalculate (or arg t))
  3137. ;; Delete the formula inserted temporarily.
  3138. (delete-region s e)
  3139. (set-marker s nil)
  3140. (set-marker e nil)))))))
  3141. (defun org-table-TBLFM-begin ()
  3142. "Find the beginning of the TBLFM lines and return its position.
  3143. Return nil when the beginning of TBLFM line was not found."
  3144. (save-excursion
  3145. (when (progn (forward-line 1)
  3146. (re-search-backward org-table-TBLFM-begin-regexp nil t))
  3147. (line-beginning-position 2))))
  3148. (defun org-table-expand-lhs-ranges (equations)
  3149. "Expand list of formulas.
  3150. If some of the RHS in the formulas are ranges or a row reference,
  3151. expand them to individual field equations for each field. This
  3152. function assumes the table is already analyzed (i.e., using
  3153. `org-table-analyze')."
  3154. (let (res)
  3155. (dolist (e equations (nreverse res))
  3156. (let ((lhs (car e))
  3157. (rhs (cdr e)))
  3158. (cond
  3159. ((org-string-match-p "\\`@-?[-+0-9]+\\$-?[0-9]+\\'" lhs)
  3160. ;; This just refers to one fixed field.
  3161. (push e res))
  3162. ((org-string-match-p "\\`[a-zA-Z][_a-zA-Z0-9]*\\'" lhs)
  3163. ;; This just refers to one fixed named field.
  3164. (push e res))
  3165. ((org-string-match-p "\\`\\$[0-9]+\\'" lhs)
  3166. ;; Column formulas are treated specially and are not
  3167. ;; expanded.
  3168. (push e res))
  3169. ((string-match "\\`@[0-9]+\\'" lhs)
  3170. (dotimes (ic org-table-current-ncol)
  3171. (push (cons (propertize (format "%s$%d" lhs (1+ ic)) :orig-eqn e)
  3172. rhs)
  3173. res)))
  3174. (t
  3175. (let* ((range (org-table-get-range
  3176. lhs org-table-current-begin-pos 1 nil 'corners))
  3177. (r1 (org-table-line-to-dline (nth 0 range)))
  3178. (c1 (nth 1 range))
  3179. (r2 (org-table-line-to-dline (nth 2 range) 'above))
  3180. (c2 (nth 3 range)))
  3181. (loop for ir from r1 to r2 do
  3182. (loop for ic from c1 to c2 do
  3183. (push
  3184. (cons (propertize (format "@%d$%d" ir ic) :orig-eqn e)
  3185. rhs)
  3186. res))))))))))
  3187. (defun org-table-formula-handle-first/last-rc (s)
  3188. "Replace @<, @>, $<, $> with first/last row/column of the table.
  3189. So @< and $< will always be replaced with @1 and $1, respectively.
  3190. The advantage of these special markers are that structure editing of
  3191. the table will not change them, while @1 and $1 will be modified
  3192. when a line/row is swapped out of that privileged position. So for
  3193. formulas that use a range of rows or columns, it may often be better
  3194. to anchor the formula with \"I\" row markers, or to offset from the
  3195. borders of the table using the @< @> $< $> makers."
  3196. (let (n nmax len char (start 0))
  3197. (while (string-match "\\([@$]\\)\\(<+\\|>+\\)\\|\\(remote([^)]+)\\)"
  3198. s start)
  3199. (if (match-end 3)
  3200. (setq start (match-end 3))
  3201. (setq nmax (if (equal (match-string 1 s) "@")
  3202. (1- (length org-table-dlines))
  3203. org-table-current-ncol)
  3204. len (- (match-end 2) (match-beginning 2))
  3205. char (string-to-char (match-string 2 s))
  3206. n (if (= char ?<)
  3207. len
  3208. (- nmax len -1)))
  3209. (if (or (< n 1) (> n nmax))
  3210. (user-error "Reference \"%s\" in expression \"%s\" points outside table"
  3211. (match-string 0 s) s))
  3212. (setq start (match-beginning 0))
  3213. (setq s (replace-match (format "%s%d" (match-string 1 s) n) t t s)))))
  3214. s)
  3215. (defun org-table-formula-substitute-names (f)
  3216. "Replace $const with values in string F."
  3217. (let ((start 0)
  3218. (pp (/= (string-to-char f) ?'))
  3219. (duration (org-string-match-p ";.*[Tt].*\\'" f))
  3220. (new (replace-regexp-in-string ; Check for column names.
  3221. org-table-column-name-regexp
  3222. (lambda (m)
  3223. (concat "$" (cdr (assoc (match-string 1 m)
  3224. org-table-column-names))))
  3225. f t t)))
  3226. ;; Parameters and constants.
  3227. (while (setq start
  3228. (string-match
  3229. "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)\\|\\(\\<remote([^)]*)\\)"
  3230. new start))
  3231. (if (match-end 2) (setq start (match-end 2))
  3232. (incf start)
  3233. ;; When a duration is expected, convert value on the fly.
  3234. (let ((value
  3235. (save-match-data
  3236. (let ((v (org-table-get-constant (match-string 1 new))))
  3237. (if (and (org-string-nw-p v) duration)
  3238. (org-table-time-string-to-seconds v)
  3239. v)))))
  3240. (when value
  3241. (setq new (replace-match
  3242. (concat (and pp "(") value (and pp ")")) t t new))))))
  3243. (if org-table-formula-debug (org-propertize new :orig-formula f)) new))
  3244. (defun org-table-get-constant (const)
  3245. "Find the value for a parameter or constant in a formula.
  3246. Parameters get priority."
  3247. (or (cdr (assoc const org-table-local-parameters))
  3248. (cdr (assoc const org-table-formula-constants-local))
  3249. (cdr (assoc const org-table-formula-constants))
  3250. (and (fboundp 'constants-get) (constants-get const))
  3251. (and (string= (substring const 0 (min 5 (length const))) "PROP_")
  3252. (org-entry-get nil (substring const 5) 'inherit))
  3253. "#UNDEFINED_NAME"))
  3254. (defvar org-table-fedit-map
  3255. (let ((map (make-sparse-keymap)))
  3256. (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
  3257. (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
  3258. (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
  3259. (org-defkey map "\C-c'" 'org-table-fedit-finish)
  3260. (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
  3261. (org-defkey map "\C-c?" 'org-table-show-reference)
  3262. (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
  3263. (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
  3264. (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
  3265. (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
  3266. (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
  3267. (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
  3268. (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
  3269. (org-defkey map [(meta down)] 'org-table-fedit-scroll)
  3270. (org-defkey map [(meta tab)] 'lisp-complete-symbol)
  3271. (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
  3272. (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
  3273. (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
  3274. (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
  3275. (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
  3276. map))
  3277. (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
  3278. '("Edit-Formulas"
  3279. ["Finish and Install" org-table-fedit-finish t]
  3280. ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
  3281. ["Abort" org-table-fedit-abort t]
  3282. "--"
  3283. ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
  3284. ["Complete Lisp Symbol" lisp-complete-symbol t]
  3285. "--"
  3286. "Shift Reference at Point"
  3287. ["Up" org-table-fedit-ref-up t]
  3288. ["Down" org-table-fedit-ref-down t]
  3289. ["Left" org-table-fedit-ref-left t]
  3290. ["Right" org-table-fedit-ref-right t]
  3291. "-"
  3292. "Change Test Row for Column Formulas"
  3293. ["Up" org-table-fedit-line-up t]
  3294. ["Down" org-table-fedit-line-down t]
  3295. "--"
  3296. ["Scroll Table Window" org-table-fedit-scroll t]
  3297. ["Scroll Table Window down" org-table-fedit-scroll-down t]
  3298. ["Show Table Grid" org-table-fedit-toggle-coordinates
  3299. :style toggle :selected (with-current-buffer (marker-buffer org-pos)
  3300. org-table-overlay-coordinates)]
  3301. "--"
  3302. ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
  3303. :style toggle :selected org-table-buffer-is-an]))
  3304. (defvar org-pos)
  3305. ;;;###autoload
  3306. (defun org-table-edit-formulas ()
  3307. "Edit the formulas of the current table in a separate buffer."
  3308. (interactive)
  3309. (when (save-excursion (beginning-of-line)
  3310. (let ((case-fold-search t)) (looking-at "[ \t]*#\\+TBLFM")))
  3311. (beginning-of-line 0))
  3312. (unless (org-at-table-p) (user-error "Not at a table"))
  3313. (org-table-analyze)
  3314. (let ((key (org-table-current-field-formula 'key 'noerror))
  3315. (eql (sort (org-table-get-stored-formulas 'noerror)
  3316. #'org-table-formula-less-p))
  3317. (pos (point-marker))
  3318. (startline 1)
  3319. (wc (current-window-configuration))
  3320. (sel-win (selected-window))
  3321. (titles '((column . "# Column Formulas\n")
  3322. (field . "# Field and Range Formulas\n")
  3323. (named . "# Named Field Formulas\n"))))
  3324. (org-switch-to-buffer-other-window "*Edit Formulas*")
  3325. (erase-buffer)
  3326. ;; Keep global-font-lock-mode from turning on font-lock-mode
  3327. (let ((font-lock-global-modes '(not fundamental-mode)))
  3328. (fundamental-mode))
  3329. (setq-local font-lock-global-modes (list 'not major-mode))
  3330. (setq-local org-pos pos)
  3331. (setq-local org-window-configuration wc)
  3332. (setq-local org-selected-window sel-win)
  3333. (use-local-map org-table-fedit-map)
  3334. (org-add-hook 'post-command-hook #'org-table-fedit-post-command t t)
  3335. (easy-menu-add org-table-fedit-menu)
  3336. (setq startline (org-current-line))
  3337. (dolist (entry eql)
  3338. (let* ((type (cond
  3339. ((string-match "\\`$[<>]" (car entry)) 'column)
  3340. ((equal (string-to-char (car entry)) ?@) 'field)
  3341. ((string-match "\\'[0-9]" (car entry)) 'column)
  3342. (t 'named)))
  3343. (title (assq type titles)))
  3344. (when title
  3345. (unless (bobp) (insert "\n"))
  3346. (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
  3347. (setq titles (remove title titles)))
  3348. (when (equal key (car entry)) (setq startline (org-current-line)))
  3349. (let ((s (concat (if (member (string-to-char (car entry)) '(?@ ?$)) "" "$")
  3350. (car entry) " = " (cdr entry) "\n")))
  3351. (remove-text-properties 0 (length s) '(face nil) s)
  3352. (insert s))))
  3353. (when (eq org-table-use-standard-references t)
  3354. (org-table-fedit-toggle-ref-type))
  3355. (org-goto-line startline)
  3356. (message
  3357. (substitute-command-keys "\\<org-mode-map>\
  3358. Edit formulas, finish with `\\[org-ctrl-c-ctrl-c]' or `\\[org-edit-special]'. \
  3359. See menu for more commands."))))
  3360. (defun org-table-fedit-post-command ()
  3361. (when (not (memq this-command '(lisp-complete-symbol)))
  3362. (let ((win (selected-window)))
  3363. (save-excursion
  3364. (ignore-errors (org-table-show-reference))
  3365. (select-window win)))))
  3366. (defun org-table-formula-to-user (s)
  3367. "Convert a formula from internal to user representation."
  3368. (if (eq org-table-use-standard-references t)
  3369. (org-table-convert-refs-to-an s)
  3370. s))
  3371. (defun org-table-formula-from-user (s)
  3372. "Convert a formula from user to internal representation."
  3373. (if org-table-use-standard-references
  3374. (org-table-convert-refs-to-rc s)
  3375. s))
  3376. (defun org-table-convert-refs-to-rc (s)
  3377. "Convert spreadsheet references from A7 to @7$28.
  3378. Works for single references, but also for entire formulas and even the
  3379. full TBLFM line."
  3380. (let ((start 0))
  3381. (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\|\\<remote([^,)]*)\\)" s start)
  3382. (cond
  3383. ((match-end 3)
  3384. ;; format match, just advance
  3385. (setq start (match-end 0)))
  3386. ((and (> (match-beginning 0) 0)
  3387. (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
  3388. (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
  3389. ;; 3.e5 or something like this.
  3390. (setq start (match-end 0)))
  3391. ((or (> (- (match-end 1) (match-beginning 1)) 2)
  3392. ;; (member (match-string 1 s)
  3393. ;; '("arctan" "exp" "expm" "lnp" "log" "stir"))
  3394. )
  3395. ;; function name, just advance
  3396. (setq start (match-end 0)))
  3397. (t
  3398. (setq start (match-beginning 0)
  3399. s (replace-match
  3400. (if (equal (match-string 2 s) "&")
  3401. (format "$%d" (org-letters-to-number (match-string 1 s)))
  3402. (format "@%d$%d"
  3403. (string-to-number (match-string 2 s))
  3404. (org-letters-to-number (match-string 1 s))))
  3405. t t s)))))
  3406. s))
  3407. (defun org-table-convert-refs-to-an (s)
  3408. "Convert spreadsheet references from to @7$28 to AB7.
  3409. Works for single references, but also for entire formulas and even the
  3410. full TBLFM line."
  3411. (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
  3412. (setq s (replace-match
  3413. (format "%s%d"
  3414. (org-number-to-letters
  3415. (string-to-number (match-string 2 s)))
  3416. (string-to-number (match-string 1 s)))
  3417. t t s)))
  3418. (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
  3419. (setq s (replace-match (concat "\\1"
  3420. (org-number-to-letters
  3421. (string-to-number (match-string 2 s))) "&")
  3422. t nil s)))
  3423. s)
  3424. (defun org-letters-to-number (s)
  3425. "Convert a base 26 number represented by letters into an integer.
  3426. For example: AB -> 28."
  3427. (let ((n 0))
  3428. (setq s (upcase s))
  3429. (while (> (length s) 0)
  3430. (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
  3431. s (substring s 1)))
  3432. n))
  3433. (defun org-number-to-letters (n)
  3434. "Convert an integer into a base 26 number represented by letters.
  3435. For example: 28 -> AB."
  3436. (let ((s ""))
  3437. (while (> n 0)
  3438. (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
  3439. n (/ (1- n) 26)))
  3440. s))
  3441. (defun org-table-time-string-to-seconds (s)
  3442. "Convert a time string into numerical duration in seconds.
  3443. S can be a string matching either -?HH:MM:SS or -?HH:MM.
  3444. If S is a string representing a number, keep this number."
  3445. (if (equal s "")
  3446. s
  3447. (let (hour minus min sec res)
  3448. (cond
  3449. ((and (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\):\\([0-9]+\\)" s))
  3450. (setq minus (< 0 (length (match-string 1 s)))
  3451. hour (string-to-number (match-string 2 s))
  3452. min (string-to-number (match-string 3 s))
  3453. sec (string-to-number (match-string 4 s)))
  3454. (if minus
  3455. (setq res (- (+ (* hour 3600) (* min 60) sec)))
  3456. (setq res (+ (* hour 3600) (* min 60) sec))))
  3457. ((and (not (string-match org-ts-regexp-both s))
  3458. (string-match "\\(-?\\)\\([0-9]+\\):\\([0-9]+\\)" s))
  3459. (setq minus (< 0 (length (match-string 1 s)))
  3460. hour (string-to-number (match-string 2 s))
  3461. min (string-to-number (match-string 3 s)))
  3462. (if minus
  3463. (setq res (- (+ (* hour 3600) (* min 60))))
  3464. (setq res (+ (* hour 3600) (* min 60)))))
  3465. (t (setq res (string-to-number s))))
  3466. (number-to-string res))))
  3467. (defun org-table-time-seconds-to-string (secs &optional output-format)
  3468. "Convert a number of seconds to a time string.
  3469. If OUTPUT-FORMAT is non-nil, return a number of days, hours,
  3470. minutes or seconds."
  3471. (let* ((secs0 (abs secs))
  3472. (res
  3473. (cond ((eq output-format 'days)
  3474. (format "%.3f" (/ (float secs0) 86400)))
  3475. ((eq output-format 'hours)
  3476. (format "%.2f" (/ (float secs0) 3600)))
  3477. ((eq output-format 'minutes)
  3478. (format "%.1f" (/ (float secs0) 60)))
  3479. ((eq output-format 'seconds)
  3480. (format "%d" secs0))
  3481. (t (org-format-seconds "%.2h:%.2m:%.2s" secs0)))))
  3482. (if (< secs 0) (concat "-" res) res)))
  3483. (defun org-table-fedit-convert-buffer (function)
  3484. "Convert all references in this buffer, using FUNCTION."
  3485. (let ((origin (copy-marker (line-beginning-position))))
  3486. (goto-char (point-min))
  3487. (while (not (eobp))
  3488. (insert (funcall function (buffer-substring (point) (line-end-position))))
  3489. (delete-region (point) (line-end-position))
  3490. (forward-line))
  3491. (goto-char origin)
  3492. (set-marker origin nil)))
  3493. (defun org-table-fedit-toggle-ref-type ()
  3494. "Convert all references in the buffer from B3 to @3$2 and back."
  3495. (interactive)
  3496. (setq-local org-table-buffer-is-an (not org-table-buffer-is-an))
  3497. (org-table-fedit-convert-buffer
  3498. (if org-table-buffer-is-an
  3499. 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
  3500. (message "Reference type switched to %s"
  3501. (if org-table-buffer-is-an "A1 etc" "@row$column")))
  3502. (defun org-table-fedit-ref-up ()
  3503. "Shift the reference at point one row/hline up."
  3504. (interactive)
  3505. (org-table-fedit-shift-reference 'up))
  3506. (defun org-table-fedit-ref-down ()
  3507. "Shift the reference at point one row/hline down."
  3508. (interactive)
  3509. (org-table-fedit-shift-reference 'down))
  3510. (defun org-table-fedit-ref-left ()
  3511. "Shift the reference at point one field to the left."
  3512. (interactive)
  3513. (org-table-fedit-shift-reference 'left))
  3514. (defun org-table-fedit-ref-right ()
  3515. "Shift the reference at point one field to the right."
  3516. (interactive)
  3517. (org-table-fedit-shift-reference 'right))
  3518. (defun org-table-fedit-shift-reference (dir)
  3519. (cond
  3520. ((org-in-regexp "\\(\\<[a-zA-Z]\\)&")
  3521. (if (memq dir '(left right))
  3522. (org-rematch-and-replace 1 (eq dir 'left))
  3523. (user-error "Cannot shift reference in this direction")))
  3524. ((org-in-regexp "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
  3525. ;; A B3-like reference
  3526. (if (memq dir '(up down))
  3527. (org-rematch-and-replace 2 (eq dir 'up))
  3528. (org-rematch-and-replace 1 (eq dir 'left))))
  3529. ((org-in-regexp
  3530. "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
  3531. ;; An internal reference
  3532. (if (memq dir '(up down))
  3533. (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
  3534. (org-rematch-and-replace 5 (eq dir 'left))))))
  3535. (defun org-rematch-and-replace (n &optional decr hline)
  3536. "Re-match the group N, and replace it with the shifted reference."
  3537. (or (match-end n) (user-error "Cannot shift reference in this direction"))
  3538. (goto-char (match-beginning n))
  3539. (and (looking-at (regexp-quote (match-string n)))
  3540. (replace-match (org-table-shift-refpart (match-string 0) decr hline)
  3541. t t)))
  3542. (defun org-table-shift-refpart (ref &optional decr hline)
  3543. "Shift a reference part REF.
  3544. If DECR is set, decrease the references row/column, else increase.
  3545. If HLINE is set, this may be a hline reference, it certainly is not
  3546. a translation reference."
  3547. (save-match-data
  3548. (let* ((sign (string-match "^[-+]" ref)) n)
  3549. (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
  3550. (cond
  3551. ((and hline (string-match "^I+" ref))
  3552. (setq n (string-to-number (concat sign (number-to-string (length ref)))))
  3553. (setq n (+ n (if decr -1 1)))
  3554. (if (= n 0) (setq n (+ n (if decr -1 1))))
  3555. (if sign
  3556. (setq sign (if (< n 0) "-" "+") n (abs n))
  3557. (setq n (max 1 n)))
  3558. (concat sign (make-string n ?I)))
  3559. ((string-match "^[0-9]+" ref)
  3560. (setq n (string-to-number (concat sign ref)))
  3561. (setq n (+ n (if decr -1 1)))
  3562. (if sign
  3563. (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
  3564. (number-to-string (max 1 n))))
  3565. ((string-match "^[a-zA-Z]+" ref)
  3566. (org-number-to-letters
  3567. (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
  3568. (t (user-error "Cannot shift reference"))))))
  3569. (defun org-table-fedit-toggle-coordinates ()
  3570. "Toggle the display of coordinates in the referenced table."
  3571. (interactive)
  3572. (let ((pos (marker-position org-pos)))
  3573. (with-current-buffer (marker-buffer org-pos)
  3574. (save-excursion
  3575. (goto-char pos)
  3576. (org-table-toggle-coordinate-overlays)))))
  3577. (defun org-table-fedit-finish (&optional arg)
  3578. "Parse the buffer for formula definitions and install them.
  3579. With prefix ARG, apply the new formulas to the table."
  3580. (interactive "P")
  3581. (org-table-remove-rectangle-highlight)
  3582. (if org-table-use-standard-references
  3583. (progn
  3584. (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
  3585. (setq org-table-buffer-is-an nil)))
  3586. (let ((pos org-pos) (sel-win org-selected-window) eql var form)
  3587. (goto-char (point-min))
  3588. (while (re-search-forward
  3589. "^\\(@[-+I<>0-9.$@]+\\|@?[0-9]+\\|\\$\\([a-zA-Z0-9]+\\|[<>]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
  3590. nil t)
  3591. (setq var (if (match-end 2) (match-string 2) (match-string 1))
  3592. form (match-string 3))
  3593. (setq form (org-trim form))
  3594. (when (not (equal form ""))
  3595. (while (string-match "[ \t]*\n[ \t]*" form)
  3596. (setq form (replace-match " " t t form)))
  3597. (when (assoc var eql)
  3598. (user-error "Double formulas for %s" var))
  3599. (push (cons var form) eql)))
  3600. (setq org-pos nil)
  3601. (set-window-configuration org-window-configuration)
  3602. (select-window sel-win)
  3603. (goto-char pos)
  3604. (unless (org-at-table-p)
  3605. (user-error "Lost table position - cannot install formulas"))
  3606. (org-table-store-formulas eql)
  3607. (move-marker pos nil)
  3608. (kill-buffer "*Edit Formulas*")
  3609. (if arg
  3610. (org-table-recalculate 'all)
  3611. (message "New formulas installed - press C-u C-c C-c to apply."))))
  3612. (defun org-table-fedit-abort ()
  3613. "Abort editing formulas, without installing the changes."
  3614. (interactive)
  3615. (org-table-remove-rectangle-highlight)
  3616. (let ((pos org-pos) (sel-win org-selected-window))
  3617. (set-window-configuration org-window-configuration)
  3618. (select-window sel-win)
  3619. (goto-char pos)
  3620. (move-marker pos nil)
  3621. (message "Formula editing aborted without installing changes")))
  3622. (defun org-table-fedit-lisp-indent ()
  3623. "Pretty-print and re-indent Lisp expressions in the Formula Editor."
  3624. (interactive)
  3625. (let ((pos (point)) beg end ind)
  3626. (beginning-of-line 1)
  3627. (cond
  3628. ((looking-at "[ \t]")
  3629. (goto-char pos)
  3630. (call-interactively 'lisp-indent-line))
  3631. ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
  3632. ((not (fboundp 'pp-buffer))
  3633. (user-error "Cannot pretty-print. Command `pp-buffer' is not available"))
  3634. ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
  3635. (goto-char (- (match-end 0) 2))
  3636. (setq beg (point))
  3637. (setq ind (make-string (current-column) ?\ ))
  3638. (condition-case nil (forward-sexp 1)
  3639. (error
  3640. (user-error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
  3641. (setq end (point))
  3642. (save-restriction
  3643. (narrow-to-region beg end)
  3644. (if (eq last-command this-command)
  3645. (progn
  3646. (goto-char (point-min))
  3647. (setq this-command nil)
  3648. (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
  3649. (replace-match " ")))
  3650. (pp-buffer)
  3651. (untabify (point-min) (point-max))
  3652. (goto-char (1+ (point-min)))
  3653. (while (re-search-forward "^." nil t)
  3654. (beginning-of-line 1)
  3655. (insert ind))
  3656. (goto-char (point-max))
  3657. (org-delete-backward-char 1)))
  3658. (goto-char beg))
  3659. (t nil))))
  3660. (defvar org-show-positions nil)
  3661. (defun org-table-show-reference (&optional local)
  3662. "Show the location/value of the $ expression at point."
  3663. (interactive)
  3664. (org-table-remove-rectangle-highlight)
  3665. (when local (org-table-analyze))
  3666. (catch 'exit
  3667. (let ((pos (if local (point) org-pos))
  3668. (table-start (if local org-table-current-begin-pos (org-table-begin)))
  3669. (face2 'highlight)
  3670. (org-inhibit-highlight-removal t)
  3671. (win (selected-window))
  3672. (org-show-positions nil)
  3673. var name e what match dest)
  3674. (setq what (cond
  3675. ((org-in-regexp "^@[0-9]+[ \t=]")
  3676. (setq match (concat (substring (match-string 0) 0 -1)
  3677. "$1.."
  3678. (substring (match-string 0) 0 -1)
  3679. "$100"))
  3680. 'range)
  3681. ((or (org-in-regexp org-table-range-regexp2)
  3682. (org-in-regexp org-table-translate-regexp)
  3683. (org-in-regexp org-table-range-regexp))
  3684. (setq match
  3685. (save-match-data
  3686. (org-table-convert-refs-to-rc (match-string 0))))
  3687. 'range)
  3688. ((org-in-regexp "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
  3689. ((org-in-regexp "\\$[0-9]+") 'column)
  3690. ((not local) nil)
  3691. (t (user-error "No reference at point")))
  3692. match (and what (or match (match-string 0))))
  3693. (when (and match (not (equal (match-beginning 0) (point-at-bol))))
  3694. (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
  3695. 'secondary-selection))
  3696. (org-add-hook 'before-change-functions
  3697. #'org-table-remove-rectangle-highlight)
  3698. (when (eq what 'name) (setq var (substring match 1)))
  3699. (when (eq what 'range)
  3700. (unless (eq (string-to-char match) ?@) (setq match (concat "@" match)))
  3701. (setq match (org-table-formula-substitute-names match)))
  3702. (unless local
  3703. (save-excursion
  3704. (end-of-line)
  3705. (re-search-backward "^\\S-" nil t)
  3706. (beginning-of-line)
  3707. (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\
  3708. \\([0-9]+\\|&\\)\\) *=")
  3709. (setq dest
  3710. (save-match-data
  3711. (org-table-convert-refs-to-rc (match-string 1))))
  3712. (org-table-add-rectangle-overlay
  3713. (match-beginning 1) (match-end 1) face2))))
  3714. (if (and (markerp pos) (marker-buffer pos))
  3715. (if (get-buffer-window (marker-buffer pos))
  3716. (select-window (get-buffer-window (marker-buffer pos)))
  3717. (org-switch-to-buffer-other-window (get-buffer-window
  3718. (marker-buffer pos)))))
  3719. (goto-char pos)
  3720. (org-table-force-dataline)
  3721. (when dest
  3722. (setq name (substring dest 1))
  3723. (cond
  3724. ((org-string-match-p "\\`\\$[a-zA-Z][a-zA-Z0-9]*" dest)
  3725. (org-table-goto-field dest))
  3726. ((org-string-match-p "\\`@\\([1-9][0-9]*\\)\\$\\([1-9][0-9]*\\)\\'"
  3727. dest)
  3728. (org-table-goto-field dest))
  3729. (t (org-table-goto-column (string-to-number name))))
  3730. (move-marker pos (point))
  3731. (org-table-highlight-rectangle nil nil face2))
  3732. (cond
  3733. ((equal dest match))
  3734. ((not match))
  3735. ((eq what 'range)
  3736. (ignore-errors (org-table-get-range match table-start nil 'highlight)))
  3737. ((setq e (assoc var org-table-named-field-locations))
  3738. (org-table-goto-field var)
  3739. (org-table-highlight-rectangle)
  3740. (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
  3741. ((setq e (assoc var org-table-column-names))
  3742. (org-table-goto-column (string-to-number (cdr e)))
  3743. (org-table-highlight-rectangle)
  3744. (goto-char table-start)
  3745. (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
  3746. (org-table-end) t)
  3747. (progn
  3748. (goto-char (match-beginning 1))
  3749. (org-table-highlight-rectangle)
  3750. (message "Named column (column %s)" (cdr e)))
  3751. (user-error "Column name not found")))
  3752. ((eq what 'column)
  3753. ;; Column number.
  3754. (org-table-goto-column (string-to-number (substring match 1)))
  3755. (org-table-highlight-rectangle)
  3756. (message "Column %s" (substring match 1)))
  3757. ((setq e (assoc var org-table-local-parameters))
  3758. (goto-char table-start)
  3759. (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
  3760. (progn
  3761. (goto-char (match-beginning 1))
  3762. (org-table-highlight-rectangle)
  3763. (message "Local parameter."))
  3764. (user-error "Parameter not found")))
  3765. ((not var) (user-error "No reference at point"))
  3766. ((setq e (assoc var org-table-formula-constants-local))
  3767. (message "Local Constant: $%s=%s in #+CONSTANTS line."
  3768. var (cdr e)))
  3769. ((setq e (assoc var org-table-formula-constants))
  3770. (message "Constant: $%s=%s in `org-table-formula-constants'."
  3771. var (cdr e)))
  3772. ((setq e (and (fboundp 'constants-get) (constants-get var)))
  3773. (message "Constant: $%s=%s, from `constants.el'%s."
  3774. var e (format " (%s units)" constants-unit-system)))
  3775. (t (user-error "Undefined name $%s" var)))
  3776. (goto-char pos)
  3777. (when (and org-show-positions
  3778. (not (memq this-command '(org-table-fedit-scroll
  3779. org-table-fedit-scroll-down))))
  3780. (push pos org-show-positions)
  3781. (push table-start org-show-positions)
  3782. (let ((min (apply 'min org-show-positions))
  3783. (max (apply 'max org-show-positions)))
  3784. (set-window-start (selected-window) min)
  3785. (goto-char max)
  3786. (or (pos-visible-in-window-p max)
  3787. (set-window-start (selected-window) max))))
  3788. (select-window win))))
  3789. (defun org-table-force-dataline ()
  3790. "Make sure the cursor is in a dataline in a table."
  3791. (unless (save-excursion
  3792. (beginning-of-line 1)
  3793. (looking-at org-table-dataline-regexp))
  3794. (let* ((re org-table-dataline-regexp)
  3795. (p1 (save-excursion (re-search-forward re nil 'move)))
  3796. (p2 (save-excursion (re-search-backward re nil 'move))))
  3797. (cond ((and p1 p2)
  3798. (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
  3799. p1 p2)))
  3800. ((or p1 p2) (goto-char (or p1 p2)))
  3801. (t (user-error "No table dataline around here"))))))
  3802. (defun org-table-fedit-line-up ()
  3803. "Move cursor one line up in the window showing the table."
  3804. (interactive)
  3805. (org-table-fedit-move 'previous-line))
  3806. (defun org-table-fedit-line-down ()
  3807. "Move cursor one line down in the window showing the table."
  3808. (interactive)
  3809. (org-table-fedit-move 'next-line))
  3810. (defun org-table-fedit-move (command)
  3811. "Move the cursor in the window showing the table.
  3812. Use COMMAND to do the motion, repeat if necessary to end up in a data line."
  3813. (let ((org-table-allow-automatic-line-recalculation nil)
  3814. (pos org-pos) (win (selected-window)) p)
  3815. (select-window (get-buffer-window (marker-buffer org-pos)))
  3816. (setq p (point))
  3817. (call-interactively command)
  3818. (while (and (org-at-table-p)
  3819. (org-at-table-hline-p))
  3820. (call-interactively command))
  3821. (or (org-at-table-p) (goto-char p))
  3822. (move-marker pos (point))
  3823. (select-window win)))
  3824. (defun org-table-fedit-scroll (N)
  3825. (interactive "p")
  3826. (let ((other-window-scroll-buffer (marker-buffer org-pos)))
  3827. (scroll-other-window N)))
  3828. (defun org-table-fedit-scroll-down (N)
  3829. (interactive "p")
  3830. (org-table-fedit-scroll (- N)))
  3831. (defvar org-table-rectangle-overlays nil)
  3832. (defun org-table-add-rectangle-overlay (beg end &optional face)
  3833. "Add a new overlay."
  3834. (let ((ov (make-overlay beg end)))
  3835. (overlay-put ov 'face (or face 'secondary-selection))
  3836. (push ov org-table-rectangle-overlays)))
  3837. (defun org-table-highlight-rectangle (&optional beg end face)
  3838. "Highlight rectangular region in a table.
  3839. When buffer positions BEG and END are provided, use them to
  3840. delimit the region to highlight. Otherwise, refer to point. Use
  3841. FACE, when non-nil, for the highlight."
  3842. (let* ((beg (or beg (point)))
  3843. (end (or end (point)))
  3844. (b (min beg end))
  3845. (e (max beg end))
  3846. (start-coordinates
  3847. (save-excursion
  3848. (goto-char b)
  3849. (cons (line-beginning-position) (org-table-current-column))))
  3850. (end-coordinates
  3851. (save-excursion
  3852. (goto-char e)
  3853. (cons (line-beginning-position) (org-table-current-column)))))
  3854. (when (boundp 'org-show-positions)
  3855. (setq org-show-positions (cons b (cons e org-show-positions))))
  3856. (goto-char (car start-coordinates))
  3857. (let ((column-start (min (cdr start-coordinates) (cdr end-coordinates)))
  3858. (column-end (max (cdr start-coordinates) (cdr end-coordinates)))
  3859. (last-row (car end-coordinates)))
  3860. (while (<= (point) last-row)
  3861. (when (looking-at org-table-dataline-regexp)
  3862. (org-table-goto-column column-start)
  3863. (skip-chars-backward "^|\n")
  3864. (let ((p (point)))
  3865. (org-table-goto-column column-end)
  3866. (skip-chars-forward "^|\n")
  3867. (org-table-add-rectangle-overlay p (point) face)))
  3868. (forward-line)))
  3869. (goto-char (car start-coordinates)))
  3870. (add-hook 'before-change-functions #'org-table-remove-rectangle-highlight))
  3871. (defun org-table-remove-rectangle-highlight (&rest _ignore)
  3872. "Remove the rectangle overlays."
  3873. (unless org-inhibit-highlight-removal
  3874. (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
  3875. (mapc 'delete-overlay org-table-rectangle-overlays)
  3876. (setq org-table-rectangle-overlays nil)))
  3877. (defvar-local org-table-coordinate-overlays nil
  3878. "Collects the coordinate grid overlays, so that they can be removed.")
  3879. (defun org-table-overlay-coordinates ()
  3880. "Add overlays to the table at point, to show row/column coordinates."
  3881. (interactive)
  3882. (mapc 'delete-overlay org-table-coordinate-overlays)
  3883. (setq org-table-coordinate-overlays nil)
  3884. (save-excursion
  3885. (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
  3886. (goto-char (org-table-begin))
  3887. (while (org-at-table-p)
  3888. (setq eol (point-at-eol))
  3889. (setq ov (make-overlay (point-at-bol) (1+ (point-at-bol))))
  3890. (push ov org-table-coordinate-overlays)
  3891. (setq hline (looking-at org-table-hline-regexp))
  3892. (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
  3893. (format "%4d" (setq id (1+ id)))))
  3894. (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
  3895. (when hline
  3896. (setq ic 0)
  3897. (while (re-search-forward "[+|]\\(-+\\)" eol t)
  3898. (setq beg (1+ (match-beginning 0))
  3899. ic (1+ ic)
  3900. s1 (concat "$" (int-to-string ic))
  3901. s2 (org-number-to-letters ic)
  3902. str (if (eq org-table-use-standard-references t) s2 s1))
  3903. (setq ov (make-overlay beg (+ beg (length str))))
  3904. (push ov org-table-coordinate-overlays)
  3905. (org-overlay-display ov str 'org-special-keyword 'evaporate)))
  3906. (beginning-of-line 2)))))
  3907. ;;;###autoload
  3908. (defun org-table-toggle-coordinate-overlays ()
  3909. "Toggle the display of Row/Column numbers in tables."
  3910. (interactive)
  3911. (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
  3912. (message "Tables Row/Column numbers display turned %s"
  3913. (if org-table-overlay-coordinates "on" "off"))
  3914. (if (and (org-at-table-p) org-table-overlay-coordinates)
  3915. (org-table-align))
  3916. (unless org-table-overlay-coordinates
  3917. (mapc 'delete-overlay org-table-coordinate-overlays)
  3918. (setq org-table-coordinate-overlays nil)))
  3919. ;;;###autoload
  3920. (defun org-table-toggle-formula-debugger ()
  3921. "Toggle the formula debugger in tables."
  3922. (interactive)
  3923. (setq org-table-formula-debug (not org-table-formula-debug))
  3924. (message "Formula debugging has been turned %s"
  3925. (if org-table-formula-debug "on" "off")))
  3926. ;;; The orgtbl minor mode
  3927. ;; Define a minor mode which can be used in other modes in order to
  3928. ;; integrate the org-mode table editor.
  3929. ;; This is really a hack, because the org-mode table editor uses several
  3930. ;; keys which normally belong to the major mode, for example the TAB and
  3931. ;; RET keys. Here is how it works: The minor mode defines all the keys
  3932. ;; necessary to operate the table editor, but wraps the commands into a
  3933. ;; function which tests if the cursor is currently inside a table. If that
  3934. ;; is the case, the table editor command is executed. However, when any of
  3935. ;; those keys is used outside a table, the function uses `key-binding' to
  3936. ;; look up if the key has an associated command in another currently active
  3937. ;; keymap (minor modes, major mode, global), and executes that command.
  3938. ;; There might be problems if any of the keys used by the table editor is
  3939. ;; otherwise used as a prefix key.
  3940. ;; Another challenge is that the key binding for TAB can be tab or \C-i,
  3941. ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
  3942. ;; addresses this by checking explicitly for both bindings.
  3943. ;; The optimized version (see variable `orgtbl-optimized') takes over
  3944. ;; all keys which are bound to `self-insert-command' in the *global map*.
  3945. ;; Some modes bind other commands to simple characters, for example
  3946. ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
  3947. ;; active, this binding is ignored inside tables and replaced with a
  3948. ;; modified self-insert.
  3949. (defvar orgtbl-mode-map (make-keymap)
  3950. "Keymap for `orgtbl-mode'.")
  3951. (defvar org-old-auto-fill-inhibit-regexp nil
  3952. "Local variable used by `orgtbl-mode'.")
  3953. (defconst orgtbl-line-start-regexp
  3954. "[ \t]*\\(|\\|#\\+\\(tblfm\\|orgtbl\\|tblname\\):\\)"
  3955. "Matches a line belonging to an orgtbl.")
  3956. (defconst orgtbl-extra-font-lock-keywords
  3957. (list (list (concat "^" orgtbl-line-start-regexp ".*")
  3958. 0 (quote 'org-table) 'prepend))
  3959. "Extra `font-lock-keywords' to be added when `orgtbl-mode' is active.")
  3960. ;; Install it as a minor mode.
  3961. (put 'orgtbl-mode :included t)
  3962. (put 'orgtbl-mode :menu-tag "Org Table Mode")
  3963. ;;;###autoload
  3964. (define-minor-mode orgtbl-mode
  3965. "The `org-mode' table editor as a minor mode for use in other modes."
  3966. :lighter " OrgTbl" :keymap orgtbl-mode-map
  3967. (org-load-modules-maybe)
  3968. (cond
  3969. ((derived-mode-p 'org-mode)
  3970. ;; Exit without error, in case some hook functions calls this
  3971. ;; by accident in org-mode.
  3972. (message "Orgtbl-mode is not useful in org-mode, command ignored"))
  3973. (orgtbl-mode
  3974. (and (orgtbl-setup) (defun orgtbl-setup () nil)) ;; FIXME: Yuck!?!
  3975. ;; Make sure we are first in minor-mode-map-alist
  3976. (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
  3977. ;; FIXME: maybe it should use emulation-mode-map-alists?
  3978. (and c (setq minor-mode-map-alist
  3979. (cons c (delq c minor-mode-map-alist)))))
  3980. (setq-local org-table-may-need-update t)
  3981. (org-add-hook 'before-change-functions 'org-before-change-function
  3982. nil 'local)
  3983. (setq-local org-old-auto-fill-inhibit-regexp
  3984. auto-fill-inhibit-regexp)
  3985. (setq-local auto-fill-inhibit-regexp
  3986. (if auto-fill-inhibit-regexp
  3987. (concat orgtbl-line-start-regexp "\\|"
  3988. auto-fill-inhibit-regexp)
  3989. orgtbl-line-start-regexp))
  3990. (add-to-invisibility-spec '(org-cwidth))
  3991. (when (fboundp 'font-lock-add-keywords)
  3992. (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
  3993. (org-restart-font-lock))
  3994. (easy-menu-add orgtbl-mode-menu))
  3995. (t
  3996. (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
  3997. (org-table-cleanup-narrow-column-properties)
  3998. (org-remove-from-invisibility-spec '(org-cwidth))
  3999. (remove-hook 'before-change-functions 'org-before-change-function t)
  4000. (when (fboundp 'font-lock-remove-keywords)
  4001. (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
  4002. (org-restart-font-lock))
  4003. (easy-menu-remove orgtbl-mode-menu)
  4004. (force-mode-line-update 'all))))
  4005. (defun org-table-cleanup-narrow-column-properties ()
  4006. "Remove all properties related to narrow-column invisibility."
  4007. (let ((s (point-min)))
  4008. (while (setq s (text-property-any s (point-max)
  4009. 'display org-narrow-column-arrow))
  4010. (remove-text-properties s (1+ s) '(display t)))
  4011. (setq s (point-min))
  4012. (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
  4013. (remove-text-properties s (1+ s) '(org-cwidth t)))
  4014. (setq s (point-min))
  4015. (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
  4016. (remove-text-properties s (1+ s) '(invisible t)))))
  4017. (defun orgtbl-make-binding (fun n &rest keys)
  4018. "Create a function for binding in the table minor mode.
  4019. FUN is the command to call inside a table. N is used to create a unique
  4020. command name. KEYS are keys that should be checked in for a command
  4021. to execute outside of tables."
  4022. (eval
  4023. (list 'defun
  4024. (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
  4025. '(arg)
  4026. (concat "In tables, run `" (symbol-name fun) "'.\n"
  4027. "Outside of tables, run the binding of `"
  4028. (mapconcat #'key-description keys "' or `")
  4029. "'.")
  4030. '(interactive "p")
  4031. (list 'if
  4032. '(org-at-table-p)
  4033. (list 'call-interactively (list 'quote fun))
  4034. (list 'let '(orgtbl-mode)
  4035. (list 'call-interactively
  4036. (append '(or)
  4037. (mapcar (lambda (k)
  4038. (list 'key-binding k))
  4039. keys)
  4040. '('orgtbl-error))))))))
  4041. (defun orgtbl-error ()
  4042. "Error when there is no default binding for a table key."
  4043. (interactive)
  4044. (user-error "This key has no function outside tables"))
  4045. (defun orgtbl-setup ()
  4046. "Setup orgtbl keymaps."
  4047. (let ((nfunc 0)
  4048. (bindings
  4049. '(([(meta shift left)] org-table-delete-column)
  4050. ([(meta left)] org-table-move-column-left)
  4051. ([(meta right)] org-table-move-column-right)
  4052. ([(meta shift right)] org-table-insert-column)
  4053. ([(meta shift up)] org-table-kill-row)
  4054. ([(meta shift down)] org-table-insert-row)
  4055. ([(meta up)] org-table-move-row-up)
  4056. ([(meta down)] org-table-move-row-down)
  4057. ("\C-c\C-w" org-table-cut-region)
  4058. ("\C-c\M-w" org-table-copy-region)
  4059. ("\C-c\C-y" org-table-paste-rectangle)
  4060. ("\C-c\C-w" org-table-wrap-region)
  4061. ("\C-c-" org-table-insert-hline)
  4062. ("\C-c}" org-table-toggle-coordinate-overlays)
  4063. ("\C-c{" org-table-toggle-formula-debugger)
  4064. ("\C-m" org-table-next-row)
  4065. ([(shift return)] org-table-copy-down)
  4066. ("\C-c?" org-table-field-info)
  4067. ("\C-c " org-table-blank-field)
  4068. ("\C-c+" org-table-sum)
  4069. ("\C-c=" org-table-eval-formula)
  4070. ("\C-c'" org-table-edit-formulas)
  4071. ("\C-c`" org-table-edit-field)
  4072. ("\C-c*" org-table-recalculate)
  4073. ("\C-c^" org-table-sort-lines)
  4074. ("\M-a" org-table-beginning-of-field)
  4075. ("\M-e" org-table-end-of-field)
  4076. ([(control ?#)] org-table-rotate-recalc-marks)))
  4077. elt key fun cmd)
  4078. (while (setq elt (pop bindings))
  4079. (setq nfunc (1+ nfunc))
  4080. (setq key (org-key (car elt))
  4081. fun (nth 1 elt)
  4082. cmd (orgtbl-make-binding fun nfunc key))
  4083. (org-defkey orgtbl-mode-map key cmd))
  4084. ;; Special treatment needed for TAB and RET
  4085. (org-defkey orgtbl-mode-map [(return)]
  4086. (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
  4087. (org-defkey orgtbl-mode-map "\C-m"
  4088. (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
  4089. (org-defkey orgtbl-mode-map [(tab)]
  4090. (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
  4091. (org-defkey orgtbl-mode-map "\C-i"
  4092. (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
  4093. (org-defkey orgtbl-mode-map [(shift tab)]
  4094. (orgtbl-make-binding 'org-table-previous-field 104
  4095. [(shift tab)] [(tab)] "\C-i"))
  4096. (unless (featurep 'xemacs)
  4097. (org-defkey orgtbl-mode-map [S-iso-lefttab]
  4098. (orgtbl-make-binding 'org-table-previous-field 107
  4099. [S-iso-lefttab] [backtab] [(shift tab)]
  4100. [(tab)] "\C-i")))
  4101. (org-defkey orgtbl-mode-map [backtab]
  4102. (orgtbl-make-binding 'org-table-previous-field 108
  4103. [backtab] [S-iso-lefttab] [(shift tab)]
  4104. [(tab)] "\C-i"))
  4105. (org-defkey orgtbl-mode-map "\M-\C-m"
  4106. (orgtbl-make-binding 'org-table-wrap-region 105
  4107. "\M-\C-m" [(meta return)]))
  4108. (org-defkey orgtbl-mode-map [(meta return)]
  4109. (orgtbl-make-binding 'org-table-wrap-region 106
  4110. [(meta return)] "\M-\C-m"))
  4111. (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
  4112. (org-defkey orgtbl-mode-map "\C-c|" 'orgtbl-create-or-convert-from-region)
  4113. (when orgtbl-optimized
  4114. ;; If the user wants maximum table support, we need to hijack
  4115. ;; some standard editing functions
  4116. (org-remap orgtbl-mode-map
  4117. 'self-insert-command 'orgtbl-self-insert-command
  4118. 'delete-char 'org-delete-char
  4119. 'delete-backward-char 'org-delete-backward-char)
  4120. (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
  4121. (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
  4122. '("OrgTbl"
  4123. ["Create or convert" org-table-create-or-convert-from-region
  4124. :active (not (org-at-table-p)) :keys "C-c |" ]
  4125. "--"
  4126. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
  4127. ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
  4128. ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
  4129. ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
  4130. "--"
  4131. ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
  4132. ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
  4133. ["Copy Field from Above"
  4134. org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
  4135. "--"
  4136. ("Column"
  4137. ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
  4138. ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
  4139. ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
  4140. ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
  4141. ("Row"
  4142. ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
  4143. ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
  4144. ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
  4145. ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
  4146. ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
  4147. "--"
  4148. ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
  4149. ("Rectangle"
  4150. ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
  4151. ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
  4152. ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
  4153. ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
  4154. "--"
  4155. ("Radio tables"
  4156. ["Insert table template" orgtbl-insert-radio-table
  4157. (assq major-mode orgtbl-radio-table-templates)]
  4158. ["Comment/uncomment table" orgtbl-toggle-comment t])
  4159. "--"
  4160. ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
  4161. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  4162. ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
  4163. ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
  4164. ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
  4165. ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  4166. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
  4167. ["Sum Column/Rectangle" org-table-sum
  4168. :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
  4169. ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
  4170. ["Debug Formulas"
  4171. org-table-toggle-formula-debugger :active (org-at-table-p)
  4172. :keys "C-c {"
  4173. :style toggle :selected org-table-formula-debug]
  4174. ["Show Col/Row Numbers"
  4175. org-table-toggle-coordinate-overlays :active (org-at-table-p)
  4176. :keys "C-c }"
  4177. :style toggle :selected org-table-overlay-coordinates]
  4178. "--"
  4179. ("Plot"
  4180. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  4181. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  4182. t))
  4183. (defun orgtbl-ctrl-c-ctrl-c (arg)
  4184. "If the cursor is inside a table, realign the table.
  4185. If it is a table to be sent away to a receiver, do it.
  4186. With prefix arg, also recompute table."
  4187. (interactive "P")
  4188. (let ((case-fold-search t) (pos (point)) action)
  4189. (save-excursion
  4190. (beginning-of-line 1)
  4191. (setq action (cond
  4192. ((looking-at "[ \t]*#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
  4193. ((looking-at "[ \t]*|") pos)
  4194. ((looking-at "[ \t]*#\\+tblfm:") 'recalc))))
  4195. (cond
  4196. ((integerp action)
  4197. (goto-char action)
  4198. (org-table-maybe-eval-formula)
  4199. (if arg
  4200. (call-interactively 'org-table-recalculate)
  4201. (org-table-maybe-recalculate-line))
  4202. (call-interactively 'org-table-align)
  4203. (when (orgtbl-send-table 'maybe)
  4204. (run-hooks 'orgtbl-after-send-table-hook)))
  4205. ((eq action 'recalc)
  4206. (save-excursion
  4207. (beginning-of-line 1)
  4208. (skip-chars-backward " \r\n\t")
  4209. (if (org-at-table-p)
  4210. (org-call-with-arg 'org-table-recalculate t))))
  4211. (t (let (orgtbl-mode)
  4212. (call-interactively (key-binding "\C-c\C-c")))))))
  4213. (defun orgtbl-create-or-convert-from-region (_arg)
  4214. "Create table or convert region to table, if no conflicting binding.
  4215. This installs the table binding `C-c |', but only if there is no
  4216. conflicting binding to this key outside orgtbl-mode."
  4217. (interactive "P")
  4218. (let* (orgtbl-mode (cmd (key-binding "\C-c|")))
  4219. (if cmd
  4220. (call-interactively cmd)
  4221. (call-interactively 'org-table-create-or-convert-from-region))))
  4222. (defun orgtbl-tab (arg)
  4223. "Justification and field motion for `orgtbl-mode'."
  4224. (interactive "P")
  4225. (if arg (org-table-edit-field t)
  4226. (org-table-justify-field-maybe)
  4227. (org-table-next-field)))
  4228. (defun orgtbl-ret ()
  4229. "Justification and field motion for `orgtbl-mode'."
  4230. (interactive)
  4231. (if (bobp)
  4232. (newline)
  4233. (org-table-justify-field-maybe)
  4234. (org-table-next-row)))
  4235. (defun orgtbl-self-insert-command (N)
  4236. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  4237. If the cursor is in a table looking at whitespace, the whitespace is
  4238. overwritten, and the table is not marked as requiring realignment."
  4239. (interactive "p")
  4240. (if (and (org-at-table-p)
  4241. (or
  4242. (and org-table-auto-blank-field
  4243. (member last-command
  4244. '(orgtbl-hijacker-command-100
  4245. orgtbl-hijacker-command-101
  4246. orgtbl-hijacker-command-102
  4247. orgtbl-hijacker-command-103
  4248. orgtbl-hijacker-command-104
  4249. orgtbl-hijacker-command-105
  4250. yas/expand))
  4251. (org-table-blank-field))
  4252. t)
  4253. (eq N 1)
  4254. (looking-at "[^|\n]* +|"))
  4255. (let (org-table-may-need-update)
  4256. (goto-char (1- (match-end 0)))
  4257. (org-delete-backward-char 1)
  4258. (goto-char (match-beginning 0))
  4259. (self-insert-command N))
  4260. (setq org-table-may-need-update t)
  4261. (let* (orgtbl-mode
  4262. a
  4263. (cmd (or (key-binding
  4264. (or (and (listp function-key-map)
  4265. (setq a (assoc last-input-event function-key-map))
  4266. (cdr a))
  4267. (vector last-input-event)))
  4268. 'self-insert-command)))
  4269. (call-interactively cmd)
  4270. (if (and org-self-insert-cluster-for-undo
  4271. (eq cmd 'self-insert-command))
  4272. (if (not (eq last-command 'orgtbl-self-insert-command))
  4273. (setq org-self-insert-command-undo-counter 1)
  4274. (if (>= org-self-insert-command-undo-counter 20)
  4275. (setq org-self-insert-command-undo-counter 1)
  4276. (and (> org-self-insert-command-undo-counter 0)
  4277. buffer-undo-list
  4278. (not (cadr buffer-undo-list)) ; remove nil entry
  4279. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  4280. (setq org-self-insert-command-undo-counter
  4281. (1+ org-self-insert-command-undo-counter))))))))
  4282. ;;;###autoload
  4283. (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
  4284. "Regular expression matching exponentials as produced by calc.")
  4285. (defun orgtbl-gather-send-defs ()
  4286. "Gather a plist of :name, :transform, :params for each destination before
  4287. a radio table."
  4288. (save-excursion
  4289. (goto-char (org-table-begin))
  4290. (let (rtn)
  4291. (beginning-of-line 0)
  4292. (while (looking-at "[ \t]*#\\+ORGTBL[: \t][ \t]*SEND[ \t]+\\([^ \t\r\n]+\\)[ \t]+\\([^ \t\r\n]+\\)\\([ \t]+.*\\)?")
  4293. (let ((name (org-no-properties (match-string 1)))
  4294. (transform (intern (match-string 2)))
  4295. (params (if (match-end 3)
  4296. (read (concat "(" (match-string 3) ")")))))
  4297. (push (list :name name :transform transform :params params)
  4298. rtn)
  4299. (beginning-of-line 0)))
  4300. rtn)))
  4301. (defun orgtbl-send-replace-tbl (name txt)
  4302. "Find and replace table NAME with TXT."
  4303. (save-excursion
  4304. (goto-char (point-min))
  4305. (unless (re-search-forward
  4306. (concat "BEGIN +RECEIVE +ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
  4307. (user-error "Don't know where to insert translated table"))
  4308. (let ((beg (line-beginning-position 2)))
  4309. (unless (re-search-forward
  4310. (concat "END +RECEIVE +ORGTBL +" name) nil t)
  4311. (user-error "Cannot find end of insertion region"))
  4312. (beginning-of-line)
  4313. (delete-region beg (point)))
  4314. (insert txt "\n")))
  4315. ;;;###autoload
  4316. (defun org-table-to-lisp (&optional txt)
  4317. "Convert the table at point to a Lisp structure.
  4318. The structure will be a list. Each item is either the symbol `hline'
  4319. for a horizontal separator line, or a list of field values as strings.
  4320. The table is taken from the parameter TXT, or from the buffer at point."
  4321. (unless (or txt (org-at-table-p)) (user-error "No table at point"))
  4322. (let ((txt (or txt
  4323. (buffer-substring-no-properties (org-table-begin)
  4324. (org-table-end)))))
  4325. (mapcar (lambda (x)
  4326. (if (string-match org-table-hline-regexp x) 'hline
  4327. (org-split-string (org-trim x) "\\s-*|\\s-*")))
  4328. (org-split-string txt "[ \t]*\n[ \t]*"))))
  4329. (defun orgtbl-send-table (&optional maybe)
  4330. "Send a transformed version of table at point to the receiver position.
  4331. With argument MAYBE, fail quietly if no transformation is defined
  4332. for this table."
  4333. (interactive)
  4334. (catch 'exit
  4335. (unless (org-at-table-p) (user-error "Not at a table"))
  4336. ;; when non-interactive, we assume align has just happened.
  4337. (when (org-called-interactively-p 'any) (org-table-align))
  4338. (let ((dests (orgtbl-gather-send-defs))
  4339. (table (org-table-to-lisp
  4340. (buffer-substring-no-properties (org-table-begin)
  4341. (org-table-end))))
  4342. (ntbl 0))
  4343. (unless dests
  4344. (if maybe (throw 'exit nil)
  4345. (user-error "Don't know how to transform this table")))
  4346. (dolist (dest dests)
  4347. (let ((name (plist-get dest :name))
  4348. (transform (plist-get dest :transform))
  4349. (params (plist-get dest :params)))
  4350. (unless (fboundp transform)
  4351. (user-error "No such transformation function %s" transform))
  4352. (orgtbl-send-replace-tbl name (funcall transform table params)))
  4353. (incf ntbl))
  4354. (message "Table converted and installed at %d receiver location%s"
  4355. ntbl (if (> ntbl 1) "s" ""))
  4356. (and (> ntbl 0) ntbl))))
  4357. (defun org-remove-by-index (list indices &optional i0)
  4358. "Remove the elements in LIST with indices in INDICES.
  4359. First element has index 0, or I0 if given."
  4360. (if (not indices)
  4361. list
  4362. (if (integerp indices) (setq indices (list indices)))
  4363. (setq i0 (1- (or i0 0)))
  4364. (delq :rm (mapcar (lambda (x)
  4365. (setq i0 (1+ i0))
  4366. (if (memq i0 indices) :rm x))
  4367. list))))
  4368. (defun orgtbl-toggle-comment ()
  4369. "Comment or uncomment the orgtbl at point."
  4370. (interactive)
  4371. (let* ((case-fold-search t)
  4372. (re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
  4373. (re2 (concat "^" orgtbl-line-start-regexp))
  4374. (commented (save-excursion (beginning-of-line 1)
  4375. (cond ((looking-at re1) t)
  4376. ((looking-at re2) nil)
  4377. (t (user-error "Not at an org table")))))
  4378. (re (if commented re1 re2))
  4379. beg end)
  4380. (save-excursion
  4381. (beginning-of-line 1)
  4382. (while (looking-at re) (beginning-of-line 0))
  4383. (beginning-of-line 2)
  4384. (setq beg (point))
  4385. (while (looking-at re) (beginning-of-line 2))
  4386. (setq end (point)))
  4387. (comment-region beg end (if commented '(4) nil))))
  4388. (defun orgtbl-insert-radio-table ()
  4389. "Insert a radio table template appropriate for this major mode."
  4390. (interactive)
  4391. (let* ((e (assq major-mode orgtbl-radio-table-templates))
  4392. (txt (nth 1 e))
  4393. name pos)
  4394. (unless e (user-error "No radio table setup defined for %s" major-mode))
  4395. (setq name (read-string "Table name: "))
  4396. (while (string-match "%n" txt)
  4397. (setq txt (replace-match name t t txt)))
  4398. (or (bolp) (insert "\n"))
  4399. (setq pos (point))
  4400. (insert txt)
  4401. (goto-char pos)))
  4402. ;;;###autoload
  4403. (defun orgtbl-to-generic (table params)
  4404. "Convert the orgtbl-mode TABLE to some other format.
  4405. This generic routine can be used for many standard cases.
  4406. TABLE is a list, each entry either the symbol `hline' for
  4407. a horizontal separator line, or a list of fields for that
  4408. line. PARAMS is a property list of parameters that can
  4409. influence the conversion.
  4410. Valid parameters are:
  4411. :backend, :raw
  4412. Export back-end used as a basis to transcode elements of the
  4413. table, when no specific parameter applies to it. It is also
  4414. used to translate cells contents. You can prevent this by
  4415. setting :raw property to a non-nil value.
  4416. :splice
  4417. When non-nil, only convert rows, not the table itself. This is
  4418. equivalent to setting to the empty string both :tstart
  4419. and :tend, which see.
  4420. :skip
  4421. When set to an integer N, skip the first N lines of the table.
  4422. Horizontal separation lines do count for this parameter!
  4423. :skipcols
  4424. List of columns that should be skipped. If the table has
  4425. a column with calculation marks, that column is automatically
  4426. discarded beforehand.
  4427. :hline
  4428. String to be inserted on horizontal separation lines. May be
  4429. nil to ignore these lines altogether.
  4430. :sep
  4431. Separator between two fields, as a string.
  4432. Each in the following group may be either a string or a function
  4433. of no arguments returning a string:
  4434. :tstart, :tend
  4435. Strings to start and end the table. Ignored when :splice is t.
  4436. :lstart, :lend
  4437. Strings to start and end a new table line.
  4438. :llstart, :llend
  4439. Strings to start and end the last table line. Default,
  4440. respectively, to :lstart and :lend.
  4441. Each in the following group may be a string or a function of one
  4442. argument (either the cells in the current row, as a list of
  4443. strings, or the current cell) returning a string:
  4444. :lfmt
  4445. Format string for an entire row, with enough %s to capture all
  4446. fields. When non-nil, :lstart, :lend, and :sep are ignored.
  4447. :llfmt
  4448. Format for the entire last line, defaults to :lfmt.
  4449. :fmt
  4450. A format to be used to wrap the field, should contain %s for
  4451. the original field value. For example, to wrap everything in
  4452. dollars, you could use :fmt \"$%s$\". This may also be
  4453. a property list with column numbers and format strings, or
  4454. functions, e.g.,
  4455. \(:fmt (2 \"$%s$\" 4 (lambda (c) (format \"$%s$\" c))))
  4456. :hlstart :hllstart :hlend :hllend :hsep :hlfmt :hllfmt :hfmt
  4457. Same as above, specific for the header lines in the table.
  4458. All lines before the first hline are treated as header. If
  4459. any of these is not present, the data line value is used.
  4460. This may be either a string or a function of two arguments:
  4461. :efmt
  4462. Use this format to print numbers with exponential. The format
  4463. should have %s twice for inserting mantissa and exponent, for
  4464. example \"%s\\\\times10^{%s}\". This may also be a property
  4465. list with column numbers and format strings or functions.
  4466. :fmt will still be applied after :efmt."
  4467. ;; Make sure `org-export-create-backend' is available.
  4468. (require 'ox)
  4469. (let* ((backend (plist-get params :backend))
  4470. (custom-backend
  4471. ;; Build a custom back-end according to PARAMS. Before
  4472. ;; defining a translator, check if there is anything to do.
  4473. ;; When there isn't, let BACKEND handle the element.
  4474. (org-export-create-backend
  4475. :parent (or backend 'org)
  4476. :transcoders
  4477. `((table . ,(org-table--to-generic-table params))
  4478. (table-row . ,(org-table--to-generic-row params))
  4479. (table-cell . ,(org-table--to-generic-cell params))
  4480. ;; Macros are not going to be expanded. However, no
  4481. ;; regular back-end has a transcoder for them. We
  4482. ;; provide one so they are not ignored, but displayed
  4483. ;; as-is instead.
  4484. (macro . (lambda (m c i) (org-element-macro-interpreter m nil))))))
  4485. data info)
  4486. ;; Store TABLE as Org syntax in DATA. Tolerate non-string cells.
  4487. ;; Initialize communication channel in INFO.
  4488. (with-temp-buffer
  4489. (let ((org-inhibit-startup t)) (org-mode))
  4490. (let ((standard-output (current-buffer)))
  4491. (dolist (e table)
  4492. (cond ((eq e 'hline) (princ "|--\n"))
  4493. ((consp e)
  4494. (princ "| ") (dolist (c e) (princ c) (princ " |"))
  4495. (princ "\n")))))
  4496. (setq data
  4497. (org-element-map (org-element-parse-buffer) 'table
  4498. #'identity nil t))
  4499. (setq info (org-export-get-environment backend nil params)))
  4500. (when (and backend (symbolp backend) (not (org-export-get-backend backend)))
  4501. (user-error "Unknown :backend value"))
  4502. (when (or (not backend) (plist-get info :raw)) (require 'ox-org))
  4503. ;; Handle :skip parameter.
  4504. (let ((skip (plist-get info :skip)))
  4505. (when skip
  4506. (unless (wholenump skip) (user-error "Wrong :skip value"))
  4507. (let ((n 0))
  4508. (org-element-map data 'table-row
  4509. (lambda (row)
  4510. (if (>= n skip) t
  4511. (org-element-extract-element row)
  4512. (incf n)
  4513. nil))
  4514. nil t))))
  4515. ;; Handle :skipcols parameter.
  4516. (let ((skipcols (plist-get info :skipcols)))
  4517. (when skipcols
  4518. (unless (consp skipcols) (user-error "Wrong :skipcols value"))
  4519. (org-element-map data 'table
  4520. (lambda (table)
  4521. (let ((specialp (org-export-table-has-special-column-p table)))
  4522. (dolist (row (org-element-contents table))
  4523. (when (eq (org-element-property :type row) 'standard)
  4524. (let ((c 1))
  4525. (dolist (cell (nthcdr (if specialp 1 0)
  4526. (org-element-contents row)))
  4527. (when (memq c skipcols)
  4528. (org-element-extract-element cell))
  4529. (incf c))))))))))
  4530. ;; Since we are going to export using a low-level mechanism,
  4531. ;; ignore special column and special rows manually.
  4532. (let ((special? (org-export-table-has-special-column-p data))
  4533. ignore)
  4534. (org-element-map data (if special? '(table-cell table-row) 'table-row)
  4535. (lambda (datum)
  4536. (when (if (eq (org-element-type datum) 'table-row)
  4537. (org-export-table-row-is-special-p datum nil)
  4538. (org-export-first-sibling-p datum nil))
  4539. (push datum ignore))))
  4540. (setq info (plist-put info :ignore-list ignore)))
  4541. ;; We use a low-level mechanism to export DATA so as to skip all
  4542. ;; usual pre-processing and post-processing, i.e., hooks, filters,
  4543. ;; Babel code evaluation, include keywords and macro expansion,
  4544. ;; and filters.
  4545. (let ((output (org-export-data-with-backend data custom-backend info)))
  4546. ;; Remove final newline.
  4547. (if (org-string-nw-p output) (substring-no-properties output 0 -1) ""))))
  4548. (defun org-table--generic-apply (value name &optional with-cons &rest args)
  4549. (cond ((null value) nil)
  4550. ((functionp value) `(funcall ',value ,@args))
  4551. ((stringp value)
  4552. (cond ((consp (car args)) `(apply #'format ,value ,@args))
  4553. (args `(format ,value ,@args))
  4554. (t value)))
  4555. ((and with-cons (consp value))
  4556. `(let ((val (cadr (memq column ',value))))
  4557. (cond ((null val) contents)
  4558. ((stringp val) (format val ,@args))
  4559. ((functionp val) (funcall val ,@args))
  4560. (t (user-error "Wrong %s value" ,name)))))
  4561. (t (user-error "Wrong %s value" name))))
  4562. (defun org-table--to-generic-table (params)
  4563. "Return custom table transcoder according to PARAMS.
  4564. PARAMS is a plist. See `orgtbl-to-generic' for more
  4565. information."
  4566. (let ((backend (plist-get params :backend))
  4567. (splice (plist-get params :splice))
  4568. (tstart (plist-get params :tstart))
  4569. (tend (plist-get params :tend)))
  4570. `(lambda (table contents info)
  4571. (concat
  4572. ,(and tstart (not splice)
  4573. `(concat ,(org-table--generic-apply tstart ":tstart") "\n"))
  4574. ,(if (or (not backend) tstart tend splice) 'contents
  4575. `(org-export-with-backend ',backend table contents info))
  4576. ,(org-table--generic-apply (and (not splice) tend) ":tend")))))
  4577. (defun org-table--to-generic-row (params)
  4578. "Return custom table row transcoder according to PARAMS.
  4579. PARAMS is a plist. See `orgtbl-to-generic' for more
  4580. information."
  4581. (let* ((backend (plist-get params :backend))
  4582. (lstart (plist-get params :lstart))
  4583. (llstart (plist-get params :llstart))
  4584. (hlstart (plist-get params :hlstart))
  4585. (hllstart (plist-get params :hllstart))
  4586. (lend (plist-get params :lend))
  4587. (llend (plist-get params :llend))
  4588. (hlend (plist-get params :hlend))
  4589. (hllend (plist-get params :hllend))
  4590. (lfmt (plist-get params :lfmt))
  4591. (llfmt (plist-get params :llfmt))
  4592. (hlfmt (plist-get params :hlfmt))
  4593. (hllfmt (plist-get params :hllfmt)))
  4594. `(lambda (row contents info)
  4595. (if (eq (org-element-property :type row) 'rule)
  4596. ,(cond
  4597. ((plist-member params :hline)
  4598. (org-table--generic-apply (plist-get params :hline) ":hline"))
  4599. (backend `(org-export-with-backend ',backend row nil info)))
  4600. (let ((headerp (org-export-table-row-in-header-p row info))
  4601. (lastp (not (org-export-get-next-element row info)))
  4602. (last-header-p (org-export-table-row-ends-header-p row info)))
  4603. (when contents
  4604. ;; Check if we can apply `:lfmt', `:llfmt', `:hlfmt', or
  4605. ;; `:hllfmt' to CONTENTS. Otherwise, fallback on
  4606. ;; `:lstart', `:lend' and their relatives.
  4607. ,(let ((cells
  4608. '(org-element-map row 'table-cell
  4609. (lambda (cell)
  4610. ;; Export all cells, without separators.
  4611. ;;
  4612. ;; Use `org-export-data-with-backend'
  4613. ;; instead of `org-export-data' to eschew
  4614. ;; cached values, which
  4615. ;; ignore :orgtbl-ignore-sep parameter.
  4616. (org-export-data-with-backend
  4617. cell
  4618. (plist-get info :back-end)
  4619. (org-combine-plists info '(:orgtbl-ignore-sep t))))
  4620. info)))
  4621. `(cond
  4622. ,(and hllfmt
  4623. `(last-header-p ,(org-table--generic-apply
  4624. hllfmt ":hllfmt" nil cells)))
  4625. ,(and hlfmt
  4626. `(headerp ,(org-table--generic-apply
  4627. hlfmt ":hlfmt" nil cells)))
  4628. ,(and llfmt
  4629. `(lastp ,(org-table--generic-apply
  4630. llfmt ":llfmt" nil cells)))
  4631. (t
  4632. ,(if lfmt (org-table--generic-apply lfmt ":lfmt" nil cells)
  4633. `(concat
  4634. (cond
  4635. ,(and
  4636. (or hllstart hllend)
  4637. `(last-header-p
  4638. (concat
  4639. ,(org-table--generic-apply hllstart ":hllstart")
  4640. contents
  4641. ,(org-table--generic-apply hllend ":hllend"))))
  4642. ,(and
  4643. (or hlstart hlend)
  4644. `(headerp
  4645. (concat
  4646. ,(org-table--generic-apply hlstart ":hlstart")
  4647. contents
  4648. ,(org-table--generic-apply hlend ":hlend"))))
  4649. ,(and
  4650. (or llstart llend)
  4651. `(lastp
  4652. (concat
  4653. ,(org-table--generic-apply llstart ":llstart")
  4654. contents
  4655. ,(org-table--generic-apply llend ":llend"))))
  4656. (t
  4657. ,(cond
  4658. ((or lstart lend)
  4659. `(concat
  4660. ,(org-table--generic-apply lstart ":lstart")
  4661. contents
  4662. ,(org-table--generic-apply lend ":lend")))
  4663. (backend
  4664. `(org-export-with-backend
  4665. ',backend row contents info))
  4666. (t 'contents)))))))))))))))
  4667. (defun org-table--to-generic-cell (params)
  4668. "Return custom table cell transcoder according to PARAMS.
  4669. PARAMS is a plist. See `orgtbl-to-generic' for more
  4670. information."
  4671. (let* ((backend (plist-get params :backend))
  4672. (efmt (plist-get params :efmt))
  4673. (fmt (plist-get params :fmt))
  4674. (hfmt (plist-get params :hfmt))
  4675. (sep (plist-get params :sep))
  4676. (hsep (plist-get params :hsep)))
  4677. `(lambda (cell contents info)
  4678. (let ((headerp (org-export-table-row-in-header-p
  4679. (org-export-get-parent-element cell) info))
  4680. (column (1+ (cdr (org-export-table-cell-address cell info)))))
  4681. ;; Make sure that contents are exported as Org data when :raw
  4682. ;; parameter is non-nil.
  4683. ,(when (and backend (plist-get params :raw))
  4684. `(setq contents
  4685. ;; Since we don't know what are the pseudo object
  4686. ;; types defined in backend, we cannot pass them to
  4687. ;; `org-element-interpret-data'. As a consequence,
  4688. ;; they will be treated as pseudo elements, and
  4689. ;; will have newlines appended instead of spaces.
  4690. ;; Therefore, we must make sure :post-blank value
  4691. ;; is really turned into spaces.
  4692. (replace-regexp-in-string
  4693. "\n" " "
  4694. (org-trim
  4695. (org-element-interpret-data
  4696. (org-element-contents cell))))))
  4697. (when contents
  4698. ;; Check if we can apply `:efmt' on CONTENTS.
  4699. ,(when efmt
  4700. `(when (string-match orgtbl-exp-regexp contents)
  4701. (let ((mantissa (match-string 1 contents))
  4702. (exponent (match-string 2 contents)))
  4703. (setq contents ,(org-table--generic-apply
  4704. efmt ":efmt" t 'mantissa 'exponent)))))
  4705. ;; Check if we can apply FMT (or HFMT) on CONTENTS.
  4706. (cond
  4707. ,(and hfmt `(headerp (setq contents ,(org-table--generic-apply
  4708. hfmt ":hfmt" t 'contents))))
  4709. ,(and fmt `(t (setq contents ,(org-table--generic-apply
  4710. fmt ":fmt" t 'contents))))))
  4711. ;; If a separator is provided, use it instead of BACKEND's.
  4712. ;; Separators are ignored when LFMT (or equivalent) is
  4713. ;; provided.
  4714. ,(cond
  4715. ((or hsep sep)
  4716. `(if (or ,(and (not sep) '(not headerp))
  4717. (plist-get info :orgtbl-ignore-sep)
  4718. (not (org-export-get-next-element cell info)))
  4719. ,(if (not backend) 'contents
  4720. `(org-export-with-backend ',backend cell contents info))
  4721. (concat contents
  4722. ,(if (and sep hsep) `(if headerp ,hsep ,sep)
  4723. (or hsep sep)))))
  4724. (backend `(org-export-with-backend ',backend cell contents info))
  4725. (t 'contents))))))
  4726. ;;;###autoload
  4727. (defun orgtbl-to-tsv (table params)
  4728. "Convert the orgtbl-mode table to TAB separated material."
  4729. (orgtbl-to-generic table (org-combine-plists '(:sep "\t") params)))
  4730. ;;;###autoload
  4731. (defun orgtbl-to-csv (table params)
  4732. "Convert the orgtbl-mode table to CSV material.
  4733. This does take care of the proper quoting of fields with comma or quotes."
  4734. (orgtbl-to-generic table
  4735. (org-combine-plists '(:sep "," :fmt org-quote-csv-field)
  4736. params)))
  4737. ;;;###autoload
  4738. (defun orgtbl-to-latex (table params)
  4739. "Convert the orgtbl-mode TABLE to LaTeX.
  4740. TABLE is a list, each entry either the symbol `hline' for
  4741. a horizontal separator line, or a list of fields for that line.
  4742. PARAMS is a property list of parameters that can influence the
  4743. conversion. All parameters from `orgtbl-to-generic' are
  4744. supported. It is also possible to use the following ones:
  4745. :booktabs
  4746. When non-nil, use formal \"booktabs\" style.
  4747. :environment
  4748. Specify environment to use, as a string. If you use
  4749. \"longtable\", you may also want to specify :language property,
  4750. as a string, to get proper continuation strings."
  4751. (require 'ox-latex)
  4752. (orgtbl-to-generic
  4753. table
  4754. (org-combine-plists
  4755. ;; Provide sane default values.
  4756. (list :backend 'latex
  4757. :latex-default-table-mode 'table
  4758. :latex-tables-centered nil
  4759. :latex-tables-booktabs (plist-get params :booktabs)
  4760. :latex-table-scientific-notation nil
  4761. :latex-default-table-environment
  4762. (or (plist-get params :environment) "tabular"))
  4763. params)))
  4764. ;;;###autoload
  4765. (defun orgtbl-to-html (table params)
  4766. "Convert the orgtbl-mode TABLE to HTML.
  4767. TABLE is a list, each entry either the symbol `hline' for
  4768. a horizontal separator line, or a list of fields for that line.
  4769. PARAMS is a property list of parameters that can influence the
  4770. conversion. All parameters from `orgtbl-to-generic' are
  4771. supported. It is also possible to use the following one:
  4772. :attributes
  4773. Attributes and values, as a plist, which will be used in
  4774. <table> tag."
  4775. (require 'ox-html)
  4776. (orgtbl-to-generic
  4777. table
  4778. (org-combine-plists
  4779. ;; Provide sane default values.
  4780. (list :backend 'html
  4781. :html-table-data-tags '("<td%s>" . "</td>")
  4782. :html-table-use-header-tags-for-first-column nil
  4783. :html-table-align-individual-fields t
  4784. :html-table-row-tags '("<tr>" . "</tr>")
  4785. :html-table-attributes
  4786. (if (plist-member params :attributes)
  4787. (plist-get params :attributes)
  4788. '(:border "2" :cellspacing "0" :cellpadding "6" :rules "groups"
  4789. :frame "hsides")))
  4790. params)))
  4791. ;;;###autoload
  4792. (defun orgtbl-to-texinfo (table params)
  4793. "Convert the orgtbl-mode TABLE to Texinfo.
  4794. TABLE is a list, each entry either the symbol `hline' for
  4795. a horizontal separator line, or a list of fields for that line.
  4796. PARAMS is a property list of parameters that can influence the
  4797. conversion. All parameters from `orgtbl-to-generic' are
  4798. supported. It is also possible to use the following one:
  4799. :columns
  4800. Column widths, as a string. When providing column fractions,
  4801. \"@columnfractions\" command can be omitted."
  4802. (require 'ox-texinfo)
  4803. (let ((output
  4804. (orgtbl-to-generic
  4805. table
  4806. (org-combine-plists
  4807. (list :backend 'texinfo
  4808. :texinfo-tables-verbatim nil
  4809. :texinfo-table-scientific-notation nil)
  4810. params)))
  4811. (columns (let ((w (plist-get params :columns)))
  4812. (cond ((not w) nil)
  4813. ((org-string-match-p "{\\|@columnfractions " w) w)
  4814. (t (concat "@columnfractions " w))))))
  4815. (if (not columns) output
  4816. (replace-regexp-in-string
  4817. "@multitable \\(.*\\)" columns output t nil 1))))
  4818. ;;;###autoload
  4819. (defun orgtbl-to-orgtbl (table params)
  4820. "Convert the orgtbl-mode TABLE into another orgtbl-mode table.
  4821. TABLE is a list, each entry either the symbol `hline' for
  4822. a horizontal separator line, or a list of fields for that line.
  4823. PARAMS is a property list of parameters that can influence the
  4824. conversion. All parameters from `orgtbl-to-generic' are
  4825. supported.
  4826. Useful when slicing one table into many. The :hline, :sep,
  4827. :lstart, and :lend provide orgtbl framing. :tstart and :tend can
  4828. be set to provide ORGTBL directives for the generated table."
  4829. (require 'ox-org)
  4830. (orgtbl-to-generic table (org-combine-plists params (list :backend 'org))))
  4831. (defun orgtbl-to-table.el (table params)
  4832. "Convert the orgtbl-mode TABLE into a table.el table.
  4833. TABLE is a list, each entry either the symbol `hline' for
  4834. a horizontal separator line, or a list of fields for that line.
  4835. PARAMS is a property list of parameters that can influence the
  4836. conversion. All parameters from `orgtbl-to-generic' are
  4837. supported."
  4838. (with-temp-buffer
  4839. (insert (orgtbl-to-orgtbl table params))
  4840. (org-table-align)
  4841. (replace-regexp-in-string
  4842. "-|" "-+"
  4843. (replace-regexp-in-string "|-" "+-" (buffer-substring 1 (buffer-size))))))
  4844. (defun orgtbl-to-unicode (table params)
  4845. "Convert the orgtbl-mode TABLE into a table with unicode characters.
  4846. TABLE is a list, each entry either the symbol `hline' for
  4847. a horizontal separator line, or a list of fields for that line.
  4848. PARAMS is a property list of parameters that can influence the
  4849. conversion. All parameters from `orgtbl-to-generic' are
  4850. supported. It is also possible to use the following ones:
  4851. :ascii-art
  4852. When non-nil, use \"ascii-art-to-unicode\" package to translate
  4853. the table. You can download it here:
  4854. http://gnuvola.org/software/j/aa2u/ascii-art-to-unicode.el.
  4855. :narrow
  4856. When non-nil, narrow columns width than provided width cookie,
  4857. using \"=>\" as an ellipsis, just like in an Org mode buffer."
  4858. (require 'ox-ascii)
  4859. (orgtbl-to-generic
  4860. table
  4861. (org-combine-plists
  4862. (list :backend 'ascii
  4863. :ascii-charset 'utf-8
  4864. :ascii-table-widen-columns (not (plist-get params :narrow))
  4865. :ascii-table-use-ascii-art (plist-get params :ascii-art))
  4866. params)))
  4867. ;; Put the cursor in a column containing numerical values
  4868. ;; of an Org-Mode table,
  4869. ;; type C-c " a
  4870. ;; A new column is added with a bar plot.
  4871. ;; When the table is refreshed (C-u C-c *),
  4872. ;; the plot is updated to reflect the new values.
  4873. (defun orgtbl-ascii-draw (value min max &optional width characters)
  4874. "Draw an ascii bar in a table.
  4875. VALUE is a the value to plot, the width of the bar to draw. A
  4876. value equal to MIN will be displayed as empty (zero width bar).
  4877. A value equal to MAX will draw a bar filling all the WIDTH.
  4878. WIDTH is the expected width in characters of the column.
  4879. CHARACTERS is a string that will compose the bar, with shades of
  4880. grey from pure white to pure black. It defaults to a 10
  4881. characters string of regular ascii characters."
  4882. (let* ((characters (or characters " .:;c!lhVHW"))
  4883. (width (or width 12))
  4884. (value (if (numberp value) value (string-to-number value)))
  4885. (value (* (/ (- (+ value 0.0) min) (- max min)) width)))
  4886. (cond
  4887. ((< value 0) "too small")
  4888. ((> value width) "too large")
  4889. (t
  4890. (let ((len (1- (length characters))))
  4891. (concat
  4892. (make-string (floor value) (elt characters len))
  4893. (string (elt characters
  4894. (floor (* (- value (floor value)) len))))))))))
  4895. ;;;###autoload
  4896. (defun orgtbl-ascii-plot (&optional ask)
  4897. "Draw an ascii bar plot in a column.
  4898. With cursor in a column containing numerical values, this
  4899. function will draw a plot in a new column.
  4900. ASK, if given, is a numeric prefix to override the default 12
  4901. characters width of the plot. ASK may also be the
  4902. \\[universal-argument] prefix, which will prompt for the width."
  4903. (interactive "P")
  4904. (let ((col (org-table-current-column))
  4905. (min 1e999) ; 1e999 will be converted to infinity
  4906. (max -1e999) ; which is the desired result
  4907. (table (org-table-to-lisp))
  4908. (length
  4909. (cond ((consp ask)
  4910. (read-number "Length of column " 12))
  4911. ((numberp ask) ask)
  4912. (t 12))))
  4913. ;; Skip any hline a the top of table.
  4914. (while (eq (car table) 'hline) (setq table (cdr table)))
  4915. ;; Skip table header if any.
  4916. (dolist (x (or (cdr (memq 'hline table)) table))
  4917. (when (consp x)
  4918. (setq x (nth (1- col) x))
  4919. (when (string-match
  4920. "^[-+]?\\([0-9]*[.]\\)?[0-9]*\\([eE][+-]?[0-9]+\\)?$"
  4921. x)
  4922. (setq x (string-to-number x))
  4923. (when (> min x) (setq min x))
  4924. (when (< max x) (setq max x)))))
  4925. (org-table-insert-column)
  4926. (org-table-move-column-right)
  4927. (org-table-store-formulas
  4928. (cons
  4929. (cons
  4930. (number-to-string (1+ col))
  4931. (format "'(%s $%s %s %s %s)"
  4932. "orgtbl-ascii-draw" col min max length))
  4933. (org-table-get-stored-formulas)))
  4934. (org-table-recalculate t)))
  4935. ;; Example of extension: unicode characters
  4936. ;; Here are two examples of different styles.
  4937. ;; Unicode block characters are used to give a smooth effect.
  4938. ;; See http://en.wikipedia.org/wiki/Block_Elements
  4939. ;; Use one of those drawing functions
  4940. ;; - orgtbl-ascii-draw (the default ascii)
  4941. ;; - orgtbl-uc-draw-grid (unicode with a grid effect)
  4942. ;; - orgtbl-uc-draw-cont (smooth unicode)
  4943. ;; This is best viewed with the "DejaVu Sans Mono" font
  4944. ;; (use M-x set-default-font).
  4945. (defun orgtbl-uc-draw-grid (value min max &optional width)
  4946. "Draw a bar in a table using block unicode characters.
  4947. It is a variant of orgtbl-ascii-draw with Unicode block
  4948. characters, for a smooth display. Bars appear as grids (to the
  4949. extent the font allows)."
  4950. ;; http://en.wikipedia.org/wiki/Block_Elements
  4951. ;; best viewed with the "DejaVu Sans Mono" font.
  4952. (orgtbl-ascii-draw value min max width
  4953. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589"))
  4954. (defun orgtbl-uc-draw-cont (value min max &optional width)
  4955. "Draw a bar in a table using block unicode characters.
  4956. It is a variant of orgtbl-ascii-draw with Unicode block
  4957. characters, for a smooth display. Bars are solid (to the extent
  4958. the font allows)."
  4959. (orgtbl-ascii-draw value min max width
  4960. " \u258F\u258E\u258D\u258C\u258B\u258A\u2589\u2588"))
  4961. (defun org-table-get-remote-range (name-or-id form)
  4962. "Get a field value or a list of values in a range from table at ID.
  4963. NAME-OR-ID may be the name of a table in the current file as set
  4964. by a \"#+NAME:\" directive. The first table following this line
  4965. will then be used. Alternatively, it may be an ID referring to
  4966. any entry, also in a different file. In this case, the first
  4967. table in that entry will be referenced.
  4968. FORM is a field or range descriptor like \"@2$3\" or \"B3\" or
  4969. \"@I$2..@II$2\". All the references must be absolute, not relative.
  4970. The return value is either a single string for a single field, or a
  4971. list of the fields in the rectangle."
  4972. (save-match-data
  4973. (let ((case-fold-search t) (id-loc nil)
  4974. ;; Protect a bunch of variables from being overwritten by
  4975. ;; the context of the remote table.
  4976. org-table-column-names org-table-column-name-regexp
  4977. org-table-local-parameters org-table-named-field-locations
  4978. org-table-current-line-types
  4979. org-table-current-begin-pos org-table-dlines
  4980. org-table-current-ncol
  4981. org-table-hlines org-table-last-alignment
  4982. org-table-last-column-widths org-table-last-alignment
  4983. org-table-last-column-widths
  4984. buffer loc)
  4985. (setq form (org-table-convert-refs-to-rc form))
  4986. (org-with-wide-buffer
  4987. (goto-char (point-min))
  4988. (if (re-search-forward
  4989. (concat "^[ \t]*#\\+\\(tbl\\)?name:[ \t]*"
  4990. (regexp-quote name-or-id) "[ \t]*$")
  4991. nil t)
  4992. (setq buffer (current-buffer) loc (match-beginning 0))
  4993. (setq id-loc (org-id-find name-or-id 'marker))
  4994. (unless (and id-loc (markerp id-loc))
  4995. (user-error "Can't find remote table \"%s\"" name-or-id))
  4996. (setq buffer (marker-buffer id-loc)
  4997. loc (marker-position id-loc))
  4998. (move-marker id-loc nil))
  4999. (with-current-buffer buffer
  5000. (org-with-wide-buffer
  5001. (goto-char loc)
  5002. (forward-char 1)
  5003. (unless (and (re-search-forward "^\\(\\*+ \\)\\|^[ \t]*|" nil t)
  5004. (not (match-beginning 1)))
  5005. (user-error "Cannot find a table at NAME or ID %s" name-or-id))
  5006. (org-table-analyze)
  5007. (setq form (org-table-formula-substitute-names
  5008. (org-table-formula-handle-first/last-rc form)))
  5009. (if (and (string-match org-table-range-regexp form)
  5010. (> (length (match-string 0 form)) 1))
  5011. (org-table-get-range
  5012. (match-string 0 form) org-table-current-begin-pos 1)
  5013. form)))))))
  5014. (defun org-table-remote-reference-indirection (form)
  5015. "Return formula with table remote references substituted by indirection.
  5016. For example \"remote($1, @>$2)\" => \"remote(year_2013, @>$1)\".
  5017. This indirection works only with the format @ROW$COLUMN. The
  5018. format \"B3\" is not supported because it can not be
  5019. distinguished from a plain table name or ID."
  5020. (let ((regexp
  5021. ;; Same as in `org-table-eval-formula'.
  5022. (concat "\\<remote([ \t]*\\("
  5023. ;; Allow "$1", "@<", "$-1", "@<<$1" etc.
  5024. "[@$][^ \t,]+"
  5025. "\\)[ \t]*,[ \t]*\\([^\n)]+\\))")))
  5026. (replace-regexp-in-string
  5027. regexp
  5028. (lambda (m)
  5029. (save-match-data
  5030. (let ((eq (org-table-formula-handle-first/last-rc (match-string 1 m))))
  5031. (org-table-get-range
  5032. (if (org-string-match-p "\\`\\$[0-9]+\\'" eq)
  5033. (concat "@0" eq)
  5034. eq)))))
  5035. form t t 1)))
  5036. (defmacro org-define-lookup-function (mode)
  5037. (let ((mode-str (symbol-name mode))
  5038. (first-p (equal mode 'first))
  5039. (all-p (equal mode 'all)))
  5040. (let ((plural-str (if all-p "s" "")))
  5041. `(defun ,(intern (format "org-lookup-%s" mode-str)) (val s-list r-list &optional predicate)
  5042. ,(format "Find %s occurrence%s of VAL in S-LIST; return corresponding element%s of R-LIST.
  5043. If R-LIST is nil, return matching element%s of S-LIST.
  5044. If PREDICATE is not nil, use it instead of `equal' to match VAL.
  5045. Matching is done by (PREDICATE VAL S), where S is an element of S-LIST.
  5046. This function is generated by a call to the macro `org-define-lookup-function'."
  5047. mode-str plural-str plural-str plural-str)
  5048. (let ,(let ((lvars '((p (or predicate 'equal))
  5049. (sl s-list)
  5050. (rl (or r-list s-list))
  5051. (ret nil))))
  5052. (if first-p (cons '(match-p nil) lvars) lvars))
  5053. (while ,(if first-p '(and (not match-p) sl) 'sl)
  5054. (when (funcall p val (car sl))
  5055. ,(when first-p '(setq match-p t))
  5056. (let ((rval (car rl)))
  5057. (setq ret ,(if all-p '(append ret (list rval)) 'rval))))
  5058. (setq sl (cdr sl) rl (cdr rl)))
  5059. ret)))))
  5060. (org-define-lookup-function first)
  5061. (org-define-lookup-function last)
  5062. (org-define-lookup-function all)
  5063. (provide 'org-table)
  5064. ;; Local variables:
  5065. ;; generated-autoload-file: "org-loaddefs.el"
  5066. ;; End:
  5067. ;;; org-table.el ends here