org-table.el 141 KB

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