org-table.el 151 KB

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