org-table.el 235 KB

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