org-table.el 206 KB

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