org-table.el 206 KB

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