org-table.el 194 KB

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