org-table.el 183 KB

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