org-table.el 149 KB

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