org-table.el 201 KB

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