org-table.el 192 KB

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