org-table.el 190 KB

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