org-table.el 203 KB

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