org-table.el 233 KB

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