org-table.el 205 KB

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