org-table.el 189 KB

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