org-table.el 197 KB

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