org-table.el 202 KB

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