org-table.el 198 KB

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