org.el 814 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193
  1. ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
  2. ;; Carstens outline-mode for keeping track of everything.
  3. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Maintainer: Bastien Guerry <bzg@gnu.org>
  7. ;; Keywords: outlines, hypermedia, calendar, wp
  8. ;; URL: https://orgmode.org
  9. ;; Package-Requires: ((emacs "25.1"))
  10. ;; Version: 9.6-dev
  11. ;; This file is part of GNU Emacs.
  12. ;;
  13. ;; GNU Emacs is free software: you can redistribute it and/or modify
  14. ;; it under the terms of the GNU General Public License as published by
  15. ;; the Free Software Foundation, either version 3 of the License, or
  16. ;; (at your option) any later version.
  17. ;; GNU Emacs is distributed in the hope that it will be useful,
  18. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. ;; GNU General Public License for more details.
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  23. ;;
  24. ;;; Commentary:
  25. ;;
  26. ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
  27. ;; project planning with a fast and effective plain-text system.
  28. ;;
  29. ;; Org mode develops organizational tasks around NOTES files that
  30. ;; contain information about projects as plain text. Org mode is
  31. ;; implemented on top of outline-mode, which makes it possible to keep
  32. ;; the content of large files well structured. Visibility cycling and
  33. ;; structure editing help to work with the tree. Tables are easily
  34. ;; created with a built-in table editor. Org mode supports ToDo
  35. ;; items, deadlines, time stamps, and scheduling. It dynamically
  36. ;; compiles entries into an agenda that utilizes and smoothly
  37. ;; integrates much of the Emacs calendar and diary. Plain text
  38. ;; URL-like links connect to websites, emails, Usenet messages, BBDB
  39. ;; entries, and any files related to the projects. For printing and
  40. ;; sharing of notes, an Org file can be exported as a structured ASCII
  41. ;; file, as HTML, or (todo and agenda items only) as an iCalendar
  42. ;; file. It can also serve as a publishing tool for a set of linked
  43. ;; webpages.
  44. ;;
  45. ;; Installation and Activation
  46. ;; ---------------------------
  47. ;; See the corresponding sections in the manual at
  48. ;;
  49. ;; https://orgmode.org/org.html#Installation
  50. ;;
  51. ;; Documentation
  52. ;; -------------
  53. ;; The documentation of Org mode can be found in the TeXInfo file. The
  54. ;; distribution also contains a PDF version of it. At the Org mode website,
  55. ;; you can read the same text online as HTML. There is also an excellent
  56. ;; reference card made by Philip Rooke. This card can be found in the
  57. ;; doc/ directory.
  58. ;;
  59. ;; A list of recent changes can be found at
  60. ;; https://orgmode.org/Changes.html
  61. ;;
  62. ;;; Code:
  63. (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
  64. (defvar org-inlinetask-min-level)
  65. ;;;; Require other packages
  66. (require 'cl-lib)
  67. (eval-when-compile (require 'gnus-sum))
  68. (require 'calendar)
  69. (require 'find-func)
  70. (require 'format-spec)
  71. (or (eq this-command 'eval-buffer)
  72. (condition-case nil
  73. (load (concat (file-name-directory load-file-name)
  74. "org-loaddefs.el")
  75. nil t t t)
  76. (error
  77. (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
  78. (sit-for 3)
  79. (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
  80. (sit-for 3))))
  81. (eval-and-compile (require 'org-macs))
  82. (require 'org-compat)
  83. (require 'org-keys)
  84. (require 'ol)
  85. (require 'oc)
  86. (require 'org-table)
  87. (require 'org-fold)
  88. (require 'org-cycle)
  89. (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
  90. (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
  91. (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
  92. (defalias 'org-global-cycle #'org-cycle-global)
  93. (defalias 'org-overview #'org-cycle-overview)
  94. (defalias 'org-content #'org-cycle-content)
  95. (defalias 'org-reveal #'org-fold-reveal)
  96. (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
  97. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  98. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  99. (defvar org-outline-regexp "\\*+ "
  100. "Regexp to match Org headlines.")
  101. (defvar org-outline-regexp-bol "^\\*+ "
  102. "Regexp to match Org headlines.
  103. This is similar to `org-outline-regexp' but additionally makes
  104. sure that we are at the beginning of the line.")
  105. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  106. "Matches a headline, putting stars and text into groups.
  107. Stars are put in group 1 and the trimmed body in group 2.")
  108. (declare-function calendar-check-holidays "holidays" (date))
  109. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  110. (declare-function cdlatex-math-symbol "ext:cdlatex")
  111. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  112. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  113. (declare-function org-add-archive-files "org-archive" (files))
  114. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  115. (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
  116. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  117. (declare-function org-agenda-redo "org-agenda" (&optional all))
  118. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  119. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  120. (declare-function org-archive-subtree-default "org-archive" ())
  121. (declare-function org-archive-to-archive-sibling "org-archive" ())
  122. (declare-function org-attach "org-attach" ())
  123. (declare-function org-attach-dir "org-attach"
  124. (&optional create-if-not-exists-p no-fs-check))
  125. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  126. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  127. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  128. (declare-function org-clock-auto-clockout "org-clock" ())
  129. (declare-function org-clock-cancel "org-clock" ())
  130. (declare-function org-clock-display "org-clock" (&optional arg))
  131. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  132. (declare-function org-clock-goto "org-clock" (&optional select))
  133. (declare-function org-clock-in "org-clock" (&optional select start-time))
  134. (declare-function org-clock-in-last "org-clock" (&optional arg))
  135. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  136. (declare-function org-clock-out-if-current "org-clock" ())
  137. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  138. (declare-function org-clock-report "org-clock" (&optional arg))
  139. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  140. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  141. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  142. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  143. (declare-function org-clock-update-time-maybe "org-clock" ())
  144. (declare-function org-clocktable-shift "org-clock" (dir n))
  145. (declare-function org-columns-quit "org-colview" ())
  146. (declare-function org-columns-insert-dblock "org-colview" ())
  147. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  148. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  149. (declare-function org-element-at-point "org-element" (&optional pom cached-only))
  150. (declare-function org-element-at-point-no-context "org-element" (&optional pom))
  151. (declare-function org-element-cache-refresh "org-element" (pos))
  152. (declare-function org-element-cache-reset "org-element" (&optional all))
  153. (declare-function org-element-cache-map "org-element" (func &rest keys))
  154. (declare-function org-element-contents "org-element" (element))
  155. (declare-function org-element-context "org-element" (&optional element))
  156. (declare-function org-element-copy "org-element" (datum))
  157. (declare-function org-element-create "org-element" (type &optional props &rest children))
  158. (declare-function org-element-extract-element "org-element" (element))
  159. (declare-function org-element-insert-before "org-element" (element location))
  160. (declare-function org-element-interpret-data "org-element" (data))
  161. (declare-function org-element-keyword-parser "org-element" (limit affiliated))
  162. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  163. (declare-function org-element-link-parser "org-element" ())
  164. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  165. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  166. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  167. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  168. (declare-function org-element-property "org-element" (property element))
  169. (declare-function org-element-put-property "org-element" (element property value))
  170. (declare-function org-element-restriction "org-element" (element))
  171. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  172. (declare-function org-element-timestamp-parser "org-element" ())
  173. (declare-function org-element-type "org-element" (element))
  174. (declare-function org-element--cache-active-p "org-element" ())
  175. (declare-function org-export-dispatch "ox" (&optional arg))
  176. (declare-function org-export-get-backend "ox" (name))
  177. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  178. (declare-function org-feed-goto-inbox "org-feed" (feed))
  179. (declare-function org-feed-update-all "org-feed" ())
  180. (declare-function org-goto "org-goto" (&optional alternative-interface))
  181. (declare-function org-id-find-id-file "org-id" (id))
  182. (declare-function org-id-get-create "org-id" (&optional force))
  183. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  184. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  185. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  186. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  187. (declare-function org-num-mode "org-num" (&optional arg))
  188. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  189. (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
  190. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  191. (declare-function org-timer "org-timer" (&optional restart no-insert))
  192. (declare-function org-timer-item "org-timer" (&optional arg))
  193. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  194. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  195. (declare-function org-timer-start "org-timer" (&optional offset))
  196. (declare-function org-timer-stop "org-timer" ())
  197. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  198. (declare-function org-update-radio-target-regexp "ol" ())
  199. (defvar org-agenda-buffer-name)
  200. (defvar org-element-paragraph-separate)
  201. (defvar org-element-cache-map-continue-from)
  202. (defvar org-element--timestamp-regexp)
  203. (defvar org-indent-indentation-per-level)
  204. (defvar org-radio-target-regexp)
  205. (defvar org-target-link-regexp)
  206. (defvar org-target-regexp)
  207. (defvar org-id-overriding-file-name)
  208. ;; load languages based on value of `org-babel-load-languages'
  209. (defvar org-babel-load-languages)
  210. (defvar crm-separator) ; dynamically scoped param
  211. ;;;###autoload
  212. (defun org-babel-do-load-languages (sym value)
  213. "Load the languages defined in `org-babel-load-languages'."
  214. (set-default-toplevel-value sym value)
  215. (dolist (pair org-babel-load-languages)
  216. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  217. (if active
  218. (require (intern (concat "ob-" lang)))
  219. (fmakunbound
  220. (intern (concat "org-babel-execute:" lang)))
  221. (fmakunbound
  222. (intern (concat "org-babel-expand-body:" lang)))))))
  223. ;;;###autoload
  224. (defun org-babel-load-file (file &optional compile)
  225. "Load Emacs Lisp source code blocks in the Org FILE.
  226. This function exports the source code using `org-babel-tangle'
  227. and then loads the resulting file using `load-file'. With
  228. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  229. byte-compiled before it is loaded."
  230. (interactive "fFile to load: \nP")
  231. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  232. ;; Tangle only if the Org file is newer than the Elisp file.
  233. (unless (org-file-newer-than-p
  234. tangled-file
  235. (file-attribute-modification-time
  236. (file-attributes (file-truename file))))
  237. ;; Make sure that tangled file modification time is
  238. ;; updated even when `org-babel-tangle-file' does not make changes.
  239. ;; This avoids re-tangling changed FILE where the changes did
  240. ;; not affect the tangled code.
  241. (when (file-exists-p tangled-file)
  242. (set-file-times tangled-file))
  243. (org-babel-tangle-file file
  244. tangled-file
  245. (rx string-start
  246. (or "emacs-lisp" "elisp")
  247. string-end)))
  248. (if compile
  249. (progn
  250. (byte-compile-file tangled-file)
  251. (load-file (byte-compile-dest-file tangled-file))
  252. (message "Compiled and loaded %s" tangled-file))
  253. (load-file tangled-file)
  254. (message "Loaded %s" tangled-file))))
  255. (defcustom org-babel-load-languages '((emacs-lisp . t))
  256. "Languages which can be evaluated in Org buffers.
  257. \\<org-mode-map>
  258. This list can be used to load support for any of the languages
  259. below. Each language will depend on a different set of system
  260. executables and/or Emacs modes.
  261. When a language is \"loaded\", code blocks in that language can
  262. be evaluated with `org-babel-execute-src-block', which is bound
  263. by default to \\[org-ctrl-c-ctrl-c].
  264. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  265. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  266. default, only Emacs Lisp is loaded, since it has no specific
  267. requirement."
  268. :group 'org-babel
  269. :set 'org-babel-do-load-languages
  270. :version "24.1"
  271. :type '(alist :tag "Babel Languages"
  272. :key-type
  273. (choice
  274. (const :tag "Awk" awk)
  275. (const :tag "C" C)
  276. (const :tag "R" R)
  277. (const :tag "Calc" calc)
  278. (const :tag "Clojure" clojure)
  279. (const :tag "CSS" css)
  280. (const :tag "Ditaa" ditaa)
  281. (const :tag "Dot" dot)
  282. (const :tag "Emacs Lisp" emacs-lisp)
  283. (const :tag "Forth" forth)
  284. (const :tag "Fortran" fortran)
  285. (const :tag "Gnuplot" gnuplot)
  286. (const :tag "Haskell" haskell)
  287. (const :tag "Java" java)
  288. (const :tag "Javascript" js)
  289. (const :tag "LaTeX" latex)
  290. (const :tag "Lilypond" lilypond)
  291. (const :tag "Lisp" lisp)
  292. (const :tag "Makefile" makefile)
  293. (const :tag "Maxima" maxima)
  294. (const :tag "Matlab" matlab)
  295. (const :tag "Ocaml" ocaml)
  296. (const :tag "Octave" octave)
  297. (const :tag "Org" org)
  298. (const :tag "Perl" perl)
  299. (const :tag "Pico Lisp" picolisp)
  300. (const :tag "PlantUML" plantuml)
  301. (const :tag "Python" python)
  302. (const :tag "Ruby" ruby)
  303. (const :tag "Sass" sass)
  304. (const :tag "Scala" scala)
  305. (const :tag "Scheme" scheme)
  306. (const :tag "Screen" screen)
  307. (const :tag "Shell Script" shell)
  308. (const :tag "Sql" sql)
  309. (const :tag "Sqlite" sqlite)
  310. (const :tag "Stan" stan))
  311. :value-type (boolean :tag "Activate" :value t)))
  312. ;;;; Customization variables
  313. (defcustom org-clone-delete-id nil
  314. "Remove ID property of clones of a subtree.
  315. When non-nil, clones of a subtree don't inherit the ID property.
  316. Otherwise they inherit the ID property with a new unique
  317. identifier."
  318. :type 'boolean
  319. :version "24.1"
  320. :group 'org-id)
  321. ;;; Version
  322. (org-check-version)
  323. ;;;###autoload
  324. (defun org-version (&optional here full message)
  325. "Show the Org version.
  326. Interactively, or when MESSAGE is non-nil, show it in echo area.
  327. With prefix argument, or when HERE is non-nil, insert it at point.
  328. In non-interactive uses, a reduced version string is output unless
  329. FULL is given."
  330. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  331. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  332. (save-load-suffixes load-suffixes)
  333. (load-suffixes (list ".el"))
  334. (org-install-dir
  335. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  336. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  337. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  338. (let* ((load-suffixes save-load-suffixes)
  339. (release (org-release))
  340. (git-version (org-git-version))
  341. (version (format "Org mode version %s (%s @ %s)"
  342. release
  343. git-version
  344. (if org-install-dir
  345. (if (string= org-dir org-install-dir)
  346. org-install-dir
  347. (concat "mixed installation! "
  348. org-install-dir
  349. " and "
  350. org-dir))
  351. "org-loaddefs.el can not be found!")))
  352. (version1 (if full version release)))
  353. (when here (insert version1))
  354. (when message (message "%s" version1))
  355. version1)))
  356. (defconst org-version (org-version))
  357. ;;; Syntax Constants
  358. ;;;; Comments
  359. (defconst org-comment-regexp
  360. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  361. "Regular expression for comment lines.")
  362. ;;;; Keyword
  363. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  364. "Regular expression for keyword-lines.")
  365. ;;;; Block
  366. (defconst org-block-regexp
  367. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  368. "Regular expression for hiding blocks.")
  369. (defconst org-dblock-start-re
  370. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  371. "Matches the start line of a dynamic block, with parameters.")
  372. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  373. "Matches the end of a dynamic block.")
  374. ;;;; Timestamp
  375. (defconst org-ts--internal-regexp
  376. (rx (seq
  377. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  378. (optional " " (*? nonl))))
  379. "Regular expression matching the innards of a time stamp.")
  380. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  381. "Regular expression for fast time stamp matching.")
  382. (defconst org-ts-regexp-inactive
  383. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  384. "Regular expression for fast inactive time stamp matching.")
  385. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  386. "Regular expression for fast time stamp matching.")
  387. (defconst org-ts-regexp0
  388. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  389. "Regular expression matching time strings for analysis.
  390. This one does not require the space after the date, so it can be used
  391. on a string that terminates immediately after the date.")
  392. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  393. "Regular expression matching time strings for analysis.")
  394. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  395. "Regular expression matching time stamps, with groups.")
  396. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  397. "Regular expression matching time stamps (also [..]), with groups.")
  398. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  399. "Regular expression matching a time stamp range.")
  400. (defconst org-tr-regexp-both
  401. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  402. "Regular expression matching a time stamp range.")
  403. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  404. org-ts-regexp "\\)?")
  405. "Regular expression matching a time stamp or time stamp range.")
  406. (defconst org-tsr-regexp-both
  407. (concat org-ts-regexp-both "\\(--?-?"
  408. org-ts-regexp-both "\\)?")
  409. "Regular expression matching a time stamp or time stamp range.
  410. The time stamps may be either active or inactive.")
  411. (defconst org-repeat-re
  412. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  413. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  414. "Regular expression for specifying repeated events.
  415. After a match, group 1 contains the repeat expression.")
  416. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  417. "Formats for `format-time-string' which are used for time stamps.")
  418. ;;;; Clock and Planning
  419. (defconst org-clock-string "CLOCK:"
  420. "String used as prefix for timestamps clocking work hours on an item.")
  421. (defvar org-closed-string "CLOSED:"
  422. "String used as the prefix for timestamps logging closing a TODO entry.")
  423. (defvar org-deadline-string "DEADLINE:"
  424. "String to mark deadline entries.
  425. \\<org-mode-map>
  426. A deadline is this string, followed by a time stamp. It must be
  427. a word, terminated by a colon. You can insert a schedule keyword
  428. and a timestamp with `\\[org-deadline]'.")
  429. (defvar org-scheduled-string "SCHEDULED:"
  430. "String to mark scheduled TODO entries.
  431. \\<org-mode-map>
  432. A schedule is this string, followed by a time stamp. It must be
  433. a word, terminated by a colon. You can insert a schedule keyword
  434. and a timestamp with `\\[org-schedule]'.")
  435. (defconst org-ds-keyword-length
  436. (+ 2
  437. (apply #'max
  438. (mapcar #'length
  439. (list org-deadline-string org-scheduled-string
  440. org-clock-string org-closed-string))))
  441. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  442. (defconst org-planning-line-re
  443. (concat "^[ \t]*"
  444. (regexp-opt
  445. (list org-closed-string org-deadline-string org-scheduled-string)
  446. t))
  447. "Matches a line with planning info.
  448. Matched keyword is in group 1.")
  449. (defconst org-clock-line-re
  450. (concat "^[ \t]*" org-clock-string)
  451. "Matches a line with clock info.")
  452. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  453. "Matches the DEADLINE keyword.")
  454. (defconst org-deadline-time-regexp
  455. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  456. "Matches the DEADLINE keyword together with a time stamp.")
  457. (defconst org-deadline-time-hour-regexp
  458. (concat "\\<" org-deadline-string
  459. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  460. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  461. (defconst org-deadline-line-regexp
  462. (concat "\\<\\(" org-deadline-string "\\).*")
  463. "Matches the DEADLINE keyword and the rest of the line.")
  464. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  465. "Matches the SCHEDULED keyword.")
  466. (defconst org-scheduled-time-regexp
  467. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  468. "Matches the SCHEDULED keyword together with a time stamp.")
  469. (defconst org-scheduled-time-hour-regexp
  470. (concat "\\<" org-scheduled-string
  471. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  472. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  473. (defconst org-closed-time-regexp
  474. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  475. "Matches the CLOSED keyword together with a time stamp.")
  476. (defconst org-keyword-time-regexp
  477. (concat "\\<"
  478. (regexp-opt
  479. (list org-scheduled-string org-deadline-string org-closed-string
  480. org-clock-string)
  481. t)
  482. " *[[<]\\([^]>]+\\)[]>]")
  483. "Matches any of the 4 keywords, together with the time stamp.")
  484. (defconst org-keyword-time-not-clock-regexp
  485. (concat
  486. "\\<"
  487. (regexp-opt
  488. (list org-scheduled-string org-deadline-string org-closed-string) t)
  489. " *[[<]\\([^]>]+\\)[]>]")
  490. "Matches any of the 3 keywords, together with the time stamp.")
  491. (defconst org-all-time-keywords
  492. (mapcar (lambda (w) (substring w 0 -1))
  493. (list org-scheduled-string org-deadline-string
  494. org-clock-string org-closed-string))
  495. "List of time keywords.")
  496. ;;;; Drawer
  497. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  498. "Matches first or last line of a hidden block.
  499. Group 1 contains drawer's name or \"END\".")
  500. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  501. "Regular expression matching the first line of a property drawer.")
  502. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  503. "Regular expression matching the last line of a property drawer.")
  504. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  505. "Regular expression matching the first line of a clock drawer.")
  506. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  507. "Regular expression matching the last line of a clock drawer.")
  508. (defconst org-logbook-drawer-re
  509. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  510. (*? (0+ nonl) "\n")
  511. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  512. "Matches an entire LOGBOOK drawer.")
  513. (defconst org-property-drawer-re
  514. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  515. "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
  516. "[ \t]*:END:[ \t]*$")
  517. "Matches an entire property drawer.")
  518. (defconst org-clock-drawer-re
  519. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  520. org-clock-drawer-end-re "\\)\n?")
  521. "Matches an entire clock drawer.")
  522. ;;;; Headline
  523. (defconst org-heading-keyword-regexp-format
  524. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  525. "Printf format for a regexp matching a headline with some keyword.
  526. This regexp will match the headline of any node which has the
  527. exact keyword that is put into the format. The keyword isn't in
  528. any group by default, but the stars and the body are.")
  529. (defconst org-heading-keyword-maybe-regexp-format
  530. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  531. "Printf format for a regexp matching a headline, possibly with some keyword.
  532. This regexp can match any headline with the specified keyword, or
  533. without a keyword. The keyword isn't in any group by default,
  534. but the stars and the body are.")
  535. (defconst org-archive-tag "ARCHIVE"
  536. "The tag that marks a subtree as archived.
  537. An archived subtree does not open during visibility cycling, and does
  538. not contribute to the agenda listings.")
  539. (defconst org-tag-re "[[:alnum:]_@#%]+"
  540. "Regexp matching a single tag.")
  541. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  542. "Regexp matching the tag group at the end of a line, with leading spaces.
  543. Tags are stored in match group 1. Match group 2 stores the tags
  544. without the enclosing colons.")
  545. (defconst org-tag-line-re
  546. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  547. "Regexp matching tags in a headline.
  548. Tags are stored in match group 1. Match group 2 stores the tags
  549. without the enclosing colons.")
  550. (eval-and-compile
  551. (defconst org-comment-string "COMMENT"
  552. "Entries starting with this keyword will never be exported.
  553. \\<org-mode-map>
  554. An entry can be toggled between COMMENT and normal with
  555. `\\[org-toggle-comment]'."))
  556. ;;;; LaTeX Environments and Fragments
  557. (defconst org-latex-regexps
  558. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  559. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  560. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  561. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  562. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  563. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  564. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  565. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  566. "Regular expressions for matching embedded LaTeX.")
  567. ;;;; Node Property
  568. (defconst org-effort-property "Effort"
  569. "The property that is being used to keep track of effort estimates.
  570. Effort estimates given in this property need to be in the format
  571. defined in org-duration.el.")
  572. ;;; The custom variables
  573. (defgroup org nil
  574. "Outline-based notes management and organizer."
  575. :tag "Org"
  576. :group 'outlines
  577. :group 'calendar)
  578. (defcustom org-mode-hook nil
  579. "Mode hook for Org mode, run after the mode was turned on."
  580. :group 'org
  581. :type 'hook)
  582. (defcustom org-load-hook nil
  583. "Hook that is run after org.el has been loaded."
  584. :group 'org
  585. :type 'hook)
  586. (make-obsolete-variable
  587. 'org-load-hook
  588. "use `with-eval-after-load' instead." "9.5")
  589. (defcustom org-log-buffer-setup-hook nil
  590. "Hook that is run after an Org log buffer is created."
  591. :group 'org
  592. :version "24.1"
  593. :type 'hook)
  594. (defvar org-modules) ; defined below
  595. (defvar org-modules-loaded nil
  596. "Have the modules been loaded already?")
  597. ;;;###autoload
  598. (defun org-load-modules-maybe (&optional force)
  599. "Load all extensions listed in `org-modules'."
  600. (when (or force (not org-modules-loaded))
  601. (dolist (ext org-modules)
  602. (condition-case nil (require ext)
  603. (error (message "Problems while trying to load feature `%s'" ext))))
  604. (setq org-modules-loaded t)))
  605. (defun org-set-modules (var value)
  606. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  607. (set-default-toplevel-value var value)
  608. (when (featurep 'org)
  609. (org-load-modules-maybe 'force)
  610. (org-element-cache-reset 'all)))
  611. (defcustom org-modules '(ol-doi ol-w3m ol-bbdb ol-bibtex ol-docview ol-gnus ol-info ol-irc ol-mhe ol-rmail ol-eww)
  612. "Modules that should always be loaded together with org.el.
  613. If a description starts with <C>, the file is not part of Emacs and Org mode,
  614. so loading it will require that you have properly installed org-contrib
  615. package from NonGNU Emacs Lisp Package Archive
  616. https://elpa.nongnu.org/nongnu/org-contrib.html
  617. You can also use this system to load external packages (i.e. neither Org
  618. core modules, nor org-contrib modules). Just add symbols
  619. to the end of the list. If the package is called org-xyz.el, then you need
  620. to add the symbol `xyz', and the package must have a call to:
  621. (provide \\='org-xyz)
  622. For export specific modules, see also `org-export-backends'."
  623. :group 'org
  624. :set 'org-set-modules
  625. :package-version '(Org . "9.5")
  626. :type
  627. '(set :greedy t
  628. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  629. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  630. (const :tag " crypt: Encryption of subtrees" org-crypt)
  631. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  632. (const :tag " docview: Links to Docview buffers" ol-docview)
  633. (const :tag " doi: Links to DOI references" ol-doi)
  634. (const :tag " eww: Store link to URL of Eww" ol-eww)
  635. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  636. (const :tag " habit: Track your consistency with habits" org-habit)
  637. (const :tag " id: Global IDs for identifying entries" org-id)
  638. (const :tag " info: Links to Info nodes" ol-info)
  639. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  640. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  641. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  642. (const :tag " mouse: Additional mouse support" org-mouse)
  643. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  644. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  645. (const :tag " tempo: Fast completion for structures" org-tempo)
  646. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  647. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  648. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  649. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  650. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  651. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  652. (const :tag "C collector: Collect properties into tables" org-collector)
  653. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  654. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  655. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  656. (const :tag "C eval: Include command output as text" org-eval)
  657. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  658. (const :tag "C git-link: Links to specific file version" ol-git-link)
  659. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  660. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  661. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  662. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  663. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  664. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  665. (const :tag "C man: Links to man pages in Org mode" ol-man)
  666. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  667. (const :tag "C notify: Notifications for Org mode" org-notify)
  668. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  669. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  670. (const :tag "C registry: A registry for Org links" org-registry)
  671. (const :tag "C screen: Visit screen sessions through links" org-screen)
  672. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  673. (const :tag "C secretary: Team management with Org" org-secretary)
  674. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  675. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  676. (const :tag "C track: Keep up with Org mode development" org-track)
  677. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  678. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  679. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  680. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  681. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  682. (defvar org-export-registered-backends) ; From ox.el.
  683. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  684. (declare-function org-export-backend-name "ox" (backend) t)
  685. (defcustom org-export-backends '(ascii html icalendar latex odt)
  686. "List of export back-ends that should be always available.
  687. If a description starts with <C>, the file is not part of Emacs and Org mode,
  688. so loading it will require that you have properly installed org-contrib
  689. package from NonGNU Emacs Lisp Package Archive
  690. https://elpa.nongnu.org/nongnu/org-contrib.html
  691. Unlike to `org-modules', libraries in this list will not be
  692. loaded along with Org, but only once the export framework is
  693. needed.
  694. This variable needs to be set before org.el is loaded. If you
  695. need to make a change while Emacs is running, use the customize
  696. interface or run the following code, where VAL stands for the new
  697. value of the variable, after updating it:
  698. (progn
  699. (setq org-export-registered-backends
  700. (cl-remove-if-not
  701. (lambda (backend)
  702. (let ((name (org-export-backend-name backend)))
  703. (or (memq name val)
  704. (catch \\='parentp
  705. (dolist (b val)
  706. (and (org-export-derived-backend-p b name)
  707. (throw \\='parentp t)))))))
  708. org-export-registered-backends))
  709. (let ((new-list (mapcar #\\='org-export-backend-name
  710. org-export-registered-backends)))
  711. (dolist (backend val)
  712. (cond
  713. ((not (load (format \"ox-%s\" backend) t t))
  714. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  715. backend))
  716. ((not (memq backend new-list)) (push backend new-list))))
  717. (set-default \\='org-export-backends new-list)))
  718. Adding a back-end to this list will also pull the back-end it
  719. depends on, if any."
  720. :group 'org
  721. :group 'org-export
  722. :version "26.1"
  723. :package-version '(Org . "9.0")
  724. :initialize 'custom-initialize-set
  725. :set (lambda (var val)
  726. (if (not (featurep 'ox)) (set-default-toplevel-value var val)
  727. ;; Any back-end not required anymore (not present in VAL and not
  728. ;; a parent of any back-end in the new value) is removed from the
  729. ;; list of registered back-ends.
  730. (setq org-export-registered-backends
  731. (cl-remove-if-not
  732. (lambda (backend)
  733. (let ((name (org-export-backend-name backend)))
  734. (or (memq name val)
  735. (catch 'parentp
  736. (dolist (b val)
  737. (and (org-export-derived-backend-p b name)
  738. (throw 'parentp t)))))))
  739. org-export-registered-backends))
  740. ;; Now build NEW-LIST of both new back-ends and required
  741. ;; parents.
  742. (let ((new-list (mapcar #'org-export-backend-name
  743. org-export-registered-backends)))
  744. (dolist (backend val)
  745. (cond
  746. ((not (load (format "ox-%s" backend) t t))
  747. (message "Problems while trying to load export back-end `%s'"
  748. backend))
  749. ((not (memq backend new-list)) (push backend new-list))))
  750. ;; Set VAR to that list with fixed dependencies.
  751. (set-default-toplevel-value var new-list))))
  752. :type '(set :greedy t
  753. (const :tag " ascii Export buffer to ASCII format" ascii)
  754. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  755. (const :tag " html Export buffer to HTML format" html)
  756. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  757. (const :tag " latex Export buffer to LaTeX format" latex)
  758. (const :tag " man Export buffer to MAN format" man)
  759. (const :tag " md Export buffer to Markdown format" md)
  760. (const :tag " odt Export buffer to ODT format" odt)
  761. (const :tag " org Export buffer to Org format" org)
  762. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  763. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  764. (const :tag "C deck Export buffer to deck.js presentations" deck)
  765. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  766. (const :tag "C groff Export buffer to Groff format" groff)
  767. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  768. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  769. (const :tag "C s5 Export buffer to s5 presentations" s5)
  770. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  771. (eval-after-load 'ox
  772. '(dolist (backend org-export-backends)
  773. (condition-case nil (require (intern (format "ox-%s" backend)))
  774. (error (message "Problems while trying to load export back-end `%s'"
  775. backend)))))
  776. (defcustom org-support-shift-select nil
  777. "Non-nil means make shift-cursor commands select text when possible.
  778. \\<org-mode-map>
  779. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  780. start selecting a region, or enlarge regions started in this way.
  781. In Org mode, in special contexts, these same keys are used for
  782. other purposes, important enough to compete with shift selection.
  783. Org tries to balance these needs by supporting `shift-select-mode'
  784. outside these special contexts, under control of this variable.
  785. The default of this variable is nil, to avoid confusing behavior. Shifted
  786. cursor keys will then execute Org commands in the following contexts:
  787. - on a headline, changing TODO state (left/right) and priority (up/down)
  788. - on a time stamp, changing the time
  789. - in a plain list item, changing the bullet type
  790. - in a property definition line, switching between allowed values
  791. - in the BEGIN line of a clock table (changing the time block).
  792. - in a table, moving the cell in the specified direction.
  793. Outside these contexts, the commands will throw an error.
  794. When this variable is t and the cursor is not in a special
  795. context, Org mode will support shift-selection for making and
  796. enlarging regions. To make this more effective, the bullet
  797. cycling will no longer happen anywhere in an item line, but only
  798. if the cursor is exactly on the bullet.
  799. If you set this variable to the symbol `always', then the keys
  800. will not be special in headlines, property lines, item lines, and
  801. table cells, to make shift selection work there as well. If this is
  802. what you want, you can use the following alternative commands:
  803. `\\[org-todo]' and `\\[org-priority]' \
  804. to change TODO state and priority,
  805. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  806. can be used to switch TODO sets,
  807. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  808. and properties can be edited by hand or in column view.
  809. However, when the cursor is on a timestamp, shift-cursor commands
  810. will still edit the time stamp - this is just too good to give up."
  811. :group 'org
  812. :type '(choice
  813. (const :tag "Never" nil)
  814. (const :tag "When outside special context" t)
  815. (const :tag "Everywhere except timestamps" always)))
  816. (defcustom org-loop-over-headlines-in-active-region t
  817. "Shall some commands act upon headlines in the active region?
  818. When set to t, some commands will be performed in all headlines
  819. within the active region.
  820. When set to `start-level', some commands will be performed in all
  821. headlines within the active region, provided that these headlines
  822. are of the same level than the first one.
  823. When set to a string, those commands will be performed on the
  824. matching headlines within the active region. Such string must be
  825. a tags/property/todo match as it is used in the agenda tags view.
  826. The list of commands is: `org-schedule', `org-deadline',
  827. `org-todo', `org-set-tags-command', `org-archive-subtree',
  828. `org-archive-set-tag', `org-toggle-archive-tag' and
  829. `org-archive-to-archive-sibling'. The archiving commands skip
  830. already archived entries.
  831. See `org-agenda-loop-over-headlines-in-active-region' for the
  832. equivalent option for agenda views."
  833. :type '(choice (const :tag "Don't loop" nil)
  834. (const :tag "All headlines in active region" t)
  835. (const :tag "In active region, headlines at the same level than the first one" start-level)
  836. (string :tag "Tags/Property/Todo matcher"))
  837. :package-version '(Org . "9.4")
  838. :group 'org-todo
  839. :group 'org-archive)
  840. (defcustom org-startup-folded 'showeverything
  841. "Non-nil means entering Org mode will switch to OVERVIEW.
  842. This can also be configured on a per-file basis by adding one of
  843. the following lines anywhere in the buffer:
  844. #+STARTUP: fold (or `overview', this is equivalent)
  845. #+STARTUP: nofold (or `showall', this is equivalent)
  846. #+STARTUP: content
  847. #+STARTUP: show<n>levels (<n> = 2..5)
  848. #+STARTUP: showeverything
  849. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  850. to ignore this option when Org opens agenda files for the first
  851. time."
  852. :group 'org-startup
  853. :package-version '(Org . "9.4")
  854. :type '(choice
  855. (const :tag "nofold: show all" nil)
  856. (const :tag "fold: overview" t)
  857. (const :tag "fold: show two levels" show2levels)
  858. (const :tag "fold: show three levels" show3levels)
  859. (const :tag "fold: show four levels" show4evels)
  860. (const :tag "fold: show five levels" show5levels)
  861. (const :tag "content: all headlines" content)
  862. (const :tag "show everything, even drawers" showeverything)))
  863. (defcustom org-startup-truncated t
  864. "Non-nil means entering Org mode will set `truncate-lines'.
  865. This is useful since some lines containing links can be very long and
  866. uninteresting. Also tables look terrible when wrapped.
  867. The variable `org-startup-truncated' allows to configure
  868. truncation for Org mode different to the other modes that use the
  869. variable `truncate-lines' and as a shortcut instead of putting
  870. the variable `truncate-lines' into the `org-mode-hook'. If one
  871. wants to configure truncation for Org mode not statically but
  872. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  873. the variable `truncate-lines' has to be used because in such a
  874. case it is too late to set the variable `org-startup-truncated'."
  875. :group 'org-startup
  876. :type 'boolean)
  877. (defcustom org-startup-indented nil
  878. "Non-nil means turn on `org-indent-mode' on startup.
  879. This can also be configured on a per-file basis by adding one of
  880. the following lines anywhere in the buffer:
  881. #+STARTUP: indent
  882. #+STARTUP: noindent"
  883. :group 'org-structure
  884. :type '(choice
  885. (const :tag "Not" nil)
  886. (const :tag "Globally (slow on startup in large files)" t)))
  887. (defcustom org-startup-numerated nil
  888. "Non-nil means turn on `org-num-mode' on startup.
  889. This can also be configured on a per-file basis by adding one of
  890. the following lines anywhere in the buffer:
  891. #+STARTUP: num
  892. #+STARTUP: nonum"
  893. :group 'org-structure
  894. :package-version '(Org . "9.4")
  895. :type '(choice
  896. (const :tag "Not" nil)
  897. (const :tag "Globally" t)))
  898. (defcustom org-use-sub-superscripts t
  899. "Non-nil means interpret \"_\" and \"^\" for display.
  900. If you want to control how Org exports those characters, see
  901. `org-export-with-sub-superscripts'.
  902. When this option is turned on, you can use TeX-like syntax for
  903. sub- and superscripts within the buffer. Several characters after
  904. \"_\" or \"^\" will be considered as a single item - so grouping
  905. with {} is normally not needed. For example, the following things
  906. will be parsed as single sub- or superscripts:
  907. 10^24 or 10^tau several digits will be considered 1 item.
  908. 10^-12 or 10^-tau a leading sign with digits or a word
  909. x^2-y^3 will be read as x^2 - y^3, because items are
  910. terminated by almost any nonword/nondigit char.
  911. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  912. Still, ambiguity is possible. So when in doubt, use {} to enclose
  913. the sub/superscript. If you set this variable to the symbol `{}',
  914. the braces are *required* in order to trigger interpretations as
  915. sub/superscript. This can be helpful in documents that need \"_\"
  916. frequently in plain text."
  917. :group 'org-startup
  918. :version "24.4"
  919. :package-version '(Org . "8.0")
  920. :type '(choice
  921. (const :tag "Always interpret" t)
  922. (const :tag "Only with braces" {})
  923. (const :tag "Never interpret" nil)))
  924. (defcustom org-startup-with-beamer-mode nil
  925. "Non-nil means turn on `org-beamer-mode' on startup.
  926. This can also be configured on a per-file basis by adding one of
  927. the following lines anywhere in the buffer:
  928. #+STARTUP: beamer"
  929. :group 'org-startup
  930. :version "24.1"
  931. :type 'boolean)
  932. (defcustom org-startup-align-all-tables nil
  933. "Non-nil means align all tables when visiting a file.
  934. This can also be configured on a per-file basis by adding one of
  935. the following lines anywhere in the buffer:
  936. #+STARTUP: align
  937. #+STARTUP: noalign"
  938. :group 'org-startup
  939. :type 'boolean)
  940. (defcustom org-startup-shrink-all-tables nil
  941. "Non-nil means shrink all table columns with a width cookie.
  942. This can also be configured on a per-file basis by adding one of
  943. the following lines anywhere in the buffer:
  944. #+STARTUP: shrink"
  945. :group 'org-startup
  946. :type 'boolean
  947. :version "27.1"
  948. :package-version '(Org . "9.2")
  949. :safe #'booleanp)
  950. (defcustom org-startup-with-inline-images nil
  951. "Non-nil means show inline images when loading a new Org file.
  952. This can also be configured on a per-file basis by adding one of
  953. the following lines anywhere in the buffer:
  954. #+STARTUP: inlineimages
  955. #+STARTUP: noinlineimages"
  956. :group 'org-startup
  957. :version "24.1"
  958. :type 'boolean)
  959. (defcustom org-startup-with-latex-preview nil
  960. "Non-nil means preview LaTeX fragments when loading a new Org file.
  961. This can also be configured on a per-file basis by adding one of
  962. the following lines anywhere in the buffer:
  963. #+STARTUP: latexpreview
  964. #+STARTUP: nolatexpreview"
  965. :group 'org-startup
  966. :version "24.4"
  967. :package-version '(Org . "8.0")
  968. :type 'boolean)
  969. (defcustom org-insert-mode-line-in-empty-file nil
  970. "Non-nil means insert the first line setting Org mode in empty files.
  971. When the function `org-mode' is called interactively in an empty file, this
  972. normally means that the file name does not automatically trigger Org mode.
  973. To ensure that the file will always be in Org mode in the future, a
  974. line enforcing Org mode will be inserted into the buffer, if this option
  975. has been set."
  976. :group 'org-startup
  977. :type 'boolean)
  978. (defcustom org-ellipsis nil
  979. "The ellipsis to use in the Org mode outline.
  980. When nil, just use the standard three dots. When a non-empty string,
  981. use that string instead.
  982. The change affects only Org mode (which will then use its own display table).
  983. Changing this requires executing `\\[org-mode]' in a buffer to become
  984. effective. It cannot be set as a local variable."
  985. :group 'org-startup
  986. :type '(choice (const :tag "Default" nil)
  987. (string :tag "String" :value "...#")))
  988. (defvar org-display-table nil
  989. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  990. (defcustom org-directory "~/org"
  991. "Directory with Org files.
  992. This is just a default location to look for Org files. There is no need
  993. at all to put your files into this directory. It is used in the
  994. following situations:
  995. 1. When a capture template specifies a target file that is not an
  996. absolute path. The path will then be interpreted relative to
  997. `org-directory'
  998. 2. When the value of variable `org-agenda-files' is a single file, any
  999. relative paths in this file will be taken as relative to
  1000. `org-directory'."
  1001. :group 'org-refile
  1002. :group 'org-capture
  1003. :type 'directory)
  1004. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  1005. "Default target for storing notes.
  1006. Used as a fall back file for org-capture.el, for templates that
  1007. do not specify a target file."
  1008. :group 'org-refile
  1009. :group 'org-capture
  1010. :type 'file)
  1011. (defcustom org-reverse-note-order nil
  1012. "Non-nil means store new notes at the beginning of a file or entry.
  1013. When nil, new notes will be filed to the end of a file or entry.
  1014. This can also be a list with cons cells of regular expressions that
  1015. are matched against file names, and values."
  1016. :group 'org-capture
  1017. :group 'org-refile
  1018. :type '(choice
  1019. (const :tag "Reverse always" t)
  1020. (const :tag "Reverse never" nil)
  1021. (repeat :tag "By file name regexp"
  1022. (cons regexp boolean))))
  1023. (defgroup org-keywords nil
  1024. "Keywords in Org mode."
  1025. :tag "Org Keywords"
  1026. :group 'org)
  1027. (defcustom org-closed-keep-when-no-todo nil
  1028. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1029. :group 'org-todo
  1030. :group 'org-keywords
  1031. :version "24.4"
  1032. :package-version '(Org . "8.0")
  1033. :type 'boolean)
  1034. (defgroup org-structure nil
  1035. "Options concerning the general structure of Org files."
  1036. :tag "Org Structure"
  1037. :group 'org)
  1038. (defcustom org-indirect-buffer-display 'other-window
  1039. "How should indirect tree buffers be displayed?
  1040. This applies to indirect buffers created with the commands
  1041. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1042. Valid values are:
  1043. current-window Display in the current window
  1044. other-window Just display in another window.
  1045. dedicated-frame Create one new frame, and re-use it each time.
  1046. new-frame Make a new frame each time. Note that in this case
  1047. previously-made indirect buffers are kept, and you need to
  1048. kill these buffers yourself."
  1049. :group 'org-structure
  1050. :group 'org-agenda-windows
  1051. :type '(choice
  1052. (const :tag "In current window" current-window)
  1053. (const :tag "In current frame, other window" other-window)
  1054. (const :tag "Each time a new frame" new-frame)
  1055. (const :tag "One dedicated frame" dedicated-frame)))
  1056. (defconst org-file-apps-gnu
  1057. '((remote . emacs)
  1058. (system . mailcap)
  1059. (t . mailcap))
  1060. "Default file applications on a UNIX or GNU/Linux system.
  1061. See `org-file-apps'.")
  1062. (defconst org-file-apps-macos
  1063. '((remote . emacs)
  1064. (system . "open %s")
  1065. ("ps.gz" . "gv %s")
  1066. ("eps.gz" . "gv %s")
  1067. ("dvi" . "xdvi %s")
  1068. ("fig" . "xfig %s")
  1069. (t . "open %s"))
  1070. "Default file applications on a macOS system.
  1071. The system \"open\" is known as a default, but we use X11 applications
  1072. for some files for which the OS does not have a good default.
  1073. See `org-file-apps'.")
  1074. (defconst org-file-apps-windowsnt
  1075. (list '(remote . emacs)
  1076. (cons 'system (lambda (file _path)
  1077. (with-no-warnings (w32-shell-execute "open" file))))
  1078. (cons t (lambda (file _path)
  1079. (with-no-warnings (w32-shell-execute "open" file)))))
  1080. "Default file applications on a Windows NT system.
  1081. The system \"open\" is used for most files.
  1082. See `org-file-apps'.")
  1083. (defcustom org-file-apps
  1084. '((auto-mode . emacs)
  1085. (directory . emacs)
  1086. ("\\.mm\\'" . default)
  1087. ("\\.x?html?\\'" . default)
  1088. ("\\.pdf\\'" . default))
  1089. "Applications for opening `file:path' items in a document.
  1090. \\<org-mode-map>
  1091. Org mode uses system defaults for different file types, but you
  1092. can use this variable to set the application for a given file
  1093. extension. The entries in this list are cons cells where the car
  1094. identifies files and the cdr the corresponding command.
  1095. Possible values for the file identifier are:
  1096. \"string\" A string as a file identifier can be interpreted in different
  1097. ways, depending on its contents:
  1098. - Alphanumeric characters only:
  1099. Match links with this file extension.
  1100. Example: (\"pdf\" . \"evince %s\")
  1101. to open PDFs with evince.
  1102. - Regular expression: Match links where the
  1103. filename matches the regexp. If you want to
  1104. use groups here, use shy groups.
  1105. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1106. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1107. to open *.html and *.xhtml with firefox.
  1108. - Regular expression which contains (non-shy) groups:
  1109. Match links where the whole link, including \"::\", and
  1110. anything after that, matches the regexp.
  1111. In a custom command string, %1, %2, etc. are replaced with
  1112. the parts of the link that were matched by the groups.
  1113. For backwards compatibility, if a command string is given
  1114. that does not use any of the group matches, this case is
  1115. handled identically to the second one (i.e. match against
  1116. file name only).
  1117. In a custom function, you can access the group matches with
  1118. (match-string n link).
  1119. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1120. \"evince -p %1 %s\")
  1121. to open [[file:document.pdf::5]] with evince at page 5.
  1122. `directory' Matches a directory
  1123. `remote' Matches a remote file, accessible through tramp or efs.
  1124. Remote files most likely should be visited through Emacs
  1125. because external applications cannot handle such paths.
  1126. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1127. so all files Emacs knows how to handle. Using this with
  1128. command `emacs' will open most files in Emacs. Beware that this
  1129. will also open html files inside Emacs, unless you add
  1130. (\"html\" . default) to the list as well.
  1131. `system' The system command to open files, like `open' on Windows
  1132. and macOS, and mailcap under GNU/Linux. This is the command
  1133. that will be selected if you call `org-open-at-point' with a
  1134. double prefix argument (`\\[universal-argument] \
  1135. \\[universal-argument] \\[org-open-at-point]').
  1136. t Default for files not matched by any of the other options.
  1137. Possible values for the command are:
  1138. `emacs' The file will be visited by the current Emacs process.
  1139. `default' Use the default application for this file type, which is the
  1140. association for t in the list, most likely in the system-specific
  1141. part. This can be used to overrule an unwanted setting in the
  1142. system-specific variable.
  1143. `system' Use the system command for opening files, like \"open\".
  1144. This command is specified by the entry whose car is `system'.
  1145. Most likely, the system-specific version of this variable
  1146. does define this command, but you can overrule/replace it
  1147. here.
  1148. `mailcap' Use command specified in the mailcaps.
  1149. string A command to be executed by a shell; %s will be replaced
  1150. by the path to the file.
  1151. function A Lisp function, which will be called with two arguments:
  1152. the file path and the original link string, without the
  1153. \"file:\" prefix.
  1154. For more examples, see the system specific constants
  1155. `org-file-apps-macos'
  1156. `org-file-apps-windowsnt'
  1157. `org-file-apps-gnu'."
  1158. :group 'org
  1159. :package-version '(Org . "9.4")
  1160. :type '(repeat
  1161. (cons (choice :value ""
  1162. (string :tag "Extension")
  1163. (const :tag "System command to open files" system)
  1164. (const :tag "Default for unrecognized files" t)
  1165. (const :tag "Remote file" remote)
  1166. (const :tag "Links to a directory" directory)
  1167. (const :tag "Any files that have Emacs modes"
  1168. auto-mode))
  1169. (choice :value ""
  1170. (const :tag "Visit with Emacs" emacs)
  1171. (const :tag "Use default" default)
  1172. (const :tag "Use the system command" system)
  1173. (string :tag "Command")
  1174. (function :tag "Function")))))
  1175. (defcustom org-resource-download-policy 'prompt
  1176. "The policy applied to requests to obtain remote resources.
  1177. This affects keywords like #+setupfile and #+incude on export,
  1178. `org-persist-write:url',and `org-attach-url' in non-interactive
  1179. Emacs sessions.
  1180. This recognises four possible values:
  1181. - t, remote resources should always be downloaded.
  1182. - prompt, you will be prompted to download resources nt considered safe.
  1183. - safe, only resources considered safe will be downloaded.
  1184. - nil, never download remote resources.
  1185. A resource is considered safe if it matches one of the patterns
  1186. in `org-safe-remote-resources'."
  1187. :group 'org
  1188. :type '(choice (const :tag "Always download remote resources" t)
  1189. (const :tag "Prompt before downloading an unsafe resource" prompt)
  1190. (const :tag "Only download resources considered safe" safe)
  1191. (const :tag "Never download any resources" nil)))
  1192. (defcustom org-safe-remote-resources nil
  1193. "A list of regexp patterns matching safe URIs.
  1194. URI regexps are applied to both URLs and Org files requesting
  1195. remote resources."
  1196. :group 'org
  1197. :type '(list regexp))
  1198. (defcustom org-open-non-existing-files nil
  1199. "Non-nil means `org-open-file' opens non-existing files.
  1200. When nil, an error is thrown.
  1201. This variable applies only to external applications because they
  1202. might choke on non-existing files. If the link is to a file that
  1203. will be opened in Emacs, the variable is ignored."
  1204. :group 'org
  1205. :type 'boolean
  1206. :safe #'booleanp)
  1207. (defcustom org-open-directory-means-index-dot-org nil
  1208. "When non-nil a link to a directory really means to \"index.org\".
  1209. When nil, following a directory link runs Dired or opens
  1210. a finder/explorer window on that directory."
  1211. :group 'org
  1212. :type 'boolean
  1213. :safe #'booleanp)
  1214. (defcustom org-bookmark-names-plist
  1215. '(:last-capture "org-capture-last-stored"
  1216. :last-refile "org-refile-last-stored"
  1217. :last-capture-marker "org-capture-last-stored-marker")
  1218. "Names for bookmarks automatically set by some Org commands.
  1219. This can provide strings as names for a number of bookmarks Org sets
  1220. automatically. The following keys are currently implemented:
  1221. :last-capture
  1222. :last-capture-marker
  1223. :last-refile
  1224. When a key does not show up in the property list, the corresponding bookmark
  1225. is not set."
  1226. :group 'org-structure
  1227. :type 'plist)
  1228. (defgroup org-edit-structure nil
  1229. "Options concerning structure editing in Org mode."
  1230. :tag "Org Edit Structure"
  1231. :group 'org-structure)
  1232. (defcustom org-odd-levels-only nil
  1233. "Non-nil means skip even levels and only use odd levels for the outline.
  1234. This has the effect that two stars are being added/taken away in
  1235. promotion/demotion commands. It also influences how levels are
  1236. handled by the exporters.
  1237. Changing it requires restart of `font-lock-mode' to become effective
  1238. for fontification also in regions already fontified.
  1239. You may also set this on a per-file basis by adding one of the following
  1240. lines to the buffer:
  1241. #+STARTUP: odd
  1242. #+STARTUP: oddeven"
  1243. :group 'org-edit-structure
  1244. :group 'org-appearance
  1245. :type 'boolean)
  1246. (defcustom org-adapt-indentation nil
  1247. "Non-nil means adapt indentation to outline node level.
  1248. When set to t, Org assumes that you write outlines by indenting
  1249. text in each node to align with the headline, after the stars.
  1250. When this variable is set to `headline-data', Org only adapts the
  1251. indentation of the data lines right below the headline, such as
  1252. planning/clock lines and property/logbook drawers.
  1253. The following issues are influenced by this variable:
  1254. - The indentation is increased by one space in a demotion
  1255. command, and decreased by one in a promotion command. However,
  1256. in the latter case, if shifting some line in the entry body
  1257. would alter document structure (e.g., insert a new headline),
  1258. indentation is not changed at all.
  1259. - Property drawers and planning information is inserted indented
  1260. when this variable is set. When nil, they will not be indented.
  1261. - TAB indents a line relative to current level. The lines below
  1262. a headline will be indented when this variable is set to t.
  1263. Note that this is all about true indentation, by adding and
  1264. removing space characters. See also \"org-indent.el\" which does
  1265. level-dependent indentation in a virtual way, i.e. at display
  1266. time in Emacs."
  1267. :group 'org-edit-structure
  1268. :type '(choice
  1269. (const :tag "Adapt indentation for all lines" t)
  1270. (const :tag "Adapt indentation for headline data lines"
  1271. headline-data)
  1272. (const :tag "Do not adapt indentation at all" nil))
  1273. :safe (lambda (x) (memq x '(t nil headline-data))))
  1274. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1275. (defcustom org-special-ctrl-a/e nil
  1276. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1277. When t, `C-a' will bring back the cursor to the beginning of the
  1278. headline text, i.e. after the stars and after a possible TODO
  1279. keyword. In an item, this will be the position after bullet and
  1280. check-box, if any. When the cursor is already at that position,
  1281. another `C-a' will bring it to the beginning of the line.
  1282. `C-e' will jump to the end of the headline, ignoring the presence
  1283. of tags in the headline. A second `C-e' will then jump to the
  1284. true end of the line, after any tags. This also means that, when
  1285. this variable is non-nil, `C-e' also will never jump beyond the
  1286. end of the heading of a folded section, i.e. not after the
  1287. ellipses.
  1288. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1289. normally, going to the true line boundary first. Only a directly
  1290. following, identical keypress will bring the cursor to the
  1291. special positions.
  1292. This may also be a cons cell where the behavior for `C-a' and
  1293. `C-e' is set separately."
  1294. :group 'org-edit-structure
  1295. :type '(choice
  1296. (const :tag "off" nil)
  1297. (const :tag "on: after stars/bullet and before tags first" t)
  1298. (const :tag "reversed: true line boundary first" reversed)
  1299. (cons :tag "Set C-a and C-e separately"
  1300. (choice :tag "Special C-a"
  1301. (const :tag "off" nil)
  1302. (const :tag "on: after stars/bullet first" t)
  1303. (const :tag "reversed: before stars/bullet first" reversed))
  1304. (choice :tag "Special C-e"
  1305. (const :tag "off" nil)
  1306. (const :tag "on: before tags first" t)
  1307. (const :tag "reversed: after tags first" reversed)))))
  1308. (defcustom org-special-ctrl-k nil
  1309. "Non-nil means `C-k' will behave specially in headlines.
  1310. When nil, `C-k' will call the default `kill-line' command.
  1311. When t, the following will happen while the cursor is in the headline:
  1312. - When at the beginning of a headline, kill the entire subtree.
  1313. - When in the middle of the headline text, kill the text up to the tags.
  1314. - When after the headline text and before the tags, kill all the tags."
  1315. :group 'org-edit-structure
  1316. :type 'boolean)
  1317. (defcustom org-ctrl-k-protect-subtree nil
  1318. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1319. When set to the symbol `error', simply throw an error when `C-k' is
  1320. used to kill (part-of) a headline that has hidden text behind it.
  1321. Any other non-nil value will result in a query to the user, if it is
  1322. OK to kill that hidden subtree. When nil, kill without remorse."
  1323. :group 'org-edit-structure
  1324. :version "24.1"
  1325. :type '(choice
  1326. (const :tag "Do not protect hidden subtrees" nil)
  1327. (const :tag "Protect hidden subtrees with a security query" t)
  1328. (const :tag "Never kill a hidden subtree with C-k" error)))
  1329. (defcustom org-special-ctrl-o t
  1330. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1331. :group 'org-edit-structure
  1332. :type 'boolean)
  1333. (defcustom org-yank-folded-subtrees t
  1334. "Non-nil means when yanking subtrees, fold them.
  1335. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1336. it starts with a heading and all other headings in it are either children
  1337. or siblings, then fold all the subtrees. However, do this only if no
  1338. text after the yank would be swallowed into a folded tree by this action."
  1339. :group 'org-edit-structure
  1340. :type 'boolean)
  1341. (defcustom org-yank-adjusted-subtrees nil
  1342. "Non-nil means when yanking subtrees, adjust the level.
  1343. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1344. this function for details."
  1345. :group 'org-edit-structure
  1346. :type 'boolean)
  1347. (defcustom org-M-RET-may-split-line '((default . t))
  1348. "Non-nil means M-RET will split the line at the cursor position.
  1349. When nil, it will go to the end of the line before making a
  1350. new line.
  1351. You may also set this option in a different way for different
  1352. contexts. Valid contexts are:
  1353. headline when creating a new headline
  1354. item when creating a new item
  1355. table in a table field
  1356. default the value to be used for all contexts not explicitly
  1357. customized"
  1358. :group 'org-structure
  1359. :group 'org-table
  1360. :type '(choice
  1361. (const :tag "Always" t)
  1362. (const :tag "Never" nil)
  1363. (repeat :greedy t :tag "Individual contexts"
  1364. (cons
  1365. (choice :tag "Context"
  1366. (const headline)
  1367. (const item)
  1368. (const table)
  1369. (const default))
  1370. (boolean)))))
  1371. (defcustom org-insert-heading-respect-content nil
  1372. "Non-nil means insert new headings after the current subtree.
  1373. \\<org-mode-map>
  1374. When nil, the new heading is created directly after the current line.
  1375. The commands `\\[org-insert-heading-respect-content]' and \
  1376. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1377. for the duration of the command."
  1378. :group 'org-structure
  1379. :type 'boolean)
  1380. (defcustom org-blank-before-new-entry '((heading . auto)
  1381. (plain-list-item . auto))
  1382. "Should `org-insert-heading' leave a blank line before new heading/item?
  1383. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1384. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1385. which case Org will look at the surrounding headings/items and try to
  1386. make an intelligent decision whether to insert a blank line or not."
  1387. :group 'org-edit-structure
  1388. :type '(list
  1389. (cons (const heading)
  1390. (choice (const :tag "Never" nil)
  1391. (const :tag "Always" t)
  1392. (const :tag "Auto" auto)))
  1393. (cons (const plain-list-item)
  1394. (choice (const :tag "Never" nil)
  1395. (const :tag "Always" t)
  1396. (const :tag "Auto" auto)))))
  1397. (defcustom org-insert-heading-hook nil
  1398. "Hook being run after inserting a new heading."
  1399. :group 'org-edit-structure
  1400. :type 'hook)
  1401. (defgroup org-sparse-trees nil
  1402. "Options concerning sparse trees in Org mode."
  1403. :tag "Org Sparse Trees"
  1404. :group 'org-structure)
  1405. (defcustom org-highlight-sparse-tree-matches t
  1406. "Non-nil means highlight all matches that define a sparse tree.
  1407. The highlights will automatically disappear the next time the buffer is
  1408. changed by an edit command."
  1409. :group 'org-sparse-trees
  1410. :type 'boolean)
  1411. (defcustom org-remove-highlights-with-change t
  1412. "Non-nil means any change to the buffer will remove temporary highlights.
  1413. \\<org-mode-map>\
  1414. Such highlights are created by `org-occur' and `org-clock-display'.
  1415. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1416. to get rid of the highlights.
  1417. The highlights created by `org-latex-preview' always need
  1418. `\\[org-latex-preview]' to be removed."
  1419. :group 'org-sparse-trees
  1420. :group 'org-time
  1421. :type 'boolean)
  1422. (defcustom org-occur-case-fold-search t
  1423. "Non-nil means `org-occur' should be case-insensitive.
  1424. If set to `smart' the search will be case-insensitive only if it
  1425. doesn't specify any upper case character."
  1426. :group 'org-sparse-trees
  1427. :version "26.1"
  1428. :type '(choice
  1429. (const :tag "Case-sensitive" nil)
  1430. (const :tag "Case-insensitive" t)
  1431. (const :tag "Case-insensitive for lower case searches only" smart)))
  1432. (defcustom org-occur-hook '(org-first-headline-recenter)
  1433. "Hook that is run after `org-occur' has constructed a sparse tree.
  1434. This can be used to recenter the window to show as much of the structure
  1435. as possible."
  1436. :group 'org-sparse-trees
  1437. :type 'hook)
  1438. (defcustom org-self-insert-cluster-for-undo nil
  1439. "Non-nil means cluster self-insert commands for undo when possible.
  1440. If this is set, then, like in the Emacs command loop, 20 consecutive
  1441. characters will be undone together.
  1442. This is configurable, because there is some impact on typing performance."
  1443. :group 'org-table
  1444. :type 'boolean)
  1445. (defvaralias 'org-activate-links 'org-highlight-links)
  1446. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1447. "Types of links that should be highlighted in Org files.
  1448. This is a list of symbols, each one of them leading to the
  1449. highlighting of a certain link type.
  1450. You can still open links that are not highlighted.
  1451. In principle, it does not hurt to turn on highlighting for all
  1452. link types. There may be a small gain when turning off unused
  1453. link types. The types are:
  1454. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1455. angle Links in angular brackets that may contain whitespace like
  1456. <bbdb:Carsten Dominik>.
  1457. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1458. radio Text that is matched by a radio target, see manual for details.
  1459. tag Tag settings in a headline (link to tag search).
  1460. date Time stamps (link to calendar).
  1461. footnote Footnote labels.
  1462. If you set this variable during an Emacs session, use `org-mode-restart'
  1463. in the Org buffer so that the change takes effect."
  1464. :group 'org-appearance
  1465. :type '(set :greedy t
  1466. (const :tag "Double bracket links" bracket)
  1467. (const :tag "Angular bracket links" angle)
  1468. (const :tag "Plain text links" plain)
  1469. (const :tag "Radio target matches" radio)
  1470. (const :tag "Tags" tag)
  1471. (const :tag "Timestamps" date)
  1472. (const :tag "Footnotes" footnote)))
  1473. (defcustom org-mark-ring-length 4
  1474. "Number of different positions to be recorded in the ring.
  1475. Changing this requires a restart of Emacs to work correctly."
  1476. :group 'org-link-follow
  1477. :type 'integer)
  1478. (defgroup org-todo nil
  1479. "Options concerning TODO items in Org mode."
  1480. :tag "Org TODO"
  1481. :group 'org)
  1482. (defgroup org-progress nil
  1483. "Options concerning Progress logging in Org mode."
  1484. :tag "Org Progress"
  1485. :group 'org-time)
  1486. (defvar org-todo-interpretation-widgets
  1487. '((:tag "Sequence (cycling hits every state)" sequence)
  1488. (:tag "Type (cycling directly to DONE)" type))
  1489. "The available interpretation symbols for customizing `org-todo-keywords'.
  1490. Interested libraries should add to this list.")
  1491. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1492. "List of TODO entry keyword sequences and their interpretation.
  1493. \\<org-mode-map>This is a list of sequences.
  1494. Each sequence starts with a symbol, either `sequence' or `type',
  1495. indicating if the keywords should be interpreted as a sequence of
  1496. action steps, or as different types of TODO items. The first
  1497. keywords are states requiring action - these states will select a headline
  1498. for inclusion into the global TODO list Org produces. If one of the
  1499. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1500. signify that no further action is necessary. If \"|\" is not found,
  1501. the last keyword is treated as the only DONE state of the sequence.
  1502. The command `\\[org-todo]' cycles an entry through these states, and one
  1503. additional state where no keyword is present. For details about this
  1504. cycling, see the manual.
  1505. TODO keywords and interpretation can also be set on a per-file basis with
  1506. the special #+SEQ_TODO and #+TYP_TODO lines.
  1507. Each keyword can optionally specify a character for fast state selection
  1508. \(in combination with the variable `org-use-fast-todo-selection')
  1509. and specifiers for state change logging, using the same syntax that
  1510. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1511. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1512. indicates to record a time stamp each time this state is selected.
  1513. Each keyword may also specify if a timestamp or a note should be
  1514. recorded when entering or leaving the state, by adding additional
  1515. characters in the parenthesis after the keyword. This looks like this:
  1516. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1517. record only the time of the state change. With X and Y being either
  1518. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1519. Y when leaving the state if and only if the *target* state does not
  1520. define X. You may omit any of the fast-selection key or X or /Y,
  1521. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1522. For backward compatibility, this variable may also be just a list
  1523. of keywords. In this case the interpretation (sequence or type) will be
  1524. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1525. :group 'org-todo
  1526. :group 'org-keywords
  1527. :type '(choice
  1528. (repeat :tag "Old syntax, just keywords"
  1529. (string :tag "Keyword"))
  1530. (repeat :tag "New syntax"
  1531. (cons
  1532. (choice
  1533. :tag "Interpretation"
  1534. ;;Quick and dirty way to see
  1535. ;;`org-todo-interpretation'. This takes the
  1536. ;;place of item arguments
  1537. :convert-widget
  1538. (lambda (widget)
  1539. (widget-put widget
  1540. :args (mapcar
  1541. (lambda (x)
  1542. (widget-convert
  1543. (cons 'const x)))
  1544. org-todo-interpretation-widgets))
  1545. widget))
  1546. (repeat
  1547. (string :tag "Keyword"))))))
  1548. (defvar-local org-todo-keywords-1 nil
  1549. "All TODO and DONE keywords active in a buffer.")
  1550. (defvar org-todo-keywords-for-agenda nil)
  1551. (defvar org-done-keywords-for-agenda nil)
  1552. (defvar org-todo-keyword-alist-for-agenda nil)
  1553. (defvar org-tag-alist-for-agenda nil
  1554. "Alist of all tags from all agenda files.")
  1555. (defvar org-tag-groups-alist-for-agenda nil
  1556. "Alist of all groups tags from all current agenda files.")
  1557. (defvar-local org-tag-groups-alist nil)
  1558. (defvar org-agenda-contributing-files nil)
  1559. (defvar-local org-current-tag-alist nil
  1560. "Alist of all tag groups in current buffer.
  1561. This variable takes into consideration `org-tag-alist',
  1562. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1563. (defvar-local org-not-done-keywords nil)
  1564. (defvar-local org-done-keywords nil)
  1565. (defvar-local org-todo-heads nil)
  1566. (defvar-local org-todo-sets nil)
  1567. (defvar-local org-todo-log-states nil)
  1568. (defvar-local org-todo-kwd-alist nil)
  1569. (defvar-local org-todo-key-alist nil)
  1570. (defvar-local org-todo-key-trigger nil)
  1571. (defcustom org-todo-interpretation 'sequence
  1572. "Controls how TODO keywords are interpreted.
  1573. This variable is in principle obsolete and is only used for
  1574. backward compatibility, if the interpretation of todo keywords is
  1575. not given already in `org-todo-keywords'. See that variable for
  1576. more information."
  1577. :group 'org-todo
  1578. :group 'org-keywords
  1579. :type '(choice (const sequence)
  1580. (const type)))
  1581. (defcustom org-use-fast-todo-selection 'auto
  1582. "\\<org-mode-map>\
  1583. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1584. This variable describes if and under what circumstances the cycling
  1585. mechanism for TODO keywords will be replaced by a single-key, direct
  1586. selection scheme, where the choices are displayed in a little window.
  1587. When nil, fast selection is never used. This means that the command
  1588. will always switch to the next state.
  1589. When it is the symbol `auto', fast selection is whenever selection
  1590. keys have been defined.
  1591. `expert' is like `auto', but no special window with the keyword
  1592. will be shown, choices will only be listed in the prompt.
  1593. In all cases, the special interface is only used if access keys have
  1594. actually been assigned by the user, i.e. if keywords in the configuration
  1595. are followed by a letter in parenthesis, like TODO(t)."
  1596. :group 'org-todo
  1597. :set (lambda (var val)
  1598. (cond
  1599. ((eq var t) (set-default-toplevel-value var 'auto))
  1600. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1601. (t (set-default-toplevel-value var val))))
  1602. :type '(choice
  1603. (const :tag "Never" nil)
  1604. (const :tag "Automatically, when key letter have been defined" auto)
  1605. (const :tag "Automatically, but don't show the selection window" expert)))
  1606. (defcustom org-provide-todo-statistics t
  1607. "Non-nil means update todo statistics after insert and toggle.
  1608. ALL-HEADLINES means update todo statistics by including headlines
  1609. with no TODO keyword as well, counting them as not done.
  1610. A list of TODO keywords means the same, but skip keywords that are
  1611. not in this list.
  1612. When set to a list of two lists, the first list contains keywords
  1613. to consider as TODO keywords, the second list contains keywords
  1614. to consider as DONE keywords.
  1615. When this is set, todo statistics is updated in the parent of the
  1616. current entry each time a todo state is changed."
  1617. :group 'org-todo
  1618. :type '(choice
  1619. (const :tag "Yes, only for TODO entries" t)
  1620. (const :tag "Yes, including all entries" all-headlines)
  1621. (repeat :tag "Yes, for TODOs in this list"
  1622. (string :tag "TODO keyword"))
  1623. (list :tag "Yes, for TODOs and DONEs in these lists"
  1624. (repeat (string :tag "TODO keyword"))
  1625. (repeat (string :tag "DONE keyword")))
  1626. (other :tag "No TODO statistics" nil)))
  1627. (defcustom org-hierarchical-todo-statistics t
  1628. "Non-nil means TODO statistics covers just direct children.
  1629. When nil, all entries in the subtree are considered.
  1630. This has only an effect if `org-provide-todo-statistics' is set.
  1631. To set this to nil for only a single subtree, use a COOKIE_DATA
  1632. property and include the word \"recursive\" into the value."
  1633. :group 'org-todo
  1634. :type 'boolean)
  1635. (defcustom org-after-todo-state-change-hook nil
  1636. "Hook which is run after the state of a TODO item was changed.
  1637. The new state (a string with a TODO keyword, or nil) is available in the
  1638. Lisp variable `org-state'."
  1639. :group 'org-todo
  1640. :type 'hook)
  1641. (defvar org-blocker-hook nil
  1642. "Hook for functions that are allowed to block a state change.
  1643. Functions in this hook should not modify the buffer.
  1644. Each function gets as its single argument a property list,
  1645. see `org-trigger-hook' for more information about this list.
  1646. If any of the functions in this hook returns nil, the state change
  1647. is blocked.")
  1648. (defvar org-trigger-hook nil
  1649. "Hook for functions that are triggered by a state change.
  1650. Each function gets as its single argument a property list with at
  1651. least the following elements:
  1652. (:type type-of-change :position pos-at-entry-start
  1653. :from old-state :to new-state)
  1654. Depending on the type, more properties may be present.
  1655. This mechanism is currently implemented for:
  1656. TODO state changes
  1657. ------------------
  1658. :type todo-state-change
  1659. :from previous state (keyword as a string), or nil, or a symbol
  1660. `todo' or `done', to indicate the general type of state.
  1661. :to new state, like in :from")
  1662. (defcustom org-enforce-todo-dependencies nil
  1663. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1664. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1665. be blocked if any prior sibling is not yet done.
  1666. Finally, if the parent is blocked because of ordered siblings of its own,
  1667. the child will also be blocked."
  1668. :set (lambda (var val)
  1669. (set-default-toplevel-value var val)
  1670. (if val
  1671. (add-hook 'org-blocker-hook
  1672. 'org-block-todo-from-children-or-siblings-or-parent)
  1673. (remove-hook 'org-blocker-hook
  1674. 'org-block-todo-from-children-or-siblings-or-parent)))
  1675. :group 'org-todo
  1676. :type 'boolean)
  1677. (defcustom org-enforce-todo-checkbox-dependencies nil
  1678. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1679. When this is nil, checkboxes have no influence on switching TODO states.
  1680. When non-nil, you first need to check off all check boxes before the TODO
  1681. entry can be switched to DONE.
  1682. This variable needs to be set before org.el is loaded, and you need to
  1683. restart Emacs after a change to make the change effective. The only way
  1684. to change it while Emacs is running is through the customize interface."
  1685. :set (lambda (var val)
  1686. (set-default-toplevel-value var val)
  1687. (if val
  1688. (add-hook 'org-blocker-hook
  1689. 'org-block-todo-from-checkboxes)
  1690. (remove-hook 'org-blocker-hook
  1691. 'org-block-todo-from-checkboxes)))
  1692. :group 'org-todo
  1693. :type 'boolean)
  1694. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1695. "Non-nil means inserting a TODO heading is treated as state change.
  1696. So when the command `\\[org-insert-todo-heading]' is used, state change
  1697. logging will apply if appropriate. When nil, the new TODO item will
  1698. be inserted directly, and no logging will take place."
  1699. :group 'org-todo
  1700. :type 'boolean)
  1701. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1702. "Non-nil means switching TODO states with S-cursor counts as state change.
  1703. This is the default behavior. However, setting this to nil allows a
  1704. convenient way to select a TODO state and bypass any logging associated
  1705. with that."
  1706. :group 'org-todo
  1707. :type 'boolean)
  1708. (defcustom org-todo-state-tags-triggers nil
  1709. "Tag changes that should be triggered by TODO state changes.
  1710. This is a list. Each entry is
  1711. (state-change (tag . flag) .......)
  1712. State-change can be a string with a state, and empty string to indicate the
  1713. state that has no TODO keyword, or it can be one of the symbols `todo'
  1714. or `done', meaning any not-done or done state, respectively."
  1715. :group 'org-todo
  1716. :group 'org-tags
  1717. :type '(repeat
  1718. (cons (choice :tag "When changing to"
  1719. (const :tag "Not-done state" todo)
  1720. (const :tag "Done state" done)
  1721. (string :tag "State"))
  1722. (repeat
  1723. (cons :tag "Tag action"
  1724. (string :tag "Tag")
  1725. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1726. (defcustom org-log-done nil
  1727. "Information to record when a task moves to the DONE state.
  1728. Possible values are:
  1729. nil Don't add anything, just change the keyword
  1730. time Add a time stamp to the task
  1731. note Prompt for a note and add it with template `org-log-note-headings'
  1732. This option can also be set with on a per-file-basis with
  1733. #+STARTUP: nologdone
  1734. #+STARTUP: logdone
  1735. #+STARTUP: lognotedone
  1736. You can have local logging settings for a subtree by setting the LOGGING
  1737. property to one or more of these keywords."
  1738. :group 'org-todo
  1739. :group 'org-progress
  1740. :type '(choice
  1741. (const :tag "No logging" nil)
  1742. (const :tag "Record CLOSED timestamp" time)
  1743. (const :tag "Record CLOSED timestamp with note." note)))
  1744. ;; Normalize old uses of org-log-done.
  1745. (cond
  1746. ((eq org-log-done t) (setq org-log-done 'time))
  1747. ((and (listp org-log-done) (memq 'done org-log-done))
  1748. (setq org-log-done 'note)))
  1749. (defcustom org-log-reschedule nil
  1750. "Information to record when the scheduling date of a task is modified.
  1751. Possible values are:
  1752. nil Don't add anything, just change the date
  1753. time Add a time stamp to the task
  1754. note Prompt for a note and add it with template `org-log-note-headings'
  1755. This option can also be set with on a per-file-basis with
  1756. #+STARTUP: nologreschedule
  1757. #+STARTUP: logreschedule
  1758. #+STARTUP: lognotereschedule
  1759. You can have local logging settings for a subtree by setting the LOGGING
  1760. property to one or more of these keywords.
  1761. This variable has an effect when calling `org-schedule' or
  1762. `org-agenda-schedule' only."
  1763. :group 'org-todo
  1764. :group 'org-progress
  1765. :type '(choice
  1766. (const :tag "No logging" nil)
  1767. (const :tag "Record timestamp" time)
  1768. (const :tag "Record timestamp with note" note)))
  1769. (defcustom org-log-redeadline nil
  1770. "Information to record when the deadline date of a task is modified.
  1771. Possible values are:
  1772. nil Don't add anything, just change the date
  1773. time Add a time stamp to the task
  1774. note Prompt for a note and add it with template `org-log-note-headings'
  1775. This option can also be set with on a per-file-basis with
  1776. #+STARTUP: nologredeadline
  1777. #+STARTUP: logredeadline
  1778. #+STARTUP: lognoteredeadline
  1779. You can have local logging settings for a subtree by setting the LOGGING
  1780. property to one or more of these keywords.
  1781. This variable has an effect when calling `org-deadline' or
  1782. `org-agenda-deadline' only."
  1783. :group 'org-todo
  1784. :group 'org-progress
  1785. :type '(choice
  1786. (const :tag "No logging" nil)
  1787. (const :tag "Record timestamp" time)
  1788. (const :tag "Record timestamp with note." note)))
  1789. (defcustom org-log-note-clock-out nil
  1790. "Non-nil means record a note when clocking out of an item.
  1791. This can also be configured on a per-file basis by adding one of
  1792. the following lines anywhere in the buffer:
  1793. #+STARTUP: lognoteclock-out
  1794. #+STARTUP: nolognoteclock-out"
  1795. :group 'org-todo
  1796. :group 'org-progress
  1797. :type 'boolean)
  1798. (defcustom org-log-done-with-time t
  1799. "Non-nil means the CLOSED time stamp will contain date and time.
  1800. When nil, only the date will be recorded."
  1801. :group 'org-progress
  1802. :type 'boolean)
  1803. (defcustom org-log-note-headings
  1804. '((done . "CLOSING NOTE %t")
  1805. (state . "State %-12s from %-12S %t")
  1806. (note . "Note taken on %t")
  1807. (reschedule . "Rescheduled from %S on %t")
  1808. (delschedule . "Not scheduled, was %S on %t")
  1809. (redeadline . "New deadline from %S on %t")
  1810. (deldeadline . "Removed deadline, was %S on %t")
  1811. (refile . "Refiled on %t")
  1812. (clock-out . ""))
  1813. "Headings for notes added to entries.
  1814. The value is an alist, with the car being a symbol indicating the
  1815. note context, and the cdr is the heading to be used. The heading
  1816. may also be the empty string. The following placeholders can be
  1817. used:
  1818. %t a time stamp.
  1819. %T an active time stamp instead the default inactive one
  1820. %d a short-format time stamp.
  1821. %D an active short-format time stamp.
  1822. %s the new TODO state or time stamp (inactive), in double quotes.
  1823. %S the old TODO state or time stamp (inactive), in double quotes.
  1824. %u the user name.
  1825. %U full user name.
  1826. In fact, it is not a good idea to change the `state' entry,
  1827. because Agenda Log mode depends on the format of these entries."
  1828. :group 'org-todo
  1829. :group 'org-progress
  1830. :type '(list :greedy t
  1831. (cons (const :tag "Heading when closing an item" done) string)
  1832. (cons (const :tag
  1833. "Heading when changing todo state (todo sequence only)"
  1834. state) string)
  1835. (cons (const :tag "Heading when just taking a note" note) string)
  1836. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1837. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1838. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1839. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1840. (cons (const :tag "Heading when refiling" refile) string)
  1841. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1842. (unless (assq 'note org-log-note-headings)
  1843. (push '(note . "%t") org-log-note-headings))
  1844. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1845. (defcustom org-log-into-drawer nil
  1846. "Non-nil means insert state change notes and time stamps into a drawer.
  1847. When nil, state changes notes will be inserted after the headline and
  1848. any scheduling and clock lines, but not inside a drawer.
  1849. The value of this variable should be the name of the drawer to use.
  1850. LOGBOOK is proposed as the default drawer for this purpose, you can
  1851. also set this to a string to define the drawer of your choice.
  1852. A value of t is also allowed, representing \"LOGBOOK\".
  1853. A value of t or nil can also be set with on a per-file-basis with
  1854. #+STARTUP: logdrawer
  1855. #+STARTUP: nologdrawer
  1856. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1857. will be ignored.
  1858. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1859. a subtree.
  1860. Do not check directly this variable in a Lisp program. Call
  1861. function `org-log-into-drawer' instead."
  1862. :group 'org-todo
  1863. :group 'org-progress
  1864. :type '(choice
  1865. (const :tag "Not into a drawer" nil)
  1866. (const :tag "LOGBOOK" t)
  1867. (string :tag "Other")))
  1868. (defun org-log-into-drawer ()
  1869. "Name of the log drawer, as a string, or nil.
  1870. This is the value of `org-log-into-drawer'. However, if the
  1871. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1872. be used instead of the default value."
  1873. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1874. (cond ((equal p "nil") nil)
  1875. ((equal p "t") "LOGBOOK")
  1876. ((stringp p) p)
  1877. (p "LOGBOOK")
  1878. ((stringp org-log-into-drawer) org-log-into-drawer)
  1879. (org-log-into-drawer "LOGBOOK"))))
  1880. (defcustom org-log-state-notes-insert-after-drawers nil
  1881. "Non-nil means insert state change notes after any drawers in entry.
  1882. Only the drawers that *immediately* follow the headline and the
  1883. deadline/scheduled line are skipped.
  1884. When nil, insert notes right after the heading and perhaps the line
  1885. with deadline/scheduling if present.
  1886. This variable will have no effect if `org-log-into-drawer' is
  1887. set."
  1888. :group 'org-todo
  1889. :group 'org-progress
  1890. :type 'boolean)
  1891. (defcustom org-log-states-order-reversed t
  1892. "Non-nil means the latest state note will be directly after heading.
  1893. When nil, the state change notes will be ordered according to time.
  1894. This option can also be set with on a per-file-basis with
  1895. #+STARTUP: logstatesreversed
  1896. #+STARTUP: nologstatesreversed"
  1897. :group 'org-todo
  1898. :group 'org-progress
  1899. :type 'boolean)
  1900. (defcustom org-todo-repeat-to-state nil
  1901. "The TODO state to which a repeater should return the repeating task.
  1902. By default this is the first task of a TODO sequence or the
  1903. previous state of a TYPE_TODO set. But you can specify to use
  1904. the previous state in a TODO sequence or a string.
  1905. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1906. entry, which has precedence over this option."
  1907. :group 'org-todo
  1908. :version "24.1"
  1909. :type '(choice (const :tag "Use the previous TODO state" t)
  1910. (const :tag "Use the head of the TODO sequence" nil)
  1911. (string :tag "Use a specific TODO state")))
  1912. (defcustom org-log-repeat 'time
  1913. "Non-nil means record moving through the DONE state when triggering repeat.
  1914. An auto-repeating task is immediately switched back to TODO when
  1915. marked DONE. If you are not logging state changes (by adding \"@\"
  1916. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1917. record a closing note, there will be no record of the task moving
  1918. through DONE. This variable forces taking a note anyway.
  1919. nil Don't force a record
  1920. time Record a time stamp
  1921. note Prompt for a note and add it with template `org-log-note-headings'
  1922. This option can also be set with on a per-file-basis with
  1923. #+STARTUP: nologrepeat
  1924. #+STARTUP: logrepeat
  1925. #+STARTUP: lognoterepeat
  1926. You can have local logging settings for a subtree by setting the LOGGING
  1927. property to one or more of these keywords."
  1928. :group 'org-todo
  1929. :group 'org-progress
  1930. :type '(choice
  1931. (const :tag "Don't force a record" nil)
  1932. (const :tag "Force recording the DONE state" time)
  1933. (const :tag "Force recording a note with the DONE state" note)))
  1934. (defcustom org-todo-repeat-hook nil
  1935. "Hook that is run after a task has been repeated."
  1936. :package-version '(Org . "9.2")
  1937. :group 'org-todo
  1938. :type 'hook)
  1939. (defgroup org-priorities nil
  1940. "Priorities in Org mode."
  1941. :tag "Org Priorities"
  1942. :group 'org-todo)
  1943. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1944. (defcustom org-priority-enable-commands t
  1945. "Non-nil means priority commands are active.
  1946. When nil, these commands will be disabled, so that you never accidentally
  1947. set a priority."
  1948. :group 'org-priorities
  1949. :type 'boolean)
  1950. (defvaralias 'org-highest-priority 'org-priority-highest)
  1951. (defcustom org-priority-highest ?A
  1952. "The highest priority of TODO items.
  1953. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1954. The default is the character ?A, which is 65 as a numeric value.
  1955. If you set `org-priority-highest' to a numeric value inferior to
  1956. 65, Org assumes you want to use digits for the priority cookie.
  1957. If you set it to >=65, Org assumes you want to use alphabetical
  1958. characters.
  1959. In both cases, the value of `org-priority-highest' must be
  1960. smaller than `org-priority-lowest': for example, if \"A\" is the
  1961. highest priority, it is smaller than the lowest \"C\" priority:
  1962. 65 < 67."
  1963. :group 'org-priorities
  1964. :type '(choice
  1965. (character :tag "Character")
  1966. (integer :tag "Integer (< 65)")))
  1967. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1968. (defcustom org-priority-lowest ?C
  1969. "The lowest priority of TODO items.
  1970. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1971. The default is the character ?C, which is 67 as a numeric value.
  1972. If you set `org-priority-lowest' to a numeric value inferior to
  1973. 65, Org assumes you want to use digits for the priority cookie.
  1974. If you set it to >=65, Org assumes you want to use alphabetical
  1975. characters.
  1976. In both cases, the value of `org-priority-lowest' must be greater
  1977. than `org-priority-highest': for example, if \"C\" is the lowest
  1978. priority, it is greater than the highest \"A\" priority: 67 >
  1979. 65."
  1980. :group 'org-priorities
  1981. :type '(choice
  1982. (character :tag "Character")
  1983. (integer :tag "Integer (< 65)")))
  1984. (defvaralias 'org-default-priority 'org-priority-default)
  1985. (defcustom org-priority-default ?B
  1986. "The default priority of TODO items.
  1987. This is the priority an item gets if no explicit priority is given.
  1988. When starting to cycle on an empty priority the first step in the cycle
  1989. depends on `org-priority-start-cycle-with-default'. The resulting first
  1990. step priority must not exceed the range from `org-priority-highest' to
  1991. `org-priority-lowest' which means that `org-priority-default' has to be
  1992. in this range exclusive or inclusive to the range boundaries. Else the
  1993. first step refuses to set the default and the second will fall back on
  1994. \(depending on the command used) the highest or lowest priority."
  1995. :group 'org-priorities
  1996. :type '(choice
  1997. (character :tag "Character")
  1998. (integer :tag "Integer (< 65)")))
  1999. (defcustom org-priority-start-cycle-with-default t
  2000. "Non-nil means start with default priority when starting to cycle.
  2001. When this is nil, the first step in the cycle will be (depending on the
  2002. command used) one higher or lower than the default priority.
  2003. See also `org-priority-default'."
  2004. :group 'org-priorities
  2005. :type 'boolean)
  2006. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2007. (defcustom org-priority-get-priority-function nil
  2008. "Function to extract the priority from a string.
  2009. The string is normally the headline. If this is nil, Org
  2010. computes the priority from the priority cookie like [#A] in the
  2011. headline. It returns an integer, increasing by 1000 for each
  2012. priority level.
  2013. The user can set a different function here, which should take a
  2014. string as an argument and return the numeric priority."
  2015. :group 'org-priorities
  2016. :version "24.1"
  2017. :type '(choice
  2018. (const nil)
  2019. (function)))
  2020. (defgroup org-time nil
  2021. "Options concerning time stamps and deadlines in Org mode."
  2022. :tag "Org Time"
  2023. :group 'org)
  2024. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2025. "Number of minutes to round time stamps to.
  2026. \\<org-mode-map>\
  2027. These are two values, the first applies when first creating a time stamp.
  2028. The second applies when changing it with the commands `S-up' and `S-down'.
  2029. When changing the time stamp, this means that it will change in steps
  2030. of N minutes, as given by the second value.
  2031. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2032. numbers should be factors of 60, so for example 5, 10, 15.
  2033. When this is larger than 1, you can still force an exact time stamp by using
  2034. a double prefix argument to a time stamp command like \
  2035. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2036. and by using a prefix arg to `S-up/down' to specify the exact number
  2037. of minutes to shift."
  2038. :group 'org-time
  2039. :get (lambda (var) ; Make sure both elements are there
  2040. (if (integerp (default-value var))
  2041. (list (default-value var) 5)
  2042. (default-value var)))
  2043. :type '(list
  2044. (integer :tag "when inserting times")
  2045. (integer :tag "when modifying times")))
  2046. ;; Normalize old customizations of this variable.
  2047. (when (integerp org-time-stamp-rounding-minutes)
  2048. (setq org-time-stamp-rounding-minutes
  2049. (list org-time-stamp-rounding-minutes
  2050. org-time-stamp-rounding-minutes)))
  2051. (defcustom org-display-custom-times nil
  2052. "Non-nil means overlay custom formats over all time stamps.
  2053. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2054. To turn this on on a per-file basis, insert anywhere in the file:
  2055. #+STARTUP: customtime"
  2056. :group 'org-time
  2057. :type 'sexp)
  2058. (make-variable-buffer-local 'org-display-custom-times)
  2059. (defcustom org-time-stamp-custom-formats
  2060. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2061. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2062. These are overlaid over the default ISO format if the variable
  2063. `org-display-custom-times' is set. Time like %H:%M should be at the
  2064. end of the second format. The custom formats are also honored by export
  2065. commands, if custom time display is turned on at the time of export."
  2066. :group 'org-time
  2067. :type 'sexp)
  2068. (defun org-time-stamp-format (&optional long inactive)
  2069. "Get the right format for a time string."
  2070. (let ((f (if long (cdr org-time-stamp-formats)
  2071. (car org-time-stamp-formats))))
  2072. (if inactive
  2073. (concat "[" (substring f 1 -1) "]")
  2074. f)))
  2075. (defcustom org-deadline-warning-days 14
  2076. "Number of days before expiration during which a deadline becomes active.
  2077. This variable governs the display in sparse trees and in the agenda.
  2078. When 0 or negative, it means use this number (the absolute value of it)
  2079. even if a deadline has a different individual lead time specified.
  2080. Custom commands can set this variable in the options section."
  2081. :group 'org-time
  2082. :group 'org-agenda-daily/weekly
  2083. :type 'integer)
  2084. (defcustom org-scheduled-delay-days 0
  2085. "Number of days before a scheduled item becomes active.
  2086. This variable governs the display in sparse trees and in the agenda.
  2087. The default value (i.e. 0) means: don't delay scheduled item.
  2088. When negative, it means use this number (the absolute value of it)
  2089. even if a scheduled item has a different individual delay time
  2090. specified.
  2091. Custom commands can set this variable in the options section."
  2092. :group 'org-time
  2093. :group 'org-agenda-daily/weekly
  2094. :version "24.4"
  2095. :package-version '(Org . "8.0")
  2096. :type 'integer)
  2097. (defcustom org-read-date-prefer-future t
  2098. "Non-nil means assume future for incomplete date input from user.
  2099. This affects the following situations:
  2100. 1. The user gives a month but not a year.
  2101. For example, if it is April and you enter \"feb 2\", this will be read
  2102. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2103. 2. The user gives a day, but no month.
  2104. For example, if today is the 15th, and you enter \"3\", Org will read
  2105. this as the third of *next* month. However, if you enter \"17\",
  2106. it will be considered as *this* month.
  2107. If you set this variable to the symbol `time', then also the following
  2108. will work:
  2109. 3. If the user gives a time.
  2110. If the time is before now, it will be interpreted as tomorrow.
  2111. Currently none of this works for ISO week specifications.
  2112. When this option is nil, the current day, month and year will always be
  2113. used as defaults.
  2114. See also `org-agenda-jump-prefer-future'."
  2115. :group 'org-time
  2116. :type '(choice
  2117. (const :tag "Never" nil)
  2118. (const :tag "Check month and day" t)
  2119. (const :tag "Check month, day, and time" time)))
  2120. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2121. "Should the agenda jump command prefer the future for incomplete dates?
  2122. The default is to do the same as configured in `org-read-date-prefer-future'.
  2123. But you can also set a deviating value here.
  2124. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2125. :group 'org-agenda
  2126. :group 'org-time
  2127. :version "24.1"
  2128. :type '(choice
  2129. (const :tag "Use org-read-date-prefer-future"
  2130. org-read-date-prefer-future)
  2131. (const :tag "Never" nil)
  2132. (const :tag "Always" t)))
  2133. (defcustom org-read-date-force-compatible-dates t
  2134. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2135. Depending on the system Emacs is running on, certain dates cannot
  2136. be represented with the type used internally to represent time.
  2137. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2138. correctly. Some systems allow for earlier dates, some for later,
  2139. some for both. One way to find out is to insert any date into an
  2140. Org buffer, putting the cursor on the year and hitting S-up and
  2141. S-down to test the range.
  2142. When this variable is set to t, the date/time prompt will not let
  2143. you specify dates outside the 1970-2037 range, so it is certain that
  2144. these dates will work in whatever version of Emacs you are
  2145. running, and also that you can move a file from one Emacs implementation
  2146. to another. Whenever Org is forcing the year for you, it will display
  2147. a message and beep.
  2148. When this variable is nil, Org will check if the date is
  2149. representable in the specific Emacs implementation you are using.
  2150. If not, it will force a year, usually the current year, and beep
  2151. to remind you. Currently this setting is not recommended because
  2152. the likelihood that you will open your Org files in an Emacs that
  2153. has limited date range is not negligible.
  2154. A workaround for this problem is to use diary sexp dates for time
  2155. stamps outside of this range."
  2156. :group 'org-time
  2157. :version "24.1"
  2158. :type 'boolean)
  2159. (defcustom org-read-date-display-live t
  2160. "Non-nil means display current interpretation of date prompt live.
  2161. This display will be in an overlay, in the minibuffer. Note that
  2162. live display is only active when `org-read-date-popup-calendar'
  2163. is non-nil."
  2164. :group 'org-time
  2165. :type 'boolean)
  2166. (defvaralias 'org-popup-calendar-for-date-prompt
  2167. 'org-read-date-popup-calendar)
  2168. (defcustom org-read-date-popup-calendar t
  2169. "Non-nil means pop up a calendar when prompting for a date.
  2170. In the calendar, the date can be selected with mouse-1. However, the
  2171. minibuffer will also be active, and you can simply enter the date as well.
  2172. When nil, only the minibuffer will be available."
  2173. :group 'org-time
  2174. :type 'boolean)
  2175. (defcustom org-extend-today-until 0
  2176. "The hour when your day really ends. Must be an integer.
  2177. This has influence for the following applications:
  2178. - When switching the agenda to \"today\". If it is still earlier than
  2179. the time given here, the day recognized as TODAY is actually yesterday.
  2180. - When a date is read from the user and it is still before the time given
  2181. here, the current date and time will be assumed to be yesterday, 23:59.
  2182. Also, timestamps inserted in capture templates follow this rule.
  2183. IMPORTANT: This is a feature whose implementation is and likely will
  2184. remain incomplete. Really, it is only here because past midnight seems to
  2185. be the favorite working time of John Wiegley :-)"
  2186. :group 'org-time
  2187. :type 'integer)
  2188. (defcustom org-use-effective-time nil
  2189. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2190. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2191. \"effective time\" of any timestamps between midnight and 8am will be
  2192. 23:59 of the previous day."
  2193. :group 'org-time
  2194. :version "24.1"
  2195. :type 'boolean)
  2196. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2197. "When non-nil, use the last clock out time for `org-todo'.
  2198. Note that this option has precedence over the combined use of
  2199. `org-use-effective-time' and `org-extend-today-until'."
  2200. :group 'org-time
  2201. :version "24.4"
  2202. :package-version '(Org . "8.0")
  2203. :type 'boolean)
  2204. (defcustom org-edit-timestamp-down-means-later nil
  2205. "Non-nil means S-down will increase the time in a time stamp.
  2206. When nil, S-up will increase."
  2207. :group 'org-time
  2208. :type 'boolean)
  2209. (defcustom org-calendar-follow-timestamp-change t
  2210. "Non-nil means make the calendar window follow timestamp changes.
  2211. When a timestamp is modified and the calendar window is visible, it will be
  2212. moved to the new date."
  2213. :group 'org-time
  2214. :type 'boolean)
  2215. (defgroup org-tags nil
  2216. "Options concerning tags in Org mode."
  2217. :tag "Org Tags"
  2218. :group 'org)
  2219. (defcustom org-tag-alist nil
  2220. "Default tags available in Org files.
  2221. The value of this variable is an alist. Associations either:
  2222. (TAG)
  2223. (TAG . SELECT)
  2224. (SPECIAL)
  2225. where TAG is a tag as a string, SELECT is character, used to
  2226. select that tag through the fast tag selection interface, and
  2227. SPECIAL is one of the following keywords: `:startgroup',
  2228. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2229. `:newline'. These keywords are used to define a hierarchy of
  2230. tags. See manual for details.
  2231. When this variable is nil, Org mode bases tag input on what is
  2232. already in the buffer. The value can be overridden locally by
  2233. using a TAGS keyword, e.g.,
  2234. #+TAGS: tag1 tag2
  2235. See also `org-tag-persistent-alist' to sidestep this behavior."
  2236. :group 'org-tags
  2237. :type '(repeat
  2238. (choice
  2239. (cons :tag "Tag with key"
  2240. (string :tag "Tag name")
  2241. (character :tag "Access char"))
  2242. (list :tag "Tag" (string :tag "Tag name"))
  2243. (const :tag "Start radio group" (:startgroup))
  2244. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2245. (const :tag "Group tags delimiter" (:grouptags))
  2246. (const :tag "End radio group" (:endgroup))
  2247. (const :tag "End tag group, non distinct" (:endgrouptag))
  2248. (const :tag "New line" (:newline)))))
  2249. (defcustom org-tag-persistent-alist nil
  2250. "Tags always available in Org files.
  2251. The value of this variable is an alist. Associations either:
  2252. (TAG)
  2253. (TAG . SELECT)
  2254. (SPECIAL)
  2255. where TAG is a tag as a string, SELECT is a character, used to
  2256. select that tag through the fast tag selection interface, and
  2257. SPECIAL is one of the following keywords: `:startgroup',
  2258. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2259. `:newline'. These keywords are used to define a hierarchy of
  2260. tags. See manual for details.
  2261. Unlike to `org-tag-alist', tags defined in this variable do not
  2262. depend on a local TAGS keyword. Instead, to disable these tags
  2263. on a per-file basis, insert anywhere in the file:
  2264. #+STARTUP: noptag"
  2265. :group 'org-tags
  2266. :type '(repeat
  2267. (choice
  2268. (cons :tag "Tag with key"
  2269. (string :tag "Tag name")
  2270. (character :tag "Access char"))
  2271. (list :tag "Tag" (string :tag "Tag name"))
  2272. (const :tag "Start radio group" (:startgroup))
  2273. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2274. (const :tag "Group tags delimiter" (:grouptags))
  2275. (const :tag "End radio group" (:endgroup))
  2276. (const :tag "End tag group, non distinct" (:endgrouptag))
  2277. (const :tag "New line" (:newline)))))
  2278. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2279. "If non-nil, always offer completion for all tags of all agenda files.
  2280. Setting this variable locally allows for dynamic generation of tag
  2281. completions in capture buffers.
  2282. (add-hook \\='org-capture-mode-hook
  2283. (lambda ()
  2284. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2285. :group 'org-tags
  2286. :version "24.1"
  2287. :type 'boolean)
  2288. (defvar org-file-tags nil
  2289. "List of tags that can be inherited by all entries in the file.
  2290. The tags will be inherited if the variable `org-use-tag-inheritance'
  2291. says they should be.
  2292. This variable is populated from #+FILETAGS lines.")
  2293. (defcustom org-use-fast-tag-selection 'auto
  2294. "Non-nil means use fast tag selection scheme.
  2295. This is a special interface to select and deselect tags with single keys.
  2296. When nil, fast selection is never used.
  2297. When the symbol `auto', fast selection is used if and only if selection
  2298. characters for tags have been configured, either through the variable
  2299. `org-tag-alist' or through a #+TAGS line in the buffer.
  2300. When t, fast selection is always used and selection keys are assigned
  2301. automatically if necessary."
  2302. :group 'org-tags
  2303. :type '(choice
  2304. (const :tag "Always" t)
  2305. (const :tag "Never" nil)
  2306. (const :tag "When selection characters are configured" auto)))
  2307. (defcustom org-fast-tag-selection-single-key nil
  2308. "Non-nil means fast tag selection exits after first change.
  2309. When nil, you have to press RET to exit it.
  2310. During fast tag selection, you can toggle this flag with `C-c'.
  2311. This variable can also have the value `expert'. In this case, the window
  2312. displaying the tags menu is not even shown, until you press `C-c' again."
  2313. :group 'org-tags
  2314. :type '(choice
  2315. (const :tag "No" nil)
  2316. (const :tag "Yes" t)
  2317. (const :tag "Expert" expert)))
  2318. (defvar org-fast-tag-selection-include-todo nil
  2319. "Non-nil means fast tags selection interface will also offer TODO states.
  2320. This is an undocumented feature, you should not rely on it.")
  2321. (defcustom org-tags-column -77
  2322. "The column to which tags should be indented in a headline.
  2323. If this number is positive, it specifies the column. If it is negative,
  2324. it means that the tags should be flushright to that column. For example,
  2325. -80 works well for a normal 80 character screen.
  2326. When 0, place tags directly after headline text, with only one space in
  2327. between."
  2328. :group 'org-tags
  2329. :type 'integer)
  2330. (defcustom org-auto-align-tags t
  2331. "Non-nil keeps tags aligned when modifying headlines.
  2332. Some operations (i.e. demoting) change the length of a headline and
  2333. therefore shift the tags around. With this option turned on, after
  2334. each such operation the tags are again aligned to `org-tags-column'."
  2335. :group 'org-tags
  2336. :type 'boolean)
  2337. (defcustom org-use-tag-inheritance t
  2338. "Non-nil means tags in levels apply also for sublevels.
  2339. When nil, only the tags directly given in a specific line apply there.
  2340. This may also be a list of tags that should be inherited, or a regexp that
  2341. matches tags that should be inherited. Additional control is possible
  2342. with the variable `org-tags-exclude-from-inheritance' which gives an
  2343. explicit list of tags to be excluded from inheritance, even if the value of
  2344. `org-use-tag-inheritance' would select it for inheritance.
  2345. If this option is t, a match early-on in a tree can lead to a large
  2346. number of matches in the subtree when constructing the agenda or creating
  2347. a sparse tree. If you only want to see the first match in a tree during
  2348. a search, check out the variable `org-tags-match-list-sublevels'."
  2349. :group 'org-tags
  2350. :type '(choice
  2351. (const :tag "Not" nil)
  2352. (const :tag "Always" t)
  2353. (repeat :tag "Specific tags" (string :tag "Tag"))
  2354. (regexp :tag "Tags matched by regexp")))
  2355. (defcustom org-tags-exclude-from-inheritance nil
  2356. "List of tags that should never be inherited.
  2357. This is a way to exclude a few tags from inheritance. For way to do
  2358. the opposite, to actively allow inheritance for selected tags,
  2359. see the variable `org-use-tag-inheritance'."
  2360. :group 'org-tags
  2361. :type '(repeat (string :tag "Tag")))
  2362. (defun org-tag-inherit-p (tag)
  2363. "Check if TAG is one that should be inherited."
  2364. (cond
  2365. ((member tag org-tags-exclude-from-inheritance) nil)
  2366. ((eq org-use-tag-inheritance t) t)
  2367. ((not org-use-tag-inheritance) nil)
  2368. ((stringp org-use-tag-inheritance)
  2369. (string-match org-use-tag-inheritance tag))
  2370. ((listp org-use-tag-inheritance)
  2371. (member tag org-use-tag-inheritance))
  2372. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2373. (defcustom org-tags-match-list-sublevels t
  2374. "Non-nil means list also sublevels of headlines matching a search.
  2375. This variable applies to tags/property searches, and also to stuck
  2376. projects because this search is based on a tags match as well.
  2377. When set to the symbol `indented', sublevels are indented with
  2378. leading dots.
  2379. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2380. the sublevels of a headline matching a tag search often also match
  2381. the same search. Listing all of them can create very long lists.
  2382. Setting this variable to nil causes subtrees of a match to be skipped.
  2383. This variable is semi-obsolete and probably should always be true. It
  2384. is better to limit inheritance to certain tags using the variables
  2385. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2386. :group 'org-tags
  2387. :type '(choice
  2388. (const :tag "No, don't list them" nil)
  2389. (const :tag "Yes, do list them" t)
  2390. (const :tag "List them, indented with leading dots" indented)))
  2391. (defcustom org-tags-sort-function nil
  2392. "When set, tags are sorted using this function as a comparator."
  2393. :group 'org-tags
  2394. :type '(choice
  2395. (const :tag "No sorting" nil)
  2396. (const :tag "Alphabetical" string-collate-lessp)
  2397. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2398. (function :tag "Custom function" nil)))
  2399. (defvar org-tags-history nil
  2400. "History of minibuffer reads for tags.")
  2401. (defvar org-last-tags-completion-table nil
  2402. "The last used completion table for tags.")
  2403. (defvar org-after-tags-change-hook nil
  2404. "Hook that is run after the tags in a line have changed.")
  2405. (defgroup org-properties nil
  2406. "Options concerning properties in Org mode."
  2407. :tag "Org Properties"
  2408. :group 'org)
  2409. (defcustom org-property-format "%-10s %s"
  2410. "How property key/value pairs should be formatted by `indent-line'.
  2411. When `indent-line' hits a property definition, it will format the line
  2412. according to this format, mainly to make sure that the values are
  2413. lined-up with respect to each other."
  2414. :group 'org-properties
  2415. :type 'string)
  2416. (defcustom org-properties-postprocess-alist nil
  2417. "Alist of properties and functions to adjust inserted values.
  2418. Elements of this alist must be of the form
  2419. ([string] [function])
  2420. where [string] must be a property name and [function] must be a
  2421. lambda expression: this lambda expression must take one argument,
  2422. the value to adjust, and return the new value as a string.
  2423. For example, this element will allow the property \"Remaining\"
  2424. to be updated wrt the relation between the \"Effort\" property
  2425. and the clock summary:
  2426. ((\"Remaining\" (lambda(value)
  2427. (let ((clocksum (org-clock-sum-current-item))
  2428. (effort (org-duration-to-minutes
  2429. (org-entry-get (point) \"Effort\"))))
  2430. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2431. :group 'org-properties
  2432. :version "24.1"
  2433. :type '(alist :key-type (string :tag "Property")
  2434. :value-type (function :tag "Function")))
  2435. (defcustom org-use-property-inheritance nil
  2436. "Non-nil means properties apply also for sublevels.
  2437. This setting is chiefly used during property searches. Turning it on can
  2438. cause significant overhead when doing a search, which is why it is not
  2439. on by default.
  2440. When nil, only the properties directly given in the current entry count.
  2441. When t, every property is inherited. The value may also be a list of
  2442. properties that should have inheritance, or a regular expression matching
  2443. properties that should be inherited.
  2444. However, note that some special properties use inheritance under special
  2445. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2446. and the properties ending in \"_ALL\" when they are used as descriptor
  2447. for valid values of a property.
  2448. Note for programmers:
  2449. When querying an entry with `org-entry-get', you can control if inheritance
  2450. should be used. By default, `org-entry-get' looks only at the local
  2451. properties. You can request inheritance by setting the inherit argument
  2452. to t (to force inheritance) or to `selective' (to respect the setting
  2453. in this variable)."
  2454. :group 'org-properties
  2455. :type '(choice
  2456. (const :tag "Not" nil)
  2457. (const :tag "Always" t)
  2458. (repeat :tag "Specific properties" (string :tag "Property"))
  2459. (regexp :tag "Properties matched by regexp")))
  2460. (defun org-property-inherit-p (property)
  2461. "Return a non-nil value if PROPERTY should be inherited."
  2462. (cond
  2463. ((eq org-use-property-inheritance t) t)
  2464. ((not org-use-property-inheritance) nil)
  2465. ((stringp org-use-property-inheritance)
  2466. (string-match org-use-property-inheritance property))
  2467. ((listp org-use-property-inheritance)
  2468. (member-ignore-case property org-use-property-inheritance))
  2469. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2470. (defcustom org-property-separators nil
  2471. "An alist to control how properties are combined.
  2472. The car of each item should be either a list of property names or
  2473. a regular expression, while the cdr should be the separator to
  2474. use when combining that property.
  2475. If an alist item cannot be found that matches a given property, a
  2476. single space will be used as the separator."
  2477. :group 'org-properties
  2478. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2479. (string :tag "Regular Expression"))
  2480. :value-type (restricted-sexp :tag "Separator"
  2481. :match-alternatives (stringp)
  2482. :value " ")))
  2483. (defun org--property-get-separator (property)
  2484. "Get the separator to use for combining PROPERTY."
  2485. (or
  2486. (catch 'separator
  2487. (dolist (spec org-property-separators)
  2488. (if (listp (car spec))
  2489. (if (member property (car spec))
  2490. (throw 'separator (cdr spec)))
  2491. (if (string-match-p (car spec) property)
  2492. (throw 'separator (cdr spec))))))
  2493. " "))
  2494. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2495. "The default column format, if no other format has been defined.
  2496. This variable can be set on the per-file basis by inserting a line
  2497. #+COLUMNS: %25ITEM ....."
  2498. :group 'org-properties
  2499. :type 'string)
  2500. (defcustom org-columns-default-format-for-agenda nil
  2501. "The default column format in an agenda buffer.
  2502. This will be used for column view in the agenda unless a format has
  2503. been set by adding `org-overriding-columns-format' to the local
  2504. settings list of a custom agenda view. When nil, the columns format
  2505. for the first item in the agenda list will be used, or as a fall-back,
  2506. `org-columns-default-format'."
  2507. :group 'org-properties
  2508. :type '(choice
  2509. (const :tag "No default" nil)
  2510. (string :tag "Format string")))
  2511. (defcustom org-columns-ellipses ".."
  2512. "The ellipses to be used when a field in column view is truncated.
  2513. When this is the empty string, as many characters as possible are shown,
  2514. but then there will be no visual indication that the field has been truncated.
  2515. When this is a string of length N, the last N characters of a truncated
  2516. field are replaced by this string. If the column is narrower than the
  2517. ellipses string, only part of the ellipses string will be shown."
  2518. :group 'org-properties
  2519. :type 'string)
  2520. (defconst org-global-properties-fixed
  2521. '(("VISIBILITY_ALL" . "folded children content all")
  2522. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2523. "List of property/value pairs that can be inherited by any entry.
  2524. These are fixed values, for the preset properties. The user variable
  2525. that can be used to add to this list is `org-global-properties'.
  2526. The entries in this list are cons cells where the car is a property
  2527. name and cdr is a string with the value. If the value represents
  2528. multiple items like an \"_ALL\" property, separate the items by
  2529. spaces.")
  2530. (defcustom org-global-properties nil
  2531. "List of property/value pairs that can be inherited by any entry.
  2532. This list will be combined with the constant `org-global-properties-fixed'.
  2533. The entries in this list are cons cells where the car is a property
  2534. name and cdr is a string with the value.
  2535. Buffer local properties are added either by a document property drawer
  2536. :PROPERTIES:
  2537. :NAME: VALUE
  2538. :END:
  2539. or by adding lines like
  2540. #+PROPERTY: NAME VALUE"
  2541. :group 'org-properties
  2542. :type '(repeat
  2543. (cons (string :tag "Property")
  2544. (string :tag "Value"))))
  2545. (defvar-local org-keyword-properties nil
  2546. "List of property/value pairs inherited by any entry.
  2547. Valid for the current buffer. This variable is populated from
  2548. PROPERTY keywords.
  2549. Note that properties are defined also in property drawers.
  2550. Properties defined there take precedence over properties defined
  2551. as keywords.")
  2552. (defgroup org-agenda nil
  2553. "Options concerning agenda views in Org mode."
  2554. :tag "Org Agenda"
  2555. :group 'org)
  2556. (defvar-local org-category nil
  2557. "Variable used by Org files to set a category for agenda display.
  2558. There are multiple ways to set the category. One way is to set
  2559. it in the document property drawer. For example:
  2560. :PROPERTIES:
  2561. :CATEGORY: ELisp
  2562. :END:
  2563. Other ways to define it is as an Emacs file variable, for example
  2564. # -*- mode: org; org-category: \"ELisp\"
  2565. or for the file to contain a special line:
  2566. #+CATEGORY: ELisp
  2567. If the file does not specify a category, then file's base name
  2568. is used instead.")
  2569. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2570. (defcustom org-agenda-files nil
  2571. "The files to be used for agenda display.
  2572. If an entry is a directory, all files in that directory that are matched
  2573. by `org-agenda-file-regexp' will be part of the file list.
  2574. If the value of the variable is not a list but a single file name, then
  2575. the list of agenda files is actually stored and maintained in that file,
  2576. one agenda file per line. In this file paths can be given relative to
  2577. `org-directory'. Tilde expansion and environment variable substitution
  2578. are also made.
  2579. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2580. and removed with `\\[org-remove-file]'."
  2581. :group 'org-agenda
  2582. :type '(choice
  2583. (repeat :tag "List of files and directories" file)
  2584. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2585. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2586. "Regular expression to match files for `org-agenda-files'.
  2587. If any element in the list in that variable contains a directory instead
  2588. of a normal file, all files in that directory that are matched by this
  2589. regular expression will be included."
  2590. :group 'org-agenda
  2591. :type 'regexp)
  2592. (defvaralias 'org-agenda-multi-occur-extra-files
  2593. 'org-agenda-text-search-extra-files)
  2594. (defcustom org-agenda-text-search-extra-files nil
  2595. "List of extra files to be searched by text search commands.
  2596. These files will be searched in addition to the agenda files by the
  2597. commands `org-search-view' (`\\[org-agenda] s') \
  2598. and `org-occur-in-agenda-files'.
  2599. Note that these files will only be searched for text search commands,
  2600. not for the other agenda views like todo lists, tag searches or the weekly
  2601. agenda. This variable is intended to list notes and possibly archive files
  2602. that should also be searched by these two commands.
  2603. In fact, if the first element in the list is the symbol `agenda-archives',
  2604. then all archive files of all agenda files will be added to the search
  2605. scope."
  2606. :group 'org-agenda
  2607. :type '(set :greedy t
  2608. (const :tag "Agenda Archives" agenda-archives)
  2609. (repeat :inline t (file))))
  2610. (defcustom org-agenda-skip-unavailable-files nil
  2611. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2612. A nil value means to remove them, after a query, from the list."
  2613. :group 'org-agenda
  2614. :type 'boolean)
  2615. (defgroup org-latex nil
  2616. "Options for embedding LaTeX code into Org mode."
  2617. :tag "Org LaTeX"
  2618. :group 'org)
  2619. (defcustom org-format-latex-options
  2620. '(:foreground default :background default :scale 1.0
  2621. :html-foreground "Black" :html-background "Transparent"
  2622. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2623. "Options for creating images from LaTeX fragments.
  2624. This is a property list with the following properties:
  2625. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2626. `default' means use the foreground of the default face.
  2627. `auto' means use the foreground from the text face.
  2628. :background the background color, or \"Transparent\".
  2629. `default' means use the background of the default face.
  2630. `auto' means use the background from the text face.
  2631. :scale a scaling factor for the size of the images, to get more pixels
  2632. :html-foreground, :html-background, :html-scale
  2633. the same numbers for HTML export.
  2634. :matchers a list indicating which matchers should be used to
  2635. find LaTeX fragments. Valid members of this list are:
  2636. \"begin\" find environments
  2637. \"$1\" find single characters surrounded by $.$
  2638. \"$\" find math expressions surrounded by $...$
  2639. \"$$\" find math expressions surrounded by $$....$$
  2640. \"\\(\" find math expressions surrounded by \\(...\\)
  2641. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2642. :group 'org-latex
  2643. :type 'plist)
  2644. (defcustom org-format-latex-signal-error t
  2645. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2646. When nil, just push out a message."
  2647. :group 'org-latex
  2648. :version "24.1"
  2649. :type 'boolean)
  2650. (defcustom org-latex-to-mathml-jar-file nil
  2651. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2652. Use this to specify additional executable file say a jar file.
  2653. When using MathToWeb as the converter, specify the full-path to
  2654. your mathtoweb.jar file."
  2655. :group 'org-latex
  2656. :version "24.1"
  2657. :type '(choice
  2658. (const :tag "None" nil)
  2659. (file :tag "JAR file" :must-match t)))
  2660. (defcustom org-latex-to-mathml-convert-command nil
  2661. "Command to convert LaTeX fragments to MathML.
  2662. Replace format-specifiers in the command as noted below and use
  2663. `shell-command' to convert LaTeX to MathML.
  2664. %j: Executable file in fully expanded form as specified by
  2665. `org-latex-to-mathml-jar-file'.
  2666. %I: Input LaTeX file in fully expanded form.
  2667. %i: The latex fragment to be converted.
  2668. %o: Output MathML file.
  2669. This command is used by `org-create-math-formula'.
  2670. When using MathToWeb as the converter, set this option to
  2671. \"java -jar %j -unicode -force -df %o %I\".
  2672. When using LaTeXML set this option to
  2673. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2674. :group 'org-latex
  2675. :version "24.1"
  2676. :type '(choice
  2677. (const :tag "None" nil)
  2678. (string :tag "\nShell command")))
  2679. (defcustom org-latex-to-html-convert-command nil
  2680. "Command to convert LaTeX fragments to HTML.
  2681. This command is very open-ended: the output of the command will
  2682. directly replace the LaTeX fragment in the resulting HTML.
  2683. Replace format-specifiers in the command as noted below and use
  2684. `shell-command' to convert LaTeX to HTML.
  2685. %i: The LaTeX fragment to be converted.
  2686. For example, this could be used with LaTeXML as
  2687. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2688. :group 'org-latex
  2689. :package-version '(Org . "9.4")
  2690. :type '(choice
  2691. (const :tag "None" nil)
  2692. (string :tag "Shell command")))
  2693. (defcustom org-preview-latex-default-process 'dvipng
  2694. "The default process to convert LaTeX fragments to image files.
  2695. All available processes and theirs documents can be found in
  2696. `org-preview-latex-process-alist', which see."
  2697. :group 'org-latex
  2698. :version "26.1"
  2699. :package-version '(Org . "9.0")
  2700. :type 'symbol)
  2701. (defcustom org-preview-latex-process-alist
  2702. '((dvipng
  2703. :programs ("latex" "dvipng")
  2704. :description "dvi > png"
  2705. :message "you need to install the programs: latex and dvipng."
  2706. :image-input-type "dvi"
  2707. :image-output-type "png"
  2708. :image-size-adjust (1.0 . 1.0)
  2709. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2710. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2711. :transparent-image-converter
  2712. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2713. (dvisvgm
  2714. :programs ("latex" "dvisvgm")
  2715. :description "dvi > svg"
  2716. :message "you need to install the programs: latex and dvisvgm."
  2717. :image-input-type "dvi"
  2718. :image-output-type "svg"
  2719. :image-size-adjust (1.7 . 1.5)
  2720. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2721. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2722. (imagemagick
  2723. :programs ("latex" "convert")
  2724. :description "pdf > png"
  2725. :message "you need to install the programs: latex and imagemagick."
  2726. :image-input-type "pdf"
  2727. :image-output-type "png"
  2728. :image-size-adjust (1.0 . 1.0)
  2729. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2730. :image-converter
  2731. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2732. "Definitions of external processes for LaTeX previewing.
  2733. Org mode can use some external commands to generate TeX snippet's images for
  2734. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2735. `org-create-formula-image' how to call them.
  2736. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2737. PROPERTIES accepts the following attributes:
  2738. :programs list of strings, required programs.
  2739. :description string, describe the process.
  2740. :message string, message it when required programs cannot be found.
  2741. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2742. :image-output-type string, output file type of image converter (e.g., \"png\").
  2743. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2744. image size showed in buffer and the cdr element is for
  2745. HTML file. This option is only useful for process
  2746. developers, users should use variable
  2747. `org-format-latex-options' instead.
  2748. :post-clean list of strings, files matched are to be cleaned up once
  2749. the image is generated. When nil, the files with \".dvi\",
  2750. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2751. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2752. be cleaned up.
  2753. :latex-header list of strings, the LaTeX header of the snippet file.
  2754. When nil, the fallback value is used instead, which is
  2755. controlled by `org-format-latex-header',
  2756. `org-latex-default-packages-alist' and
  2757. `org-latex-packages-alist', which see.
  2758. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2759. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2760. replaced with values defined below.
  2761. :image-converter list of image converter commands strings. Each of them is
  2762. given to the shell and supports any of the following
  2763. place-holders defined below.
  2764. If set, :transparent-image-converter is used instead of :image-converter to
  2765. convert an image when the background color is nil or \"Transparent\".
  2766. Place-holders used by `:image-converter' and `:latex-compiler':
  2767. %f input file name
  2768. %b base name of input file
  2769. %o base directory of input file
  2770. %O absolute output file name
  2771. Place-holders only used by `:image-converter':
  2772. %D dpi, which is used to adjust image size by some processing commands.
  2773. %S the image size scale ratio, which is used to adjust image size by some
  2774. processing commands."
  2775. :group 'org-latex
  2776. :version "26.1"
  2777. :package-version '(Org . "9.0")
  2778. :type '(alist :tag "LaTeX to image backends"
  2779. :value-type (plist)))
  2780. (defcustom org-preview-latex-image-directory "ltximg/"
  2781. "Path to store latex preview images.
  2782. A relative path here creates many directories relative to the
  2783. processed Org files paths. An absolute path puts all preview
  2784. images at the same place."
  2785. :group 'org-latex
  2786. :version "26.1"
  2787. :package-version '(Org . "9.0")
  2788. :type 'string)
  2789. (defun org-format-latex-mathml-available-p ()
  2790. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2791. (save-match-data
  2792. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2793. org-latex-to-mathml-convert-command)
  2794. (let ((executable (car (split-string
  2795. org-latex-to-mathml-convert-command))))
  2796. (when (executable-find executable)
  2797. (if (string-match
  2798. "%j" org-latex-to-mathml-convert-command)
  2799. (file-readable-p org-latex-to-mathml-jar-file)
  2800. t))))))
  2801. (defcustom org-format-latex-header "\\documentclass{article}
  2802. \\usepackage[usenames]{color}
  2803. \[DEFAULT-PACKAGES]
  2804. \[PACKAGES]
  2805. \\pagestyle{empty} % do not remove
  2806. % The settings below are copied from fullpage.sty
  2807. \\setlength{\\textwidth}{\\paperwidth}
  2808. \\addtolength{\\textwidth}{-3cm}
  2809. \\setlength{\\oddsidemargin}{1.5cm}
  2810. \\addtolength{\\oddsidemargin}{-2.54cm}
  2811. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2812. \\setlength{\\textheight}{\\paperheight}
  2813. \\addtolength{\\textheight}{-\\headheight}
  2814. \\addtolength{\\textheight}{-\\headsep}
  2815. \\addtolength{\\textheight}{-\\footskip}
  2816. \\addtolength{\\textheight}{-3cm}
  2817. \\setlength{\\topmargin}{1.5cm}
  2818. \\addtolength{\\topmargin}{-2.54cm}"
  2819. "The document header used for processing LaTeX fragments.
  2820. It is imperative that this header make sure that no page number
  2821. appears on the page. The package defined in the variables
  2822. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2823. will either replace the placeholder \"[PACKAGES]\" in this
  2824. header, or they will be appended."
  2825. :group 'org-latex
  2826. :type 'string)
  2827. (defun org-set-packages-alist (var val)
  2828. "Set the packages alist and make sure it has 3 elements per entry."
  2829. (set-default-toplevel-value var (mapcar (lambda (x)
  2830. (if (and (consp x) (= (length x) 2))
  2831. (list (car x) (nth 1 x) t)
  2832. x))
  2833. val)))
  2834. (defun org-get-packages-alist (var)
  2835. "Get the packages alist and make sure it has 3 elements per entry."
  2836. (mapcar (lambda (x)
  2837. (if (and (consp x) (= (length x) 2))
  2838. (list (car x) (nth 1 x) t)
  2839. x))
  2840. (default-value var)))
  2841. (defcustom org-latex-default-packages-alist
  2842. '(("AUTO" "inputenc" t ("pdflatex"))
  2843. ("T1" "fontenc" t ("pdflatex"))
  2844. ("" "graphicx" t)
  2845. ("" "longtable" nil)
  2846. ("" "wrapfig" nil)
  2847. ("" "rotating" nil)
  2848. ("normalem" "ulem" t)
  2849. ("" "amsmath" t)
  2850. ("" "amssymb" t)
  2851. ("" "capt-of" nil)
  2852. ("" "hyperref" nil))
  2853. "Alist of default packages to be inserted in the header.
  2854. Change this only if one of the packages here causes an
  2855. incompatibility with another package you are using.
  2856. The packages in this list are needed by one part or another of
  2857. Org mode to function properly:
  2858. - inputenc, fontenc: for basic font and character selection
  2859. - graphicx: for including images
  2860. - longtable: For multipage tables
  2861. - wrapfig: for figure placement
  2862. - rotating: for sideways figures and tables
  2863. - ulem: for underline and strike-through
  2864. - amsmath: for subscript and superscript and math environments
  2865. - amssymb: for various symbols used for interpreting the entities
  2866. in `org-entities'. You can skip some of this package if you don't
  2867. use any of the symbols.
  2868. - capt-of: for captions outside of floats
  2869. - hyperref: for cross references
  2870. Therefore you should not modify this variable unless you know
  2871. what you are doing. The one reason to change it anyway is that
  2872. you might be loading some other package that conflicts with one
  2873. of the default packages. Each element is either a cell or
  2874. a string.
  2875. A cell is of the format
  2876. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2877. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2878. when compiling LaTeX snippets into images for inclusion into
  2879. non-LaTeX output.
  2880. COMPILERS is a list of compilers that should include the package,
  2881. see `org-latex-compiler'. If the document compiler is not in the
  2882. list, and the list is non-nil, the package will not be inserted
  2883. in the final document.
  2884. A string will be inserted as-is in the header of the document."
  2885. :group 'org-latex
  2886. :group 'org-export-latex
  2887. :set 'org-set-packages-alist
  2888. :get 'org-get-packages-alist
  2889. :version "26.1"
  2890. :package-version '(Org . "8.3")
  2891. :type '(repeat
  2892. (choice
  2893. (list :tag "options/package pair"
  2894. (string :tag "options")
  2895. (string :tag "package")
  2896. (boolean :tag "Snippet")
  2897. (choice
  2898. (const :tag "For all compilers" nil)
  2899. (repeat :tag "Allowed compiler" string)))
  2900. (string :tag "A line of LaTeX"))))
  2901. (defcustom org-latex-packages-alist nil
  2902. "Alist of packages to be inserted in every LaTeX header.
  2903. These will be inserted after `org-latex-default-packages-alist'.
  2904. Each element is either a cell or a string.
  2905. A cell is of the format:
  2906. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2907. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2908. needed when turning LaTeX snippets into images for inclusion into
  2909. non-LaTeX output.
  2910. COMPILERS is a list of compilers that should include the package,
  2911. see `org-latex-compiler'. If the document compiler is not in the
  2912. list, and the list is non-nil, the package will not be inserted
  2913. in the final document.
  2914. A string will be inserted as-is in the header of the document.
  2915. Make sure that you only list packages here which:
  2916. - you want in every file;
  2917. - do not conflict with the setup in `org-format-latex-header';
  2918. - do not conflict with the default packages in
  2919. `org-latex-default-packages-alist'."
  2920. :group 'org-latex
  2921. :group 'org-export-latex
  2922. :set 'org-set-packages-alist
  2923. :get 'org-get-packages-alist
  2924. :type '(repeat
  2925. (choice
  2926. (list :tag "options/package pair"
  2927. (string :tag "options")
  2928. (string :tag "package")
  2929. (boolean :tag "Snippet"))
  2930. (string :tag "A line of LaTeX"))))
  2931. (defgroup org-appearance nil
  2932. "Settings for Org mode appearance."
  2933. :tag "Org Appearance"
  2934. :group 'org)
  2935. (defcustom org-level-color-stars-only nil
  2936. "Non-nil means fontify only the stars in each headline.
  2937. When nil, the entire headline is fontified.
  2938. Changing it requires restart of `font-lock-mode' to become effective
  2939. also in regions already fontified."
  2940. :group 'org-appearance
  2941. :type 'boolean)
  2942. (defcustom org-hide-leading-stars nil
  2943. "Non-nil means hide the first N-1 stars in a headline.
  2944. This works by using the face `org-hide' for these stars. This
  2945. face is white for a light background, and black for a dark
  2946. background. You may have to customize the face `org-hide' to
  2947. make this work.
  2948. Changing it requires restart of `font-lock-mode' to become effective
  2949. also in regions already fontified.
  2950. You may also set this on a per-file basis by adding one of the following
  2951. lines to the buffer:
  2952. #+STARTUP: hidestars
  2953. #+STARTUP: showstars"
  2954. :group 'org-appearance
  2955. :type 'boolean)
  2956. (defcustom org-hidden-keywords nil
  2957. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2958. For example, a value (title) for this list makes the document's title
  2959. appear in the buffer without the initial \"#+TITLE:\" part."
  2960. :group 'org-appearance
  2961. :package-version '(Org . "9.5")
  2962. :type '(set (const :tag "#+AUTHOR" author)
  2963. (const :tag "#+DATE" date)
  2964. (const :tag "#+EMAIL" email)
  2965. (const :tag "#+SUBTITLE" subtitle)
  2966. (const :tag "#+TITLE" title)))
  2967. (defcustom org-custom-properties nil
  2968. "List of properties (as strings) with a special meaning.
  2969. The default use of these custom properties is to let the user
  2970. hide them with `org-toggle-custom-properties-visibility'."
  2971. :group 'org-properties
  2972. :group 'org-appearance
  2973. :version "24.3"
  2974. :type '(repeat (string :tag "Property Name")))
  2975. (defcustom org-fontify-todo-headline nil
  2976. "Non-nil means change the face of a headline if it is marked as TODO.
  2977. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2978. When this is non-nil, the headline after the keyword is set to the
  2979. `org-headline-todo' as an additional indication."
  2980. :group 'org-appearance
  2981. :package-version '(Org . "9.4")
  2982. :type 'boolean
  2983. :safe #'booleanp)
  2984. (defcustom org-fontify-done-headline t
  2985. "Non-nil means change the face of a headline if it is marked DONE.
  2986. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2987. When this is non-nil, the headline after the keyword is set to the
  2988. `org-headline-done' as an additional indication."
  2989. :group 'org-appearance
  2990. :package-version '(Org . "9.4")
  2991. :type 'boolean)
  2992. (defcustom org-fontify-emphasized-text t
  2993. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  2994. Changing this variable requires a restart of Emacs to take effect."
  2995. :group 'org-appearance
  2996. :type 'boolean)
  2997. (defcustom org-fontify-whole-heading-line nil
  2998. "Non-nil means fontify the whole line for headings.
  2999. This is useful when setting a background color for the
  3000. org-level-* faces."
  3001. :group 'org-appearance
  3002. :type 'boolean)
  3003. (defcustom org-fontify-whole-block-delimiter-line t
  3004. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3005. This is useful when setting a background color for the
  3006. org-block-begin-line and org-block-end-line faces."
  3007. :group 'org-appearance
  3008. :type 'boolean)
  3009. (defcustom org-highlight-latex-and-related nil
  3010. "Non-nil means highlight LaTeX related syntax in the buffer.
  3011. When non-nil, the value should be a list containing any of the
  3012. following symbols:
  3013. `native' Highlight LaTeX snippets and environments natively.
  3014. `latex' Highlight LaTeX snippets and environments.
  3015. `script' Highlight subscript and superscript.
  3016. `entities' Highlight entities."
  3017. :group 'org-appearance
  3018. :version "24.4"
  3019. :package-version '(Org . "8.0")
  3020. :type '(choice
  3021. (const :tag "No highlighting" nil)
  3022. (set :greedy t :tag "Highlight"
  3023. (const :tag "LaTeX snippets and environments (native)" native)
  3024. (const :tag "LaTeX snippets and environments" latex)
  3025. (const :tag "Subscript and superscript" script)
  3026. (const :tag "Entities" entities))))
  3027. (defcustom org-hide-emphasis-markers nil
  3028. "Non-nil mean font-lock should hide the emphasis marker characters."
  3029. :group 'org-appearance
  3030. :type 'boolean
  3031. :safe #'booleanp)
  3032. (defcustom org-hide-macro-markers nil
  3033. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3034. :group 'org-appearance
  3035. :type 'boolean)
  3036. (defcustom org-pretty-entities nil
  3037. "Non-nil means show entities as UTF8 characters.
  3038. When nil, the \\name form remains in the buffer."
  3039. :group 'org-appearance
  3040. :version "24.1"
  3041. :type 'boolean)
  3042. (defcustom org-pretty-entities-include-sub-superscripts t
  3043. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3044. :group 'org-appearance
  3045. :version "24.1"
  3046. :type 'boolean)
  3047. (defvar org-emph-re nil
  3048. "Regular expression for matching emphasis.
  3049. After a match, the match groups contain these elements:
  3050. 0 The match of the full regular expression, including the characters
  3051. before and after the proper match
  3052. 1 The character before the proper match, or empty at beginning of line
  3053. 2 The proper match, including the leading and trailing markers
  3054. 3 The leading marker like * or /, indicating the type of highlighting
  3055. 4 The text between the emphasis markers, not including the markers
  3056. 5 The character after the match, empty at the end of a line")
  3057. (defvar org-verbatim-re nil
  3058. "Regular expression for matching verbatim text.")
  3059. (defvar org-emphasis-regexp-components) ; defined just below
  3060. (defvar org-emphasis-alist) ; defined just below
  3061. (defun org-set-emph-re (var val)
  3062. "Set variable and compute the emphasis regular expression."
  3063. (set-default-toplevel-value var val)
  3064. (when (and (boundp 'org-emphasis-alist)
  3065. (boundp 'org-emphasis-regexp-components)
  3066. org-emphasis-alist org-emphasis-regexp-components)
  3067. (pcase-let*
  3068. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3069. (body (if (<= nl 0) body
  3070. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3071. (template
  3072. (format (concat "\\([%s]\\|^\\)" ;before markers
  3073. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3074. "\\([%s]\\|$\\)") ;after markers
  3075. pre border border body border post)))
  3076. (setq org-emph-re (format template "*/_+"))
  3077. (setq org-verbatim-re (format template "=~")))))
  3078. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3079. ;; set this option proved cumbersome. See this message/thread:
  3080. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3081. (defvar org-emphasis-regexp-components
  3082. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3083. "Components used to build the regular expression for emphasis.
  3084. This is a list with five entries. Terminology: In an emphasis string
  3085. like \" *strong word* \", we call the initial space PREMATCH, the final
  3086. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3087. and \"trong wor\" is the body. The different components in this variable
  3088. specify what is allowed/forbidden in each part:
  3089. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3090. post Chars allowed as postmatch. End of line will be allowed too.
  3091. border The chars *forbidden* as border characters.
  3092. body-regexp A regexp like \".\" to match a body character. Don't use
  3093. non-shy groups here, and don't allow newline here.
  3094. newline The maximum number of newlines allowed in an emphasis exp.
  3095. You need to reload Org or to restart Emacs after setting this.")
  3096. (defcustom org-emphasis-alist
  3097. '(("*" bold)
  3098. ("/" italic)
  3099. ("_" underline)
  3100. ("=" org-verbatim verbatim)
  3101. ("~" org-code verbatim)
  3102. ("+" (:strike-through t)))
  3103. "Alist of characters and faces to emphasize text.
  3104. Text starting and ending with a special character will be emphasized,
  3105. for example *bold*, _underlined_ and /italic/. This variable sets the
  3106. marker characters and the face to be used by font-lock for highlighting
  3107. in Org buffers.
  3108. You need to reload Org or to restart Emacs after customizing this."
  3109. :group 'org-appearance
  3110. :set 'org-set-emph-re
  3111. :version "24.4"
  3112. :package-version '(Org . "8.0")
  3113. :type '(repeat
  3114. (list
  3115. (string :tag "Marker character")
  3116. (choice
  3117. (face :tag "Font-lock-face")
  3118. (plist :tag "Face property list"))
  3119. (option (const verbatim)))))
  3120. (defvar org-protecting-blocks '("src" "example" "export")
  3121. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3122. This is needed for font-lock setup.")
  3123. ;;; Functions and variables from their packages
  3124. ;; Declared here to avoid compiler warnings
  3125. (defvar mark-active)
  3126. ;; Various packages
  3127. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3128. (declare-function calendar-forward-day "cal-move" (arg))
  3129. (declare-function calendar-goto-date "cal-move" (date))
  3130. (declare-function calendar-goto-today "cal-move" ())
  3131. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3132. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3133. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3134. (declare-function cdlatex-tab "ext:cdlatex" ())
  3135. (declare-function dired-get-filename
  3136. "dired"
  3137. (&optional localp no-error-if-not-filep))
  3138. (declare-function iswitchb-read-buffer
  3139. "iswitchb"
  3140. (prompt &optional
  3141. default require-match _predicate start matches-set))
  3142. (declare-function org-agenda-change-all-lines
  3143. "org-agenda"
  3144. (newhead hdmarker &optional fixface just-this))
  3145. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3146. "org-agenda"
  3147. (&optional end))
  3148. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3149. (declare-function org-agenda-format-item
  3150. "org-agenda"
  3151. (extra txt &optional level category tags dotime
  3152. remove-re habitp))
  3153. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3154. (declare-function org-agenda-save-markers-for-cut-and-paste
  3155. "org-agenda"
  3156. (beg end))
  3157. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3158. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3159. (declare-function org-attach-expand "org-attach" (file))
  3160. (declare-function org-attach-reveal "org-attach" ())
  3161. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3162. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3163. (declare-function org-indent-mode "org-indent" (&optional arg))
  3164. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3165. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3166. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3167. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3168. (declare-function parse-time-string "parse-time" (string))
  3169. (defvar align-mode-rules-list)
  3170. (defvar calc-embedded-close-formula)
  3171. (defvar calc-embedded-open-formula)
  3172. (defvar calc-embedded-open-mode)
  3173. (defvar font-lock-unfontify-region-function)
  3174. (defvar iswitchb-temp-buflist)
  3175. (defvar org-agenda-tags-todo-honor-ignore-options)
  3176. (defvar remember-data-file)
  3177. (defvar texmathp-why)
  3178. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3179. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3180. (declare-function org-resolve-clocks "org-clock"
  3181. (&optional also-non-dangling-p prompt last-valid))
  3182. (defvar org-clock-start-time)
  3183. (defvar org-clock-marker (make-marker)
  3184. "Marker recording the last clock-in.")
  3185. (defvar org-clock-hd-marker (make-marker)
  3186. "Marker recording the last clock-in, but the headline position.")
  3187. (defvar org-clock-heading ""
  3188. "The heading of the current clock entry.")
  3189. (defun org-clocking-buffer ()
  3190. "Return the buffer where the clock is currently running.
  3191. Return nil if no clock is running."
  3192. (marker-buffer org-clock-marker))
  3193. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3194. (defun org-check-running-clock ()
  3195. "Check if the current buffer contains the running clock.
  3196. If yes, offer to stop it and to save the buffer with the changes."
  3197. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3198. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3199. (buffer-name))))
  3200. (org-clock-out)
  3201. (when (y-or-n-p "Save changed buffer?")
  3202. (save-buffer))))
  3203. (defun org-clocktable-try-shift (dir n)
  3204. "Check if this line starts a clock table, if yes, shift the time block."
  3205. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3206. (org-clocktable-shift dir n)))
  3207. ;;;###autoload
  3208. (defun org-clock-persistence-insinuate ()
  3209. "Set up hooks for clock persistence."
  3210. (require 'org-clock)
  3211. (add-hook 'org-mode-hook 'org-clock-load)
  3212. (add-hook 'kill-emacs-hook 'org-clock-save))
  3213. (defun org-clock-auto-clockout-insinuate ()
  3214. "Set up hook for auto clocking out when Emacs is idle.
  3215. See `org-clock-auto-clockout-timer'.
  3216. This function is meant to be added to the user configuration."
  3217. (require 'org-clock)
  3218. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3219. (defgroup org-archive nil
  3220. "Options concerning archiving in Org mode."
  3221. :tag "Org Archive"
  3222. :group 'org-structure)
  3223. (defcustom org-archive-location "%s_archive::"
  3224. "The location where subtrees should be archived.
  3225. The value of this variable is a string, consisting of two parts,
  3226. separated by a double-colon. The first part is a filename and
  3227. the second part is a headline.
  3228. When the filename is omitted, archiving happens in the same file.
  3229. %s in the filename will be replaced by the current file
  3230. name (without the directory part). Archiving to a different file
  3231. is useful to keep archived entries from contributing to the
  3232. Org Agenda.
  3233. The archived entries will be filed as subtrees of the specified
  3234. headline. When the headline is omitted, the subtrees are simply
  3235. filed away at the end of the file, as top-level entries. Also in
  3236. the heading you can use %s to represent the file name, this can be
  3237. useful when using the same archive for a number of different files.
  3238. Here are a few examples:
  3239. \"%s_archive::\"
  3240. If the current file is Projects.org, archive in file
  3241. Projects.org_archive, as top-level trees. This is the default.
  3242. \"::* Archived Tasks\"
  3243. Archive in the current file, under the top-level headline
  3244. \"* Archived Tasks\".
  3245. \"~/org/archive.org::\"
  3246. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3247. \"~/org/archive.org::* From %s\"
  3248. Archive in file ~/org/archive.org (absolute path), under headlines
  3249. \"From FILENAME\" where file name is the current file name.
  3250. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3251. The \"datetree/\" string is special, signifying to archive
  3252. items to the datetree. Items are placed in either the CLOSED
  3253. date of the item, or the current date if there is no CLOSED date.
  3254. The heading will be a subentry to the current date. There doesn't
  3255. need to be a heading, but there always needs to be a slash after
  3256. datetree. For example, to store archived items directly in the
  3257. datetree, use \"~/org/datetree.org::datetree/\".
  3258. \"basement::** Finished Tasks\"
  3259. Archive in file ./basement (relative path), as level 3 trees
  3260. below the level 2 heading \"** Finished Tasks\".
  3261. You may define it locally by setting an ARCHIVE property. If
  3262. such a property is found in the file or in an entry, and anywhere
  3263. up the hierarchy, it will be used.
  3264. You can also set it for the whole file using the keyword-syntax:
  3265. #+ARCHIVE: basement::** Finished Tasks"
  3266. :group 'org-archive
  3267. :type 'string)
  3268. (defcustom org-agenda-skip-archived-trees t
  3269. "Non-nil means the agenda will skip any items located in archived trees.
  3270. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3271. variable is no longer recommended, you should leave it at the value t.
  3272. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3273. :group 'org-archive
  3274. :group 'org-agenda-skip
  3275. :type 'boolean)
  3276. (defcustom org-columns-skip-archived-trees t
  3277. "Non-nil means ignore archived trees when creating column view."
  3278. :group 'org-archive
  3279. :group 'org-properties
  3280. :type 'boolean)
  3281. (defcustom org-sparse-tree-open-archived-trees nil
  3282. "Non-nil means sparse tree construction shows matches in archived trees.
  3283. When nil, matches in these trees are highlighted, but the trees are kept in
  3284. collapsed state."
  3285. :group 'org-archive
  3286. :group 'org-sparse-trees
  3287. :type 'boolean)
  3288. (defcustom org-sparse-tree-default-date-type nil
  3289. "The default date type when building a sparse tree.
  3290. When this is nil, a date is a scheduled or a deadline timestamp.
  3291. Otherwise, these types are allowed:
  3292. all: all timestamps
  3293. active: only active timestamps (<...>)
  3294. inactive: only inactive timestamps ([...])
  3295. scheduled: only scheduled timestamps
  3296. deadline: only deadline timestamps"
  3297. :type '(choice (const :tag "Scheduled or deadline" nil)
  3298. (const :tag "All timestamps" all)
  3299. (const :tag "Only active timestamps" active)
  3300. (const :tag "Only inactive timestamps" inactive)
  3301. (const :tag "Only scheduled timestamps" scheduled)
  3302. (const :tag "Only deadline timestamps" deadline)
  3303. (const :tag "Only closed timestamps" closed))
  3304. :version "26.1"
  3305. :package-version '(Org . "8.3")
  3306. :group 'org-sparse-trees)
  3307. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3308. ;; Declare Column View Code
  3309. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3310. (declare-function org-columns-compute "org-colview" (property))
  3311. ;; Declare ID code
  3312. (declare-function org-id-store-link "org-id")
  3313. (declare-function org-id-locations-load "org-id")
  3314. (declare-function org-id-locations-save "org-id")
  3315. (defvar org-id-track-globally)
  3316. ;;; Variables for pre-computed regular expressions, all buffer local
  3317. (defvar-local org-todo-regexp nil
  3318. "Matches any of the TODO state keywords.
  3319. Since TODO keywords are case-sensitive, `case-fold-search' is
  3320. expected to be bound to nil when matching against this regexp.")
  3321. (defvar-local org-not-done-regexp nil
  3322. "Matches any of the TODO state keywords except the last one.
  3323. Since TODO keywords are case-sensitive, `case-fold-search' is
  3324. expected to be bound to nil when matching against this regexp.")
  3325. (defvar-local org-not-done-heading-regexp nil
  3326. "Matches a TODO headline that is not done.
  3327. Since TODO keywords are case-sensitive, `case-fold-search' is
  3328. expected to be bound to nil when matching against this regexp.")
  3329. (defvar-local org-todo-line-regexp nil
  3330. "Matches a headline and puts TODO state into group 2 if present.
  3331. Since TODO keywords are case-sensitive, `case-fold-search' is
  3332. expected to be bound to nil when matching against this regexp.")
  3333. (defvar-local org-complex-heading-regexp nil
  3334. "Matches a headline and puts everything into groups:
  3335. group 1: Stars
  3336. group 2: The TODO keyword, maybe
  3337. group 3: Priority cookie
  3338. group 4: True headline
  3339. group 5: Tags
  3340. Since TODO keywords are case-sensitive, `case-fold-search' is
  3341. expected to be bound to nil when matching against this regexp.")
  3342. (defvar-local org-complex-heading-regexp-format nil
  3343. "Printf format to make regexp to match an exact headline.
  3344. This regexp will match the headline of any node which has the
  3345. exact headline text that is put into the format, but may have any
  3346. TODO state, priority, tags, statistics cookies (at the beginning
  3347. or end of the headline title), or COMMENT keyword.")
  3348. (defvar-local org-todo-line-tags-regexp nil
  3349. "Matches a headline and puts TODO state into group 2 if present.
  3350. Also put tags into group 4 if tags are present.")
  3351. (defconst org-plain-time-of-day-regexp
  3352. (concat
  3353. "\\(\\<[012]?[0-9]"
  3354. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3355. "\\(--?"
  3356. "\\(\\<[012]?[0-9]"
  3357. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3358. "\\)?")
  3359. "Regular expression to match a plain time or time range.
  3360. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3361. groups carry important information:
  3362. 0 the full match
  3363. 1 the first time, range or not
  3364. 8 the second time, if it is a range.")
  3365. (defconst org-plain-time-extension-regexp
  3366. (concat
  3367. "\\(\\<[012]?[0-9]"
  3368. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3369. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3370. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3371. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3372. groups carry important information:
  3373. 0 the full match
  3374. 7 hours of duration
  3375. 9 minutes of duration")
  3376. (defconst org-stamp-time-of-day-regexp
  3377. (concat
  3378. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3379. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3380. "\\(--?"
  3381. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3382. "Regular expression to match a timestamp time or time range.
  3383. After a match, the following groups carry important information:
  3384. 0 the full match
  3385. 1 date plus weekday, for back referencing to make sure
  3386. both times are on the same day
  3387. 2 the first time, range or not
  3388. 4 the second time, if it is a range.")
  3389. (defconst org-startup-options
  3390. '(("fold" org-startup-folded t)
  3391. ("overview" org-startup-folded t)
  3392. ("nofold" org-startup-folded nil)
  3393. ("showall" org-startup-folded nil)
  3394. ("show2levels" org-startup-folded show2levels)
  3395. ("show3levels" org-startup-folded show3levels)
  3396. ("show4levels" org-startup-folded show4levels)
  3397. ("show5levels" org-startup-folded show5levels)
  3398. ("showeverything" org-startup-folded showeverything)
  3399. ("content" org-startup-folded content)
  3400. ("indent" org-startup-indented t)
  3401. ("noindent" org-startup-indented nil)
  3402. ("num" org-startup-numerated t)
  3403. ("nonum" org-startup-numerated nil)
  3404. ("hidestars" org-hide-leading-stars t)
  3405. ("showstars" org-hide-leading-stars nil)
  3406. ("odd" org-odd-levels-only t)
  3407. ("oddeven" org-odd-levels-only nil)
  3408. ("align" org-startup-align-all-tables t)
  3409. ("noalign" org-startup-align-all-tables nil)
  3410. ("shrink" org-startup-shrink-all-tables t)
  3411. ("inlineimages" org-startup-with-inline-images t)
  3412. ("noinlineimages" org-startup-with-inline-images nil)
  3413. ("latexpreview" org-startup-with-latex-preview t)
  3414. ("nolatexpreview" org-startup-with-latex-preview nil)
  3415. ("customtime" org-display-custom-times t)
  3416. ("logdone" org-log-done time)
  3417. ("lognotedone" org-log-done note)
  3418. ("nologdone" org-log-done nil)
  3419. ("lognoteclock-out" org-log-note-clock-out t)
  3420. ("nolognoteclock-out" org-log-note-clock-out nil)
  3421. ("logrepeat" org-log-repeat state)
  3422. ("lognoterepeat" org-log-repeat note)
  3423. ("logdrawer" org-log-into-drawer t)
  3424. ("nologdrawer" org-log-into-drawer nil)
  3425. ("logstatesreversed" org-log-states-order-reversed t)
  3426. ("nologstatesreversed" org-log-states-order-reversed nil)
  3427. ("nologrepeat" org-log-repeat nil)
  3428. ("logreschedule" org-log-reschedule time)
  3429. ("lognotereschedule" org-log-reschedule note)
  3430. ("nologreschedule" org-log-reschedule nil)
  3431. ("logredeadline" org-log-redeadline time)
  3432. ("lognoteredeadline" org-log-redeadline note)
  3433. ("nologredeadline" org-log-redeadline nil)
  3434. ("logrefile" org-log-refile time)
  3435. ("lognoterefile" org-log-refile note)
  3436. ("nologrefile" org-log-refile nil)
  3437. ("fninline" org-footnote-define-inline t)
  3438. ("nofninline" org-footnote-define-inline nil)
  3439. ("fnlocal" org-footnote-section nil)
  3440. ("fnauto" org-footnote-auto-label t)
  3441. ("fnprompt" org-footnote-auto-label nil)
  3442. ("fnconfirm" org-footnote-auto-label confirm)
  3443. ("fnplain" org-footnote-auto-label plain)
  3444. ("fnadjust" org-footnote-auto-adjust t)
  3445. ("nofnadjust" org-footnote-auto-adjust nil)
  3446. ("constcgs" constants-unit-system cgs)
  3447. ("constSI" constants-unit-system SI)
  3448. ("noptag" org-tag-persistent-alist nil)
  3449. ("hideblocks" org-hide-block-startup t)
  3450. ("nohideblocks" org-hide-block-startup nil)
  3451. ("hidedrawers" org-hide-drawer-startup t)
  3452. ("nohidedrawers" org-hide-drawer-startup nil)
  3453. ("beamer" org-startup-with-beamer-mode t)
  3454. ("entitiespretty" org-pretty-entities t)
  3455. ("entitiesplain" org-pretty-entities nil))
  3456. "Variable associated with STARTUP options for Org.
  3457. Each element is a list of three items: the startup options (as written
  3458. in the #+STARTUP line), the corresponding variable, and the value to set
  3459. this variable to if the option is found. An optional fourth element PUSH
  3460. means to push this value onto the list in the variable.")
  3461. (defcustom org-group-tags t
  3462. "When non-nil (the default), use group tags.
  3463. This can be turned on/off through `org-toggle-tags-groups'."
  3464. :group 'org-tags
  3465. :group 'org-startup
  3466. :type 'boolean)
  3467. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3468. (defun org-toggle-tags-groups ()
  3469. "Toggle support for group tags.
  3470. Support for group tags is controlled by the option
  3471. `org-group-tags', which is non-nil by default."
  3472. (interactive)
  3473. (setq org-group-tags (not org-group-tags))
  3474. (cond ((and (derived-mode-p 'org-agenda-mode)
  3475. org-group-tags)
  3476. (org-agenda-redo))
  3477. ((derived-mode-p 'org-mode)
  3478. (let ((org-inhibit-startup t)) (org-mode))))
  3479. (message "Groups tags support has been turned %s"
  3480. (if org-group-tags "on" "off")))
  3481. (defun org--tag-add-to-alist (alist1 alist2)
  3482. "Merge tags from ALIST1 into ALIST2.
  3483. Duplicates tags outside a group are removed. Keywords and order
  3484. are preserved.
  3485. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3486. See `org-tag-alist' for their structure."
  3487. (cond
  3488. ((null alist2) alist1)
  3489. ((null alist1) alist2)
  3490. (t
  3491. (let ((to-add nil)
  3492. (group-flag nil))
  3493. (dolist (tag-pair alist1)
  3494. (pcase tag-pair
  3495. (`(,(or :startgrouptag :startgroup))
  3496. (setq group-flag t)
  3497. (push tag-pair to-add))
  3498. (`(,(or :endgrouptag :endgroup))
  3499. (setq group-flag nil)
  3500. (push tag-pair to-add))
  3501. (`(,(or :grouptags :newline))
  3502. (push tag-pair to-add))
  3503. (`(,tag . ,_)
  3504. ;; Remove duplicates from ALIST1, unless they are in
  3505. ;; a group. Indeed, it makes sense to have a tag appear in
  3506. ;; multiple groups.
  3507. (when (or group-flag (not (assoc tag alist2)))
  3508. (push tag-pair to-add)))
  3509. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3510. ;; Preserve order of ALIST1.
  3511. (append (nreverse to-add) alist2)))))
  3512. (defun org-priority-to-value (s)
  3513. "Convert priority string S to its numeric value."
  3514. (or (save-match-data
  3515. (and (string-match "\\([0-9]+\\)" s)
  3516. (string-to-number (match-string 1 s))))
  3517. (string-to-char s)))
  3518. (defun org-set-regexps-and-options (&optional tags-only)
  3519. "Precompute regular expressions used in the current buffer.
  3520. When optional argument TAGS-ONLY is non-nil, only compute tags
  3521. related expressions."
  3522. (when (derived-mode-p 'org-mode)
  3523. (let ((alist (org-collect-keywords
  3524. (append '("FILETAGS" "TAGS")
  3525. (and (not tags-only)
  3526. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3527. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3528. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3529. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3530. ;; Startup options. Get this early since it does change
  3531. ;; behavior for other options (e.g., tags).
  3532. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3533. (cdr (assoc "STARTUP" alist)))))
  3534. (dolist (option startup)
  3535. (pcase (assoc-string option org-startup-options t)
  3536. (`(,_ ,variable ,value t)
  3537. (unless (listp (symbol-value variable))
  3538. (set (make-local-variable variable) nil))
  3539. (add-to-list variable value))
  3540. (`(,_ ,variable ,value . ,_)
  3541. (set (make-local-variable variable) value))
  3542. (_ nil))))
  3543. (setq-local org-file-tags
  3544. (mapcar #'org-add-prop-inherited
  3545. (cl-mapcan (lambda (value)
  3546. (cl-mapcan
  3547. (lambda (k) (org-split-string k ":"))
  3548. (split-string value)))
  3549. (cdr (assoc "FILETAGS" alist)))))
  3550. (setq org-current-tag-alist
  3551. (org--tag-add-to-alist
  3552. org-tag-persistent-alist
  3553. (let ((tags (cdr (assoc "TAGS" alist))))
  3554. (if tags
  3555. (org-tag-string-to-alist
  3556. (mapconcat #'identity tags "\n"))
  3557. org-tag-alist))))
  3558. (setq org-tag-groups-alist
  3559. (org-tag-alist-to-groups org-current-tag-alist))
  3560. (unless tags-only
  3561. ;; Properties.
  3562. (let ((properties nil))
  3563. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3564. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3565. (setq properties (org--update-property-plist
  3566. (match-string-no-properties 1 value)
  3567. (match-string-no-properties 2 value)
  3568. properties))))
  3569. (setq-local org-keyword-properties properties))
  3570. ;; Archive location.
  3571. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3572. (when archive (setq-local org-archive-location archive)))
  3573. ;; Category.
  3574. (let ((category (cdr (assoc "CATEGORY" alist))))
  3575. (when category
  3576. (setq-local org-category (intern category))
  3577. (setq-local org-keyword-properties
  3578. (org--update-property-plist
  3579. "CATEGORY" category org-keyword-properties))))
  3580. ;; Columns.
  3581. (let ((column (cdr (assoc "COLUMNS" alist))))
  3582. (when column (setq-local org-columns-default-format column)))
  3583. ;; Constants.
  3584. (let ((store nil))
  3585. (dolist (pair (cl-mapcan #'split-string
  3586. (cdr (assoc "CONSTANTS" alist))))
  3587. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3588. (let* ((name (match-string 1 pair))
  3589. (value (match-string 2 pair))
  3590. (old (assoc name store)))
  3591. (if old (setcdr old value)
  3592. (push (cons name value) store)))))
  3593. (setq org-table-formula-constants-local store))
  3594. ;; Link abbreviations.
  3595. (let ((links
  3596. (delq nil
  3597. (mapcar
  3598. (lambda (value)
  3599. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3600. (cons (match-string-no-properties 1 value)
  3601. (match-string-no-properties 2 value))))
  3602. (cdr (assoc "LINK" alist))))))
  3603. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3604. ;; Priorities.
  3605. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3606. (pcase (and value (split-string value))
  3607. (`(,high ,low ,default . ,_)
  3608. (setq-local org-priority-highest (org-priority-to-value high))
  3609. (setq-local org-priority-lowest (org-priority-to-value low))
  3610. (setq-local org-priority-default (org-priority-to-value default)))))
  3611. ;; Scripts.
  3612. (let ((value (cdr (assoc "OPTIONS" alist))))
  3613. (dolist (option value)
  3614. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3615. (setq-local org-use-sub-superscripts
  3616. (read (match-string 1 option))))))
  3617. ;; TODO keywords.
  3618. (setq-local org-todo-kwd-alist nil)
  3619. (setq-local org-todo-key-alist nil)
  3620. (setq-local org-todo-key-trigger nil)
  3621. (setq-local org-todo-keywords-1 nil)
  3622. (setq-local org-done-keywords nil)
  3623. (setq-local org-todo-heads nil)
  3624. (setq-local org-todo-sets nil)
  3625. (setq-local org-todo-log-states nil)
  3626. (let ((todo-sequences
  3627. (or (append (mapcar (lambda (value)
  3628. (cons 'type (split-string value)))
  3629. (cdr (assoc "TYP_TODO" alist)))
  3630. (mapcar (lambda (value)
  3631. (cons 'sequence (split-string value)))
  3632. (append (cdr (assoc "TODO" alist))
  3633. (cdr (assoc "SEQ_TODO" alist)))))
  3634. (let ((d (default-value 'org-todo-keywords)))
  3635. (if (not (stringp (car d))) d
  3636. ;; XXX: Backward compatibility code.
  3637. (list (cons org-todo-interpretation d)))))))
  3638. (dolist (sequence todo-sequences)
  3639. (let* ((sequence (or (run-hook-with-args-until-success
  3640. 'org-todo-setup-filter-hook sequence)
  3641. sequence))
  3642. (sequence-type (car sequence))
  3643. (keywords (cdr sequence))
  3644. (sep (member "|" keywords))
  3645. names alist)
  3646. (dolist (k (remove "|" keywords))
  3647. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3648. k)
  3649. (error "Invalid TODO keyword %s" k))
  3650. (let ((name (match-string 1 k))
  3651. (key (match-string 2 k))
  3652. (log (org-extract-log-state-settings k)))
  3653. (push name names)
  3654. (push (cons name (and key (string-to-char key))) alist)
  3655. (when log (push log org-todo-log-states))))
  3656. (let* ((names (nreverse names))
  3657. (done (if sep (org-remove-keyword-keys (cdr sep))
  3658. (last names)))
  3659. (head (car names))
  3660. (tail (list sequence-type head (car done) (org-last done))))
  3661. (add-to-list 'org-todo-heads head 'append)
  3662. (push names org-todo-sets)
  3663. (setq org-done-keywords (append org-done-keywords done nil))
  3664. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3665. (setq org-todo-key-alist
  3666. (append org-todo-key-alist
  3667. (and alist
  3668. (append '((:startgroup))
  3669. (nreverse alist)
  3670. '((:endgroup))))))
  3671. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3672. (setq org-todo-sets (nreverse org-todo-sets)
  3673. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3674. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3675. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3676. ;; Compute the regular expressions and other local variables.
  3677. ;; Using `org-outline-regexp-bol' would complicate them much,
  3678. ;; because of the fixed white space at the end of that string.
  3679. (unless org-done-keywords
  3680. (setq org-done-keywords
  3681. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3682. (setq org-not-done-keywords
  3683. (org-delete-all org-done-keywords
  3684. (copy-sequence org-todo-keywords-1))
  3685. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3686. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3687. org-not-done-heading-regexp
  3688. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3689. org-todo-line-regexp
  3690. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3691. org-complex-heading-regexp
  3692. (concat "^\\(\\*+\\)"
  3693. "\\(?: +" org-todo-regexp "\\)?"
  3694. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3695. "\\(?: +\\(.*?\\)\\)??"
  3696. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3697. "[ \t]*$")
  3698. org-complex-heading-regexp-format
  3699. (concat "^\\(\\*+\\)"
  3700. "\\(?: +" org-todo-regexp "\\)?"
  3701. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3702. "\\(?: +"
  3703. ;; Headline might be commented
  3704. "\\(?:" org-comment-string " +\\)?"
  3705. ;; Stats cookies can be stuck to body.
  3706. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3707. "\\(%s\\)"
  3708. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3709. "\\)"
  3710. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3711. "[ \t]*$")
  3712. org-todo-line-tags-regexp
  3713. (concat "^\\(\\*+\\)"
  3714. "\\(?: +" org-todo-regexp "\\)?"
  3715. "\\(?: +\\(.*?\\)\\)??"
  3716. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3717. "[ \t]*$"))
  3718. (org-compute-latex-and-related-regexp)))))
  3719. (defun org-collect-keywords (keywords &optional unique directory)
  3720. "Return values for KEYWORDS in current buffer, as an alist.
  3721. KEYWORDS is a list of strings. Return value is a list of
  3722. elements with the pattern:
  3723. (NAME . LIST-OF-VALUES)
  3724. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3725. is a list of non-empty values, as strings, in order of appearance
  3726. in the buffer.
  3727. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3728. value, empty or not, appearing in the buffer, as a string.
  3729. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3730. (VALUE . DIRECTORY)
  3731. where VALUE is the regular value, and DIRECTORY is the variable
  3732. `default-directory' for the buffer containing the keyword. This
  3733. is important for values containing relative file names, since the
  3734. function follows SETUPFILE keywords, and may change its working
  3735. directory."
  3736. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3737. (unique (mapcar #'upcase unique))
  3738. (alist (org--collect-keywords-1
  3739. keywords unique directory
  3740. (and buffer-file-name (list buffer-file-name))
  3741. nil)))
  3742. ;; Re-order results.
  3743. (dolist (entry alist)
  3744. (pcase entry
  3745. (`(,_ . ,(and value (pred consp)))
  3746. (setcdr entry (nreverse value)))))
  3747. (nreverse alist)))
  3748. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3749. (org-with-point-at 1
  3750. (let ((case-fold-search t)
  3751. (regexp (org-make-options-regexp keywords)))
  3752. (while (and keywords (re-search-forward regexp nil t))
  3753. (let ((element (org-element-at-point)))
  3754. (when (eq 'keyword (org-element-type element))
  3755. (let ((value (org-element-property :value element)))
  3756. (pcase (org-element-property :key element)
  3757. ("SETUPFILE"
  3758. (when (and (org-string-nw-p value)
  3759. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3760. (let* ((uri (org-strip-quotes value))
  3761. (uri-is-url (org-url-p uri))
  3762. (uri (if uri-is-url
  3763. uri
  3764. (expand-file-name uri))))
  3765. (unless (member uri files)
  3766. (with-temp-buffer
  3767. (unless uri-is-url
  3768. (setq default-directory (file-name-directory uri)))
  3769. (let ((contents (org-file-contents uri :noerror)))
  3770. (when contents
  3771. (insert contents)
  3772. ;; Fake Org mode: `org-element-at-point'
  3773. ;; doesn't need full set-up.
  3774. (let ((major-mode 'org-mode))
  3775. (setq alist
  3776. (org--collect-keywords-1
  3777. keywords unique directory
  3778. (cons uri files)
  3779. alist))))))))))
  3780. (keyword
  3781. (let ((entry (assoc keyword alist))
  3782. (final
  3783. (cond ((not (member keyword directory)) value)
  3784. (buffer-file-name
  3785. (cons value
  3786. (file-name-directory buffer-file-name)))
  3787. (t (cons value default-directory)))))
  3788. (cond ((member keyword unique)
  3789. (push (cons keyword final) alist)
  3790. (setq keywords (remove keyword keywords))
  3791. (setq regexp (org-make-options-regexp keywords)))
  3792. ((null entry) (push (list keyword final) alist))
  3793. (t (push final (cdr entry)))))))))))
  3794. alist)))
  3795. (defun org-tag-string-to-alist (s)
  3796. "Return tag alist associated to string S.
  3797. S is a value for TAGS keyword or produced with
  3798. `org-tag-alist-to-string'. Return value is an alist suitable for
  3799. `org-tag-alist' or `org-tag-persistent-alist'."
  3800. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3801. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3802. "\\(?:(\\(.\\))\\)?\\'"))
  3803. alist group-flag)
  3804. (dolist (tokens lines (cdr (nreverse alist)))
  3805. (push '(:newline) alist)
  3806. (while tokens
  3807. (let ((token (pop tokens)))
  3808. (pcase token
  3809. ("{"
  3810. (push '(:startgroup) alist)
  3811. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3812. ("}"
  3813. (push '(:endgroup) alist)
  3814. (setq group-flag nil))
  3815. ("["
  3816. (push '(:startgrouptag) alist)
  3817. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3818. ("]"
  3819. (push '(:endgrouptag) alist)
  3820. (setq group-flag nil))
  3821. (":"
  3822. (push '(:grouptags) alist))
  3823. ((guard (string-match tag-re token))
  3824. (let ((tag (match-string 1 token))
  3825. (key (and (match-beginning 2)
  3826. (string-to-char (match-string 2 token)))))
  3827. ;; Push all tags in groups, no matter if they already
  3828. ;; appear somewhere else in the list.
  3829. (when (or group-flag (not (assoc tag alist)))
  3830. (push (cons tag key) alist))))))))))
  3831. (defun org-tag-alist-to-string (alist &optional skip-key)
  3832. "Return tag string associated to ALIST.
  3833. ALIST is an alist, as defined in `org-tag-alist' or
  3834. `org-tag-persistent-alist', or produced with
  3835. `org-tag-string-to-alist'.
  3836. Return value is a string suitable as a value for \"TAGS\"
  3837. keyword.
  3838. When optional argument SKIP-KEY is non-nil, skip selection keys
  3839. next to tags."
  3840. (mapconcat (lambda (token)
  3841. (pcase token
  3842. (`(:startgroup) "{")
  3843. (`(:endgroup) "}")
  3844. (`(:startgrouptag) "[")
  3845. (`(:endgrouptag) "]")
  3846. (`(:grouptags) ":")
  3847. (`(:newline) "\\n")
  3848. ((and
  3849. (guard (not skip-key))
  3850. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3851. (format "%s(%c)" tag key))
  3852. (`(,(and tag (pred stringp)) . ,_) tag)
  3853. (_ (user-error "Invalid tag token: %S" token))))
  3854. alist
  3855. " "))
  3856. (defun org-tag-alist-to-groups (alist)
  3857. "Return group alist from tag ALIST.
  3858. ALIST is an alist, as defined in `org-tag-alist' or
  3859. `org-tag-persistent-alist', or produced with
  3860. `org-tag-string-to-alist'. Return value is an alist following
  3861. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3862. a string, summarizing TAGS, as a list of strings."
  3863. (let (groups group-status current-group)
  3864. (dolist (token alist (nreverse groups))
  3865. (pcase token
  3866. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3867. (`(,(or :endgroup :endgrouptag))
  3868. (when (eq group-status 'append)
  3869. (push (nreverse current-group) groups))
  3870. (setq group-status nil current-group nil))
  3871. (`(:grouptags) (setq group-status 'append))
  3872. ((and `(,tag . ,_) (guard group-status))
  3873. (if (eq group-status 'append) (push tag current-group)
  3874. (setq current-group (list tag))))
  3875. (_ nil)))))
  3876. (defvar org--file-cache (make-hash-table :test #'equal)
  3877. "Hash table to store contents of files referenced via a URL.
  3878. This is the cache of file URLs read using `org-file-contents'.")
  3879. (defun org-reset-file-cache ()
  3880. "Reset the cache of files downloaded by `org-file-contents'."
  3881. (clrhash org--file-cache))
  3882. (defun org-file-contents (file &optional noerror nocache)
  3883. "Return the contents of FILE, as a string.
  3884. FILE can be a file name or URL.
  3885. If FILE is a URL, download the contents. If the URL contents are
  3886. already cached in the `org--file-cache' hash table, the download step
  3887. is skipped.
  3888. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3889. from file or URL, and return nil.
  3890. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3891. is available. This option applies only if FILE is a URL."
  3892. (let* ((is-url (org-url-p file))
  3893. (cache (and is-url
  3894. (not nocache)
  3895. (gethash file org--file-cache))))
  3896. (cond
  3897. (cache)
  3898. (is-url
  3899. (if (org--should-fetch-remote-resource-p file)
  3900. (with-current-buffer (url-retrieve-synchronously file)
  3901. (goto-char (point-min))
  3902. ;; Move point to after the url-retrieve header.
  3903. (search-forward "\n\n" nil :move)
  3904. ;; Search for the success code only in the url-retrieve header.
  3905. (if (save-excursion
  3906. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3907. ;; Update the cache `org--file-cache' and return contents.
  3908. (puthash file
  3909. (buffer-substring-no-properties (point) (point-max))
  3910. org--file-cache)
  3911. (funcall (if noerror #'message #'user-error)
  3912. "Unable to fetch file from %S"
  3913. file)
  3914. nil))
  3915. (funcall (if noerror #'message #'user-error)
  3916. "The remote resource %S is considered unsafe, and will not be downloaded."
  3917. file)))
  3918. (t
  3919. (with-temp-buffer
  3920. (condition-case nil
  3921. (progn
  3922. (insert-file-contents file)
  3923. (buffer-string))
  3924. (file-error
  3925. (funcall (if noerror #'message #'user-error)
  3926. "Unable to read file %S"
  3927. file)
  3928. nil)))))))
  3929. (defun org--should-fetch-remote-resource-p (uri)
  3930. "Return non-nil if the URI should be fetched."
  3931. (or (eq org-resource-download-policy t)
  3932. (org--safe-remote-resource-p uri)
  3933. (and (eq org-resource-download-policy 'prompt)
  3934. (org--confirm-resource-safe uri))))
  3935. (defun org--safe-remote-resource-p (uri)
  3936. "Return non-nil if URI is considered safe.
  3937. This checks every pattern in `org-safe-remote-resources', and
  3938. returns non-nil if any of them match."
  3939. (let ((uri-patterns org-safe-remote-resources)
  3940. (file-uri (and buffer-file-name
  3941. (concat "file://" (file-truename buffer-file-name))))
  3942. match-p)
  3943. (while (and (not match-p) uri-patterns)
  3944. (setq match-p (or (string-match-p (car uri-patterns) uri)
  3945. (and file-uri (string-match-p (car uri-patterns) file-uri)))
  3946. uri-patterns (cdr uri-patterns)))
  3947. match-p))
  3948. (defun org--confirm-resource-safe (uri)
  3949. "Ask the user if URI should be considered safe, returning non-nil if so."
  3950. (unless noninteractive
  3951. (let ((current-file (and buffer-file-name (file-truename buffer-file-name)))
  3952. (buf (get-buffer-create "*Org Remote Resource*")))
  3953. ;; Set up the contents of the *Org Remote Resource* buffer.
  3954. (with-current-buffer buf
  3955. (erase-buffer)
  3956. (insert "An org-mode document would like to download "
  3957. (propertize uri 'face '(:inherit org-link :weight normal))
  3958. ", which is not considered safe.\n\n"
  3959. "Do you want to download this? You can type\n "
  3960. (propertize "!" 'face 'success)
  3961. " to download this resource, and permanantly mark it as safe.\n "
  3962. (propertize "f" 'face 'success)
  3963. (if current-file
  3964. (concat
  3965. " to download this resource, and permanantly mark all resources in "
  3966. (propertize current-file 'face 'fixed-pitch-serif)
  3967. " as safe.\n ")
  3968. "")
  3969. (propertize "y" 'face 'warning)
  3970. " to download this resource, just this once.\n "
  3971. (propertize "n" 'face 'error)
  3972. " to skip this resource.\n")
  3973. (setq-local cursor-type nil)
  3974. (set-buffer-modified-p nil)
  3975. (goto-char (point-min)))
  3976. ;; Display the buffer and read a choice.
  3977. (save-window-excursion
  3978. (pop-to-buffer buf)
  3979. (let* ((exit-chars (append '(?y ?n ?! ?\s) (and current-file '(?f))))
  3980. (prompt (format "Please type y, n%s, or !%s: "
  3981. (if current-file ", f" "")
  3982. (if (< (line-number-at-pos (point-max))
  3983. (window-body-height))
  3984. ""
  3985. ", or C-v/M-v to scroll")))
  3986. char)
  3987. (setq char (read-char-choice prompt exit-chars))
  3988. (when (memq char '(?! ?f))
  3989. (customize-push-and-save
  3990. 'org-safe-remote-resources
  3991. (list (concat "\\`"
  3992. (regexp-quote
  3993. (if (and (= char ?f) current-file)
  3994. (concat "file://" current-file) uri))
  3995. "\\'"))))
  3996. (prog1 (memq char '(?! ?\s ?y ?f))
  3997. (quit-window t)))))))
  3998. (defun org-extract-log-state-settings (x)
  3999. "Extract the log state setting from a TODO keyword string.
  4000. This will extract info from a string like \"WAIT(w@/!)\"."
  4001. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4002. (let ((kw (match-string 1 x))
  4003. (log1 (and (match-end 3) (match-string 3 x)))
  4004. (log2 (and (match-end 4) (match-string 4 x))))
  4005. (and (or log1 log2)
  4006. (list kw
  4007. (and log1 (if (equal log1 "!") 'time 'note))
  4008. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4009. (defun org-remove-keyword-keys (list)
  4010. "Remove a pair of parenthesis at the end of each string in LIST."
  4011. (mapcar (lambda (x)
  4012. (if (string-match "(.*)$" x)
  4013. (substring x 0 (match-beginning 0))
  4014. x))
  4015. list))
  4016. (defun org-assign-fast-keys (alist)
  4017. "Assign fast keys to a keyword-key alist.
  4018. Respect keys that are already there."
  4019. (let (new e (alt ?0))
  4020. (while (setq e (pop alist))
  4021. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4022. (cdr e)) ;; Key already assigned.
  4023. (push e new)
  4024. (let ((clist (string-to-list (downcase (car e))))
  4025. (used (append new alist)))
  4026. (when (= (car clist) ?@)
  4027. (pop clist))
  4028. (while (and clist (rassoc (car clist) used))
  4029. (pop clist))
  4030. (unless clist
  4031. (while (rassoc alt used)
  4032. (cl-incf alt)))
  4033. (push (cons (car e) (or (car clist) alt)) new))))
  4034. (nreverse new)))
  4035. ;;; Some variables used in various places
  4036. (defvar org-window-configuration nil
  4037. "Used in various places to store a window configuration.")
  4038. (defvar org-selected-window nil
  4039. "Used in various places to store a window configuration.")
  4040. (defvar org-finish-function nil
  4041. "Function to be called when `C-c C-c' is used.
  4042. This is for getting out of special buffers like capture.")
  4043. (defvar org-last-state)
  4044. ;; Defined somewhere in this file, but used before definition.
  4045. (defvar org-entities) ;; defined in org-entities.el
  4046. (defvar org-struct-menu)
  4047. (defvar org-org-menu)
  4048. (defvar org-tbl-menu)
  4049. ;;;; Define the Org mode
  4050. (defun org-before-change-function (_beg _end)
  4051. "Every change indicates that a table might need an update."
  4052. (setq org-table-may-need-update t))
  4053. (defvar org-mode-map)
  4054. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4055. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4056. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4057. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4058. (defvar bidi-paragraph-direction)
  4059. (defvar buffer-face-mode-face)
  4060. (require 'outline)
  4061. ;; Other stuff we need.
  4062. (require 'time-date)
  4063. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4064. (require 'easymenu))
  4065. (require 'org-entities)
  4066. (require 'org-faces)
  4067. (require 'org-list)
  4068. (require 'org-pcomplete)
  4069. (require 'org-src)
  4070. (require 'org-footnote)
  4071. (require 'org-macro)
  4072. ;; babel
  4073. (require 'ob)
  4074. (defvar org-element-cache-persistent); Defined in org-element.el
  4075. (defvar org-element-use-cache); Defined in org-element.el
  4076. (defvar org-mode-loading nil
  4077. "Non-nil during Org mode initialisation.")
  4078. ;;;###autoload
  4079. (define-derived-mode org-mode outline-mode "Org"
  4080. "Outline-based notes management and organizer, alias
  4081. \"Carsten's outline-mode for keeping track of everything.\"
  4082. Org mode develops organizational tasks around a NOTES file which
  4083. contains information about projects as plain text. Org mode is
  4084. implemented on top of Outline mode, which is ideal to keep the content
  4085. of large files well structured. It supports ToDo items, deadlines and
  4086. time stamps, which magically appear in the diary listing of the Emacs
  4087. calendar. Tables are easily created with a built-in table editor.
  4088. Plain text URL-like links connect to websites, emails (VM), Usenet
  4089. messages (Gnus), BBDB entries, and any files related to the project.
  4090. For printing and sharing of notes, an Org file (or a part of it)
  4091. can be exported as a structured ASCII or HTML file.
  4092. The following commands are available:
  4093. \\{org-mode-map}"
  4094. (setq-local org-mode-loading t)
  4095. (org-load-modules-maybe)
  4096. (org-install-agenda-files-menu)
  4097. (when (and org-link-descriptive
  4098. (eq org-fold-core-style 'overlays))
  4099. (add-to-invisibility-spec '(org-link)))
  4100. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4101. "..."))
  4102. (make-local-variable 'org-link-descriptive)
  4103. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4104. (if org-link-descriptive
  4105. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4106. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4107. (setq-local outline-regexp org-outline-regexp)
  4108. (setq-local outline-level 'org-outline-level)
  4109. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4110. (unless org-display-table
  4111. (setq org-display-table (make-display-table)))
  4112. (set-display-table-slot
  4113. org-display-table 4
  4114. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4115. org-ellipsis)))
  4116. (setq buffer-display-table org-display-table))
  4117. (org-set-regexps-and-options)
  4118. (org-set-font-lock-defaults)
  4119. (when (and org-tag-faces (not org-tags-special-faces-re))
  4120. ;; tag faces set outside customize.... force initialization.
  4121. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4122. ;; Calc embedded
  4123. (setq-local calc-embedded-open-mode "# ")
  4124. ;; Modify a few syntax entries
  4125. (modify-syntax-entry ?\" "\"")
  4126. (modify-syntax-entry ?\\ "_")
  4127. (modify-syntax-entry ?~ "_")
  4128. (modify-syntax-entry ?< "(>")
  4129. (modify-syntax-entry ?> ")<")
  4130. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4131. ;; Activate before-change-function
  4132. (setq-local org-table-may-need-update t)
  4133. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4134. ;; Check for running clock before killing a buffer
  4135. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4136. ;; Initialize cache.
  4137. (org-element-cache-reset)
  4138. (when (and org-element-cache-persistent
  4139. org-element-use-cache)
  4140. (org-persist-load 'org-element--cache (current-buffer) t))
  4141. ;; Initialize macros templates.
  4142. (org-macro-initialize-templates)
  4143. ;; Initialize radio targets.
  4144. (org-update-radio-target-regexp)
  4145. ;; Indentation.
  4146. (setq-local indent-line-function 'org-indent-line)
  4147. (setq-local indent-region-function 'org-indent-region)
  4148. ;; Filling and auto-filling.
  4149. (org-setup-filling)
  4150. ;; Comments.
  4151. (org-setup-comments-handling)
  4152. ;; Beginning/end of defun
  4153. (setq-local beginning-of-defun-function 'org-backward-element)
  4154. (setq-local end-of-defun-function
  4155. (lambda ()
  4156. (if (not (org-at-heading-p))
  4157. (org-forward-element)
  4158. (org-forward-element)
  4159. (forward-char -1))))
  4160. ;; Next error for sparse trees
  4161. (setq-local next-error-function 'org-occur-next-match)
  4162. ;; Make commit log messages from Org documents easier.
  4163. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4164. ;; Make sure dependence stuff works reliably, even for users who set it
  4165. ;; too late :-(
  4166. (if org-enforce-todo-dependencies
  4167. (add-hook 'org-blocker-hook
  4168. 'org-block-todo-from-children-or-siblings-or-parent)
  4169. (remove-hook 'org-blocker-hook
  4170. 'org-block-todo-from-children-or-siblings-or-parent))
  4171. (if org-enforce-todo-checkbox-dependencies
  4172. (add-hook 'org-blocker-hook
  4173. 'org-block-todo-from-checkboxes)
  4174. (remove-hook 'org-blocker-hook
  4175. 'org-block-todo-from-checkboxes))
  4176. ;; Align options lines
  4177. (setq-local
  4178. align-mode-rules-list
  4179. '((org-in-buffer-settings
  4180. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4181. (modes . '(org-mode)))))
  4182. ;; Setup the pcomplete hooks
  4183. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4184. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4185. (setq-local pcomplete-default-completion-function #'ignore)
  4186. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4187. (setq-local pcomplete-termination-string "")
  4188. (add-hook 'completion-at-point-functions
  4189. #'pcomplete-completions-at-point nil t)
  4190. (setq-local buffer-face-mode-face 'org-default)
  4191. ;; If empty file that did not turn on Org mode automatically, make
  4192. ;; it to.
  4193. (when (and org-insert-mode-line-in-empty-file
  4194. (called-interactively-p 'any)
  4195. (= (point-min) (point-max)))
  4196. (insert "# -*- mode: org -*-\n\n"))
  4197. (unless org-inhibit-startup
  4198. (org-unmodified
  4199. (when org-startup-with-beamer-mode (org-beamer-mode))
  4200. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4201. (org-table-map-tables
  4202. (cond ((and org-startup-align-all-tables
  4203. org-startup-shrink-all-tables)
  4204. (lambda () (org-table-align) (org-table-shrink)))
  4205. (org-startup-align-all-tables #'org-table-align)
  4206. (t #'org-table-shrink))
  4207. t))
  4208. (when org-startup-with-inline-images (org-display-inline-images))
  4209. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4210. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4211. (when org-startup-truncated (setq truncate-lines t))
  4212. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4213. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4214. ;; Add a custom keymap for `visual-line-mode' so that activating
  4215. ;; this minor mode does not override Org's keybindings.
  4216. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4217. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4218. (newmap (make-sparse-keymap)))
  4219. (set-keymap-parent newmap oldmap)
  4220. (define-key newmap [remap move-beginning-of-line] nil)
  4221. (define-key newmap [remap move-end-of-line] nil)
  4222. (define-key newmap [remap kill-line] nil)
  4223. (make-local-variable 'minor-mode-overriding-map-alist)
  4224. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4225. ;; Activate `org-table-header-line-mode'
  4226. (when org-table-header-line-p
  4227. (org-table-header-line-mode 1))
  4228. ;; Try to set `org-hide' face correctly.
  4229. (let ((foreground (org-find-invisible-foreground)))
  4230. (when foreground
  4231. (set-face-foreground 'org-hide foreground)))
  4232. ;; Set face extension as requested.
  4233. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4234. org-fontify-whole-block-delimiter-line)
  4235. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4236. (setq-local org-mode-loading nil))
  4237. ;; Update `customize-package-emacs-version-alist'
  4238. (add-to-list 'customize-package-emacs-version-alist
  4239. '(Org ("8.0" . "24.4")
  4240. ("8.1" . "24.4")
  4241. ("8.2" . "24.4")
  4242. ("8.2.7" . "24.4")
  4243. ("8.3" . "26.1")
  4244. ("9.0" . "26.1")
  4245. ("9.1" . "26.1")
  4246. ("9.2" . "27.1")
  4247. ("9.3" . "27.1")
  4248. ("9.4" . "27.2")
  4249. ("9.5" . "28.1")
  4250. ("9.6" . "29.1")))
  4251. (defvar org-mode-transpose-word-syntax-table
  4252. (let ((st (make-syntax-table text-mode-syntax-table)))
  4253. (dolist (c org-emphasis-alist st)
  4254. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4255. (when (fboundp 'abbrev-table-put)
  4256. (abbrev-table-put org-mode-abbrev-table
  4257. :parents (list text-mode-abbrev-table)))
  4258. (defun org-find-invisible-foreground ()
  4259. (let ((candidates (remove
  4260. "unspecified-bg"
  4261. (nconc
  4262. (list (face-background 'default)
  4263. (face-background 'org-default))
  4264. (mapcar
  4265. (lambda (alist)
  4266. (when (boundp alist)
  4267. (cdr (assq 'background-color (symbol-value alist)))))
  4268. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4269. (list (face-foreground 'org-hide))))))
  4270. (car (remove nil candidates))))
  4271. (defun org-current-time (&optional rounding-minutes past)
  4272. "Current time, possibly rounded to ROUNDING-MINUTES.
  4273. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4274. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4275. the rounding returns a past time."
  4276. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4277. (car org-time-stamp-rounding-minutes)))
  4278. (now (current-time)))
  4279. (if (< r 1)
  4280. now
  4281. (let* ((time (decode-time now))
  4282. (res (org-encode-time
  4283. (apply #'list
  4284. 0 (* r (round (nth 1 time) r))
  4285. (nthcdr 2 time)))))
  4286. (if (or (not past) (time-less-p res now))
  4287. res
  4288. (time-subtract res (* r 60)))))))
  4289. (defun org-today ()
  4290. "Return today date, considering `org-extend-today-until'."
  4291. (time-to-days
  4292. (time-since (* 3600 org-extend-today-until))))
  4293. ;;;; Font-Lock stuff, including the activators
  4294. (defconst org-match-sexp-depth 3
  4295. "Number of stacked braces for sub/superscript matching.")
  4296. (defun org-create-multibrace-regexp (left right n)
  4297. "Create a regular expression which will match a balanced sexp.
  4298. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4299. as single character strings.
  4300. The regexp returned will match the entire expression including the
  4301. delimiters. It will also define a single group which contains the
  4302. match except for the outermost delimiters. The maximum depth of
  4303. stacked delimiters is N. Escaping delimiters is not possible."
  4304. (let* ((nothing (concat "[^" left right "]*?"))
  4305. (or "\\|")
  4306. (re nothing)
  4307. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4308. (while (> n 1)
  4309. (setq n (1- n)
  4310. re (concat re or next)
  4311. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4312. (concat left "\\(" re "\\)" right)))
  4313. (defconst org-match-substring-regexp
  4314. (concat
  4315. "\\(\\S-\\)\\([_^]\\)\\("
  4316. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4317. "\\|"
  4318. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4319. "\\|"
  4320. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4321. "The regular expression matching a sub- or superscript.")
  4322. (defconst org-match-substring-with-braces-regexp
  4323. (concat
  4324. "\\(\\S-\\)\\([_^]\\)"
  4325. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4326. "The regular expression matching a sub- or superscript, forcing braces.")
  4327. (defvar org-emph-face nil)
  4328. (defun org-do-emphasis-faces (limit)
  4329. "Run through the buffer and emphasize strings."
  4330. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4331. (car org-emphasis-regexp-components))))
  4332. (catch :exit
  4333. (while (re-search-forward quick-re limit t)
  4334. (let* ((marker (match-string 2))
  4335. (verbatim? (member marker '("~" "="))))
  4336. (when (save-excursion
  4337. (goto-char (match-beginning 0))
  4338. (and
  4339. ;; Do not match table hlines.
  4340. (not (and (equal marker "+")
  4341. (org-match-line
  4342. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4343. ;; Do not match headline stars. Do not consider
  4344. ;; stars of a headline as closing marker for bold
  4345. ;; markup either.
  4346. (not (and (equal marker "*")
  4347. (save-excursion
  4348. (forward-char)
  4349. (skip-chars-backward "*")
  4350. (looking-at-p org-outline-regexp-bol))))
  4351. ;; Match full emphasis markup regexp.
  4352. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4353. ;; Do not span over paragraph boundaries.
  4354. (not (string-match-p org-element-paragraph-separate
  4355. (match-string 2)))
  4356. ;; Do not span over cells in table rows.
  4357. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4358. (string-match-p "|" (match-string 4))))))
  4359. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4360. (m (if org-hide-emphasis-markers 4 2)))
  4361. (font-lock-prepend-text-property
  4362. (match-beginning m) (match-end m) 'face face)
  4363. (when verbatim?
  4364. (org-remove-flyspell-overlays-in
  4365. (match-beginning 0) (match-end 0))
  4366. (when (and (org-fold-core-folding-spec-p 'org-link)
  4367. (org-fold-core-folding-spec-p 'org-link-description))
  4368. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4369. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4370. (remove-text-properties (match-beginning 2) (match-end 2)
  4371. '(display t invisible t intangible t)))
  4372. (add-text-properties (match-beginning 2) (match-end 2)
  4373. '(font-lock-multiline t org-emphasis t))
  4374. (when (and org-hide-emphasis-markers
  4375. (not (org-at-comment-p)))
  4376. (add-text-properties (match-end 4) (match-beginning 5)
  4377. '(invisible t))
  4378. (add-text-properties (match-beginning 3) (match-end 3)
  4379. '(invisible t)))
  4380. (throw :exit t))))))))
  4381. (defun org-emphasize (&optional char)
  4382. "Insert or change an emphasis, i.e. a font like bold or italic.
  4383. If there is an active region, change that region to a new emphasis.
  4384. If there is no region, just insert the marker characters and position
  4385. the cursor between them.
  4386. CHAR should be the marker character. If it is a space, it means to
  4387. remove the emphasis of the selected region.
  4388. If CHAR is not given (for example in an interactive call) it will be
  4389. prompted for."
  4390. (interactive)
  4391. (let ((erc org-emphasis-regexp-components)
  4392. (string "") beg end move s)
  4393. (if (org-region-active-p)
  4394. (setq beg (region-beginning)
  4395. end (region-end)
  4396. string (buffer-substring beg end))
  4397. (setq move t))
  4398. (unless char
  4399. (message "Emphasis marker or tag: [%s]"
  4400. (mapconcat #'car org-emphasis-alist ""))
  4401. (setq char (read-char-exclusive)))
  4402. (if (equal char ?\s)
  4403. (setq s ""
  4404. move nil)
  4405. (unless (assoc (char-to-string char) org-emphasis-alist)
  4406. (user-error "No such emphasis marker: \"%c\"" char))
  4407. (setq s (char-to-string char)))
  4408. (while (and (> (length string) 1)
  4409. (equal (substring string 0 1) (substring string -1))
  4410. (assoc (substring string 0 1) org-emphasis-alist))
  4411. (setq string (substring string 1 -1)))
  4412. (setq string (concat s string s))
  4413. (when beg (delete-region beg end))
  4414. (unless (or (bolp)
  4415. (string-match (concat "[" (nth 0 erc) "\n]")
  4416. (char-to-string (char-before (point)))))
  4417. (insert " "))
  4418. (unless (or (eobp)
  4419. (string-match (concat "[" (nth 1 erc) "\n]")
  4420. (char-to-string (char-after (point)))))
  4421. (insert " ") (backward-char 1))
  4422. (insert string)
  4423. (and move (backward-char 1))))
  4424. (defconst org-nonsticky-props
  4425. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4426. (defsubst org-rear-nonsticky-at (pos)
  4427. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4428. (defun org-activate-links--overlays (limit)
  4429. "Add link properties to links.
  4430. This includes angle, plain, and bracket links."
  4431. (catch :exit
  4432. (while (re-search-forward org-link-any-re limit t)
  4433. (let* ((start (match-beginning 0))
  4434. (end (match-end 0))
  4435. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4436. (visible-end (or (match-end 3) (match-end 2)))
  4437. (style (cond ((eq ?< (char-after start)) 'angle)
  4438. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4439. (t 'plain))))
  4440. (when (and (memq style org-highlight-links)
  4441. ;; Do not span over paragraph boundaries.
  4442. (not (string-match-p org-element-paragraph-separate
  4443. (match-string 0)))
  4444. ;; Do not confuse plain links with tags.
  4445. (not (and (eq style 'plain)
  4446. (let ((face (get-text-property
  4447. (max (1- start) (point-min)) 'face)))
  4448. (if (consp face) (memq 'org-tag face)
  4449. (eq 'org-tag face))))))
  4450. (let* ((link-object (save-excursion
  4451. (goto-char start)
  4452. (save-match-data (org-element-link-parser))))
  4453. (link (org-element-property :raw-link link-object))
  4454. (type (org-element-property :type link-object))
  4455. (path (org-element-property :path link-object))
  4456. (face-property (pcase (org-link-get-parameter type :face)
  4457. ((and (pred functionp) face) (funcall face path))
  4458. ((and (pred facep) face) face)
  4459. ((and (pred consp) face) face) ;anonymous
  4460. (_ 'org-link)))
  4461. (properties ;for link's visible part
  4462. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4463. 'highlight)
  4464. 'keymap (or (org-link-get-parameter type :keymap)
  4465. org-mouse-map)
  4466. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4467. ((and (pred stringp) echo) echo)
  4468. ((and (pred functionp) echo) echo)
  4469. (_ (concat "LINK: " link)))
  4470. 'htmlize-link (pcase (org-link-get-parameter type
  4471. :htmlize-link)
  4472. ((and (pred functionp) f) (funcall f))
  4473. (_ `(:uri ,link)))
  4474. 'font-lock-multiline t)))
  4475. (org-remove-flyspell-overlays-in start end)
  4476. (org-rear-nonsticky-at end)
  4477. (if (not (eq 'bracket style))
  4478. (progn
  4479. (add-face-text-property start end face-property)
  4480. (add-text-properties start end properties))
  4481. ;; Handle invisible parts in bracket links.
  4482. (remove-text-properties start end '(invisible nil))
  4483. (let ((hidden
  4484. (append `(invisible
  4485. ,(or (org-link-get-parameter type :display)
  4486. 'org-link))
  4487. properties)))
  4488. (add-text-properties start visible-start hidden)
  4489. (add-face-text-property start end face-property)
  4490. (add-text-properties visible-start visible-end properties)
  4491. (add-text-properties visible-end end hidden)
  4492. (org-rear-nonsticky-at visible-start)
  4493. (org-rear-nonsticky-at visible-end)))
  4494. (let ((f (org-link-get-parameter type :activate-func)))
  4495. (when (functionp f)
  4496. (funcall f start end path (eq style 'bracket))))
  4497. (throw :exit t))))) ;signal success
  4498. nil))
  4499. (defun org-activate-links--text-properties (limit)
  4500. "Add link properties to links.
  4501. This includes angle, plain, and bracket links."
  4502. (catch :exit
  4503. (while (re-search-forward org-link-any-re limit t)
  4504. (let* ((start (match-beginning 0))
  4505. (end (match-end 0))
  4506. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4507. (visible-end (or (match-end 3) (match-end 2)))
  4508. (style (cond ((eq ?< (char-after start)) 'angle)
  4509. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4510. (t 'plain))))
  4511. (when (and (memq style org-highlight-links)
  4512. ;; Do not span over paragraph boundaries.
  4513. (not (string-match-p org-element-paragraph-separate
  4514. (match-string 0)))
  4515. ;; Do not confuse plain links with tags.
  4516. (not (and (eq style 'plain)
  4517. (let ((face (get-text-property
  4518. (max (1- start) (point-min)) 'face)))
  4519. (if (consp face) (memq 'org-tag face)
  4520. (eq 'org-tag face))))))
  4521. (let* ((link-object (save-excursion
  4522. (goto-char start)
  4523. (save-match-data (org-element-link-parser))))
  4524. (link (org-element-property :raw-link link-object))
  4525. (type (org-element-property :type link-object))
  4526. (path (org-element-property :path link-object))
  4527. (face-property (pcase (org-link-get-parameter type :face)
  4528. ((and (pred functionp) face) (funcall face path))
  4529. ((and (pred facep) face) face)
  4530. ((and (pred consp) face) face) ;anonymous
  4531. (_ 'org-link)))
  4532. (properties ;for link's visible part
  4533. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4534. 'highlight)
  4535. 'keymap (or (org-link-get-parameter type :keymap)
  4536. org-mouse-map)
  4537. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4538. ((and (pred stringp) echo) echo)
  4539. ((and (pred functionp) echo) echo)
  4540. (_ (concat "LINK: " link)))
  4541. 'htmlize-link (pcase (org-link-get-parameter type
  4542. :htmlize-link)
  4543. ((and (pred functionp) f) (funcall f))
  4544. (_ `(:uri ,link)))
  4545. 'font-lock-multiline t)))
  4546. (org-remove-flyspell-overlays-in start end)
  4547. (org-rear-nonsticky-at end)
  4548. (if (not (eq 'bracket style))
  4549. (progn
  4550. (add-face-text-property start end face-property)
  4551. (add-text-properties start end properties))
  4552. ;; Initialise folding when used outside org-mode.
  4553. (unless (or (derived-mode-p 'org-mode)
  4554. (and (org-fold-folding-spec-p 'org-link-description)
  4555. (org-fold-folding-spec-p 'org-link)))
  4556. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4557. "...")))
  4558. ;; Handle invisible parts in bracket links.
  4559. (let ((spec (or (org-link-get-parameter type :display)
  4560. 'org-link)))
  4561. (unless (org-fold-folding-spec-p spec)
  4562. (org-fold-add-folding-spec spec
  4563. (cdr org-link--link-folding-spec)
  4564. nil
  4565. 'append)
  4566. (org-fold-core-set-folding-spec-property spec :visible t))
  4567. (org-fold-region start end nil 'org-link)
  4568. (org-fold-region start end nil 'org-link-description)
  4569. ;; We are folding the whole emphasised text with SPEC
  4570. ;; first. It makes everything invisible (or whatever
  4571. ;; the user wants).
  4572. (org-fold-region start end t spec)
  4573. ;; The visible part of the text is folded using
  4574. ;; 'org-link-description, which is forcing this part of
  4575. ;; the text to be visible.
  4576. (org-fold-region visible-start visible-end t 'org-link-description)
  4577. (add-text-properties start end properties)
  4578. (add-face-text-property start end face-property)
  4579. (org-rear-nonsticky-at visible-start)
  4580. (org-rear-nonsticky-at visible-end)))
  4581. (let ((f (org-link-get-parameter type :activate-func)))
  4582. (when (functionp f)
  4583. (funcall f start end path (eq style 'bracket))))
  4584. (throw :exit t))))) ;signal success
  4585. nil))
  4586. (defsubst org-activate-links (limit)
  4587. "Add link properties to links.
  4588. This includes angle, plain, and bracket links."
  4589. (if (eq org-fold-core-style 'text-properties)
  4590. (org-activate-links--text-properties limit)
  4591. (org-activate-links--overlays limit)))
  4592. (defun org-activate-code (limit)
  4593. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4594. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4595. (remove-text-properties (match-beginning 0) (match-end 0)
  4596. '(display t invisible t intangible t))
  4597. t))
  4598. (defcustom org-src-fontify-natively t
  4599. "When non-nil, fontify code in code blocks.
  4600. See also the `org-block' face."
  4601. :type 'boolean
  4602. :version "26.1"
  4603. :package-version '(Org . "8.3")
  4604. :group 'org-appearance
  4605. :group 'org-babel)
  4606. (defcustom org-allow-promoting-top-level-subtree nil
  4607. "When non-nil, allow promoting a top level subtree.
  4608. The leading star of the top level headline will be replaced
  4609. by a #."
  4610. :type 'boolean
  4611. :version "24.1"
  4612. :group 'org-appearance)
  4613. (defun org-fontify-meta-lines-and-blocks (limit)
  4614. (condition-case nil
  4615. (org-fontify-meta-lines-and-blocks-1 limit)
  4616. (error (message "Org mode fontification error in %S at %d"
  4617. (current-buffer)
  4618. (line-number-at-pos)))))
  4619. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4620. "Fontify #+ lines and blocks."
  4621. (let ((case-fold-search t))
  4622. (when (re-search-forward
  4623. (rx bol (group (zero-or-more (any " \t")) "#"
  4624. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4625. (any " \t")
  4626. eol))
  4627. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4628. (zero-or-more (any " \t"))
  4629. (group (group (zero-or-more (not (any " \t\n"))))
  4630. (zero-or-more (any " \t"))
  4631. (group (zero-or-more any)))))
  4632. limit t)
  4633. (let ((beg (match-beginning 0))
  4634. (end-of-beginline (match-end 0))
  4635. ;; Including \n at end of #+begin line will include \n
  4636. ;; after the end of block content.
  4637. (block-start (match-end 0))
  4638. (block-end nil)
  4639. (lang (match-string 7)) ; The language, if it is a source block.
  4640. (bol-after-beginline (line-beginning-position 2))
  4641. (dc1 (downcase (match-string 2)))
  4642. (dc3 (downcase (match-string 3)))
  4643. (whole-blockline org-fontify-whole-block-delimiter-line)
  4644. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4645. (cond
  4646. ((and (match-end 4) (equal dc3 "+begin"))
  4647. ;; Truly a block
  4648. (setq block-type (downcase (match-string 5))
  4649. ;; Src, example, export, maybe more.
  4650. quoting (member block-type org-protecting-blocks))
  4651. (when (re-search-forward
  4652. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4653. (seq (zero-or-more (any " \t"))
  4654. "#+end"
  4655. ,(match-string 4)
  4656. word-end
  4657. (zero-or-more any)))))
  4658. ;; We look further than LIMIT on purpose.
  4659. nil t)
  4660. ;; We do have a matching #+end line.
  4661. (setq beg-of-endline (match-beginning 0)
  4662. end-of-endline (match-end 0)
  4663. nl-before-endline (1- (match-beginning 0)))
  4664. (setq block-end (match-beginning 0)) ; Include the final newline.
  4665. (when quoting
  4666. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4667. (remove-text-properties beg end-of-endline
  4668. '(display t invisible t intangible t)))
  4669. (add-text-properties
  4670. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4671. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4672. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4673. (cond
  4674. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4675. (save-match-data
  4676. (org-src-font-lock-fontify-block lang block-start block-end))
  4677. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4678. (quoting
  4679. (add-text-properties
  4680. bol-after-beginline beg-of-endline
  4681. (list 'face
  4682. (list :inherit
  4683. (let ((face-name
  4684. (intern (format "org-block-%s" lang))))
  4685. (append (and (facep face-name) (list face-name))
  4686. '(org-block)))))))
  4687. ((not org-fontify-quote-and-verse-blocks))
  4688. ((string= block-type "quote")
  4689. (add-face-text-property
  4690. bol-after-beginline beg-of-endline 'org-quote t))
  4691. ((string= block-type "verse")
  4692. (add-face-text-property
  4693. bol-after-beginline beg-of-endline 'org-verse t)))
  4694. ;; Fontify the #+begin and #+end lines of the blocks
  4695. (add-text-properties
  4696. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4697. '(face org-block-begin-line))
  4698. (unless (eq (char-after beg-of-endline) ?*)
  4699. (add-text-properties
  4700. beg-of-endline
  4701. (if whole-blockline
  4702. (let ((beg-of-next-line (1+ end-of-endline)))
  4703. (min (point-max) beg-of-next-line))
  4704. (min (point-max) end-of-endline))
  4705. '(face org-block-end-line)))
  4706. t))
  4707. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4708. (org-remove-flyspell-overlays-in
  4709. (match-beginning 0)
  4710. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4711. (add-text-properties
  4712. beg (match-end 3)
  4713. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4714. '(font-lock-fontified t invisible t)
  4715. '(font-lock-fontified t face org-document-info-keyword)))
  4716. (add-text-properties
  4717. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4718. (if (string-equal dc1 "+title:")
  4719. '(font-lock-fontified t face org-document-title)
  4720. '(font-lock-fontified t face org-document-info))))
  4721. ((string-prefix-p "+caption" dc1)
  4722. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4723. (remove-text-properties (match-beginning 0) (match-end 0)
  4724. '(display t invisible t intangible t))
  4725. ;; Handle short captions
  4726. (save-excursion
  4727. (beginning-of-line)
  4728. (looking-at (rx (group (zero-or-more (any " \t"))
  4729. "#+caption"
  4730. (optional "[" (zero-or-more any) "]")
  4731. ":")
  4732. (zero-or-more (any " \t")))))
  4733. (add-text-properties (line-beginning-position) (match-end 1)
  4734. '(font-lock-fontified t face org-meta-line))
  4735. (add-text-properties (match-end 0) (line-end-position)
  4736. '(font-lock-fontified t face org-block))
  4737. t)
  4738. ((member dc3 '(" " ""))
  4739. ;; Just a comment, the plus was not there
  4740. (org-remove-flyspell-overlays-in beg (match-end 0))
  4741. (add-text-properties
  4742. beg (match-end 0)
  4743. '(font-lock-fontified t face font-lock-comment-face)))
  4744. (t ;; Just any other in-buffer setting, but not indented
  4745. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4746. (remove-text-properties (match-beginning 0) (match-end 0)
  4747. '(display t invisible t intangible t))
  4748. (add-text-properties beg (match-end 0)
  4749. '(font-lock-fontified t face org-meta-line))
  4750. t))))))
  4751. (defun org-fontify-drawers (limit)
  4752. "Fontify drawers."
  4753. (when (re-search-forward org-drawer-regexp limit t)
  4754. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4755. '(font-lock-fontified t face org-drawer))
  4756. (org-remove-flyspell-overlays-in
  4757. (line-beginning-position) (line-beginning-position 2))
  4758. t))
  4759. (defun org-fontify-macros (limit)
  4760. "Fontify macros."
  4761. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4762. (let ((begin (match-beginning 0))
  4763. (opening-end (match-beginning 1)))
  4764. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4765. (match-string 1))
  4766. (let ((end (match-end 1))
  4767. (closing-start (match-beginning 1)))
  4768. (add-text-properties
  4769. begin end
  4770. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4771. (org-remove-flyspell-overlays-in begin end)
  4772. (when org-hide-macro-markers
  4773. (add-text-properties begin opening-end '(invisible t))
  4774. (add-text-properties closing-start end '(invisible t)))
  4775. t)))))
  4776. (defun org-fontify-extend-region (beg end _old-len)
  4777. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4778. (1+ end) end))
  4779. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4780. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4781. (extend
  4782. (lambda (r1 r2 dir)
  4783. (let ((re (replace-regexp-in-string
  4784. "\\(begin\\|end\\)" r1
  4785. (replace-regexp-in-string
  4786. "[][]" r2
  4787. (match-string-no-properties 0)))))
  4788. (re-search-forward (regexp-quote re) nil t dir)))))
  4789. (goto-char beg)
  4790. (back-to-indentation)
  4791. (save-match-data
  4792. (cond ((looking-at end-re)
  4793. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4794. ((looking-at begin-re)
  4795. (cons beg (or (funcall extend "end" "]" 1) end)))
  4796. (t (cons beg end))))))
  4797. (defun org-activate-footnote-links (limit)
  4798. "Add text properties for footnotes."
  4799. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4800. (when fn
  4801. (let* ((beg (nth 1 fn))
  4802. (end (nth 2 fn))
  4803. (label (car fn))
  4804. (referencep (/= (line-beginning-position) beg)))
  4805. (when (and referencep (nth 3 fn))
  4806. (save-excursion
  4807. (goto-char beg)
  4808. (search-forward (or label "fn:"))
  4809. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4810. (add-text-properties beg end
  4811. (list 'mouse-face 'highlight
  4812. 'keymap org-mouse-map
  4813. 'help-echo
  4814. (if referencep "Footnote reference"
  4815. "Footnote definition")
  4816. 'font-lock-fontified t
  4817. 'font-lock-multiline t
  4818. 'face 'org-footnote))))))
  4819. (defun org-activate-dates (limit)
  4820. "Add text properties for dates."
  4821. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4822. (not (equal (char-before (match-beginning 0)) 91)))
  4823. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4824. (add-text-properties (match-beginning 0) (match-end 0)
  4825. (list 'mouse-face 'highlight
  4826. 'keymap org-mouse-map))
  4827. (org-rear-nonsticky-at (match-end 0))
  4828. (when org-display-custom-times
  4829. ;; If it's a date range, activate custom time for second date.
  4830. (when (match-end 3)
  4831. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4832. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4833. t))
  4834. (defun org-activate-target-links (limit)
  4835. "Add text properties for target matches."
  4836. (when org-target-link-regexp
  4837. (let ((case-fold-search t))
  4838. ;; `org-target-link-regexp' matches one character before the
  4839. ;; actual target.
  4840. (unless (bolp) (forward-char -1))
  4841. (when (re-search-forward org-target-link-regexp limit t)
  4842. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4843. (add-text-properties (match-beginning 1) (match-end 1)
  4844. (list 'mouse-face 'highlight
  4845. 'keymap org-mouse-map
  4846. 'help-echo "Radio target link"
  4847. 'org-linked-text t))
  4848. (org-rear-nonsticky-at (match-end 1))
  4849. t))))
  4850. (defvar org-latex-and-related-regexp nil
  4851. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4852. (defun org-compute-latex-and-related-regexp ()
  4853. "Compute regular expression for LaTeX, entities and sub/superscript.
  4854. Result depends on variable `org-highlight-latex-and-related'."
  4855. (let ((re-sub
  4856. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4857. ((eq org-use-sub-superscripts '{})
  4858. (list org-match-substring-with-braces-regexp))
  4859. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4860. (re-latex
  4861. (when (or (memq 'latex org-highlight-latex-and-related)
  4862. (memq 'native org-highlight-latex-and-related))
  4863. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4864. (delq nil
  4865. (mapcar (lambda (x)
  4866. (and (member (car x) matchers) (nth 1 x)))
  4867. org-latex-regexps)))))
  4868. (re-entities
  4869. (when (memq 'entities org-highlight-latex-and-related)
  4870. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4871. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4872. (setq-local org-latex-and-related-regexp
  4873. (mapconcat #'identity
  4874. (append re-latex re-entities re-sub)
  4875. "\\|"))))
  4876. (defun org-do-latex-and-related (limit)
  4877. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4878. Stop at first highlighted object, if any. Return t if some
  4879. highlighting was done, nil otherwise."
  4880. (when (org-string-nw-p org-latex-and-related-regexp)
  4881. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4882. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4883. (catch 'found
  4884. (while (and (< (point) limit)
  4885. (re-search-forward org-latex-and-related-regexp nil t))
  4886. (cond
  4887. ((>= (match-beginning 0) limit)
  4888. (throw 'found nil))
  4889. ((cl-some (lambda (f)
  4890. (memq f '(org-code org-verbatim underline
  4891. org-special-keyword)))
  4892. (save-excursion
  4893. (goto-char (1+ (match-beginning 0)))
  4894. (face-at-point nil t))))
  4895. ;; Try to limit false positives. In this case, ignore
  4896. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4897. ;; contain an empty line.
  4898. ((save-excursion
  4899. (goto-char (match-beginning 0))
  4900. (and (looking-at-p latex-prefix-re)
  4901. (save-match-data
  4902. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4903. (t
  4904. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4905. '(?_ ?^))
  4906. 1
  4907. 0))
  4908. (start (+ offset (match-beginning 0)))
  4909. (end (match-end 0)))
  4910. (if (memq 'native org-highlight-latex-and-related)
  4911. (org-src-font-lock-fontify-block "latex" start end)
  4912. (font-lock-prepend-text-property start end
  4913. 'face 'org-latex-and-related))
  4914. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4915. '(font-lock-multiline t))
  4916. (throw 'found t)))))
  4917. nil))))
  4918. (defun org-restart-font-lock ()
  4919. "Restart `font-lock-mode', to force refontification."
  4920. (when font-lock-mode
  4921. (font-lock-mode -1)
  4922. (font-lock-mode 1)))
  4923. (defun org-activate-tags (limit)
  4924. (when (re-search-forward org-tag-line-re limit t)
  4925. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4926. (add-text-properties (match-beginning 1) (match-end 1)
  4927. (list 'mouse-face 'highlight
  4928. 'keymap org-mouse-map))
  4929. (org-rear-nonsticky-at (match-end 1))
  4930. t))
  4931. (defun org-outline-level ()
  4932. "Compute the outline level of the heading at point.
  4933. If this is called at a normal headline, the level is the number
  4934. of stars. Use `org-reduced-level' to remove the effect of
  4935. `org-odd-levels'. Unlike to `org-current-level', this function
  4936. takes into consideration inlinetasks."
  4937. (org-with-wide-buffer
  4938. (end-of-line)
  4939. (if (re-search-backward org-outline-regexp-bol nil t)
  4940. (1- (- (match-end 0) (match-beginning 0)))
  4941. 0)))
  4942. (defvar org-font-lock-keywords nil)
  4943. (defsubst org-re-property (property &optional literal allow-null value)
  4944. "Return a regexp matching a PROPERTY line.
  4945. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4946. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4947. non-nil, match properties even without a value.
  4948. Match group 3 is set to the value when it exists. If there is no
  4949. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4950. With optional argument VALUE, match only property lines with
  4951. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4952. unless LITERAL is non-nil."
  4953. (concat
  4954. "^\\(?4:[ \t]*\\)"
  4955. (format "\\(?1::\\(?2:%s\\):\\)"
  4956. (if literal property (regexp-quote property)))
  4957. (cond (value
  4958. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4959. (if literal value (regexp-quote value))))
  4960. (allow-null
  4961. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4962. (t
  4963. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4964. (defconst org-property-re
  4965. (org-re-property "\\S-+" 'literal t)
  4966. "Regular expression matching a property line.
  4967. There are four matching groups:
  4968. 1: :PROPKEY: including the leading and trailing colon,
  4969. 2: PROPKEY without the leading and trailing colon,
  4970. 3: PROPVAL without leading or trailing spaces,
  4971. 4: the indentation of the current line,
  4972. 5: trailing whitespace.")
  4973. (defvar org-font-lock-hook nil
  4974. "Functions to be called for special font lock stuff.")
  4975. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4976. (defvar org-font-lock-set-keywords-hook nil
  4977. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4978. This is called after `org-font-lock-extra-keywords' is defined, but before
  4979. it is installed to be used by font lock. This can be useful if something
  4980. needs to be inserted at a specific position in the font-lock sequence.")
  4981. (defun org-font-lock-hook (limit)
  4982. "Run `org-font-lock-hook' within LIMIT."
  4983. (run-hook-with-args 'org-font-lock-hook limit))
  4984. (defun org-set-font-lock-defaults ()
  4985. "Set font lock defaults for the current buffer."
  4986. (let ((org-font-lock-extra-keywords
  4987. (list
  4988. ;; Call the hook
  4989. '(org-font-lock-hook)
  4990. ;; Headlines
  4991. `(,(if org-fontify-whole-heading-line
  4992. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4993. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4994. (1 (org-get-level-face 1))
  4995. (2 (org-get-level-face 2))
  4996. (3 (org-get-level-face 3)))
  4997. ;; Table lines
  4998. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4999. (1 'org-table t))
  5000. ;; Table internals
  5001. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  5002. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  5003. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  5004. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  5005. ;; Properties
  5006. (list org-property-re
  5007. '(1 'org-special-keyword t)
  5008. '(3 'org-property-value t))
  5009. ;; Drawers
  5010. '(org-fontify-drawers)
  5011. ;; Link related fontification.
  5012. '(org-activate-links)
  5013. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  5014. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  5015. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  5016. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5017. ;; Targets.
  5018. (list org-radio-target-regexp '(0 'org-target t))
  5019. (list org-target-regexp '(0 'org-target t))
  5020. ;; Diary sexps.
  5021. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5022. ;; Macro
  5023. '(org-fontify-macros)
  5024. ;; TODO keyword
  5025. (list (format org-heading-keyword-regexp-format
  5026. org-todo-regexp)
  5027. '(2 (org-get-todo-face 2) prepend))
  5028. ;; TODO
  5029. (when org-fontify-todo-headline
  5030. (list (format org-heading-keyword-regexp-format
  5031. (concat
  5032. "\\(?:"
  5033. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5034. "\\)"))
  5035. '(2 'org-headline-todo prepend)))
  5036. ;; DONE
  5037. (when org-fontify-done-headline
  5038. (list (format org-heading-keyword-regexp-format
  5039. (concat
  5040. "\\(?:"
  5041. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5042. "\\)"))
  5043. '(2 'org-headline-done prepend)))
  5044. ;; Priorities
  5045. '(org-font-lock-add-priority-faces)
  5046. ;; Tags
  5047. '(org-font-lock-add-tag-faces)
  5048. ;; Tags groups
  5049. (when (and org-group-tags org-tag-groups-alist)
  5050. (list (concat org-outline-regexp-bol ".+\\(:"
  5051. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5052. ":\\).*$")
  5053. '(1 'org-tag-group prepend)))
  5054. ;; Special keywords
  5055. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5056. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5057. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5058. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5059. ;; Emphasis
  5060. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5061. ;; Checkboxes
  5062. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5063. 1 'org-checkbox prepend)
  5064. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5065. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5066. (0 (org-get-checkbox-statistics-face) prepend)))
  5067. ;; Description list items
  5068. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5069. 1 'org-list-dt prepend)
  5070. ;; Inline export snippets
  5071. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5072. (1 'font-lock-comment-face t)
  5073. (2 'org-tag t)
  5074. (3 'font-lock-comment-face t))
  5075. ;; ARCHIVEd headings
  5076. (list (concat
  5077. org-outline-regexp-bol
  5078. "\\(.*:" org-archive-tag ":.*\\)")
  5079. '(1 'org-archived prepend))
  5080. ;; Specials
  5081. '(org-do-latex-and-related)
  5082. '(org-fontify-entities)
  5083. '(org-raise-scripts)
  5084. ;; Code
  5085. '(org-activate-code (1 'org-code t))
  5086. ;; COMMENT
  5087. (list (format
  5088. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5089. org-todo-regexp
  5090. org-comment-string)
  5091. '(9 'org-special-keyword t))
  5092. ;; Blocks and meta lines
  5093. '(org-fontify-meta-lines-and-blocks)
  5094. '(org-fontify-inline-src-blocks)
  5095. ;; Citations. When an activate processor is specified, if
  5096. ;; specified, try loading it beforehand.
  5097. (progn
  5098. (unless (null org-cite-activate-processor)
  5099. (org-cite-try-load-processor org-cite-activate-processor))
  5100. '(org-cite-activate)))))
  5101. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5102. (run-hooks 'org-font-lock-set-keywords-hook)
  5103. ;; Now set the full font-lock-keywords
  5104. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5105. (setq-local font-lock-defaults
  5106. '(org-font-lock-keywords t nil nil backward-paragraph))
  5107. (setq-local font-lock-extend-after-change-region-function
  5108. #'org-fontify-extend-region)
  5109. (kill-local-variable 'font-lock-keywords)
  5110. nil))
  5111. (defun org-toggle-pretty-entities ()
  5112. "Toggle the composition display of entities as UTF8 characters."
  5113. (interactive)
  5114. (setq-local org-pretty-entities (not org-pretty-entities))
  5115. (org-restart-font-lock)
  5116. (if org-pretty-entities
  5117. (message "Entities are now displayed as UTF8 characters")
  5118. (save-restriction
  5119. (widen)
  5120. (decompose-region (point-min) (point-max))
  5121. (message "Entities are now displayed as plain text"))))
  5122. (defvar-local org-custom-properties-overlays nil
  5123. "List of overlays used for custom properties.")
  5124. (defun org-toggle-custom-properties-visibility ()
  5125. "Display or hide properties in `org-custom-properties'."
  5126. (interactive)
  5127. (if org-custom-properties-overlays
  5128. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5129. (setq org-custom-properties-overlays nil))
  5130. (when org-custom-properties
  5131. (org-with-wide-buffer
  5132. (goto-char (point-min))
  5133. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5134. (while (re-search-forward regexp nil t)
  5135. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5136. (when (and end (< (point) end))
  5137. ;; Hide first custom property in current drawer.
  5138. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5139. (overlay-put o 'invisible t)
  5140. (overlay-put o 'org-custom-property t)
  5141. (push o org-custom-properties-overlays))
  5142. ;; Hide additional custom properties in the same drawer.
  5143. (while (re-search-forward regexp end t)
  5144. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5145. (overlay-put o 'invisible t)
  5146. (overlay-put o 'org-custom-property t)
  5147. (push o org-custom-properties-overlays)))))
  5148. ;; Each entry is limited to a single property drawer.
  5149. (outline-next-heading)))))))
  5150. (defun org-fontify-entities (limit)
  5151. "Find an entity to fontify."
  5152. (let (ee)
  5153. (when org-pretty-entities
  5154. (catch 'match
  5155. ;; "\_ "-family is left out on purpose. Only the first one,
  5156. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5157. ;; confusing when adding a second white space character.
  5158. (while (re-search-forward
  5159. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5160. limit t)
  5161. (when (and (not (org-at-comment-p))
  5162. (setq ee (org-entity-get (match-string 1)))
  5163. (= (length (nth 6 ee)) 1))
  5164. (let* ((end (if (equal (match-string 2) "{}")
  5165. (match-end 2)
  5166. (match-end 1))))
  5167. (add-text-properties
  5168. (match-beginning 0) end
  5169. (list 'font-lock-fontified t))
  5170. (compose-region (match-beginning 0) end
  5171. (nth 6 ee) nil)
  5172. (backward-char 1)
  5173. (throw 'match t))))
  5174. nil))))
  5175. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5176. "Fontify string S like in Org mode."
  5177. (with-temp-buffer
  5178. (insert s)
  5179. (let ((org-odd-levels-only odd-levels))
  5180. (org-mode)
  5181. (font-lock-ensure)
  5182. (if org-link-descriptive
  5183. (org-link-display-format
  5184. (buffer-string))
  5185. (buffer-string)))))
  5186. (defun org-get-level-face (n)
  5187. "Get the right face for match N in font-lock matching of headlines."
  5188. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5189. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5190. (org-f (if org-cycle-level-faces
  5191. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5192. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5193. (cond
  5194. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5195. ((eq n 2) org-f)
  5196. (t (unless org-level-color-stars-only org-f)))))
  5197. (defun org-face-from-face-or-color (context inherit face-or-color)
  5198. "Create a face list that inherits INHERIT, but sets the foreground color.
  5199. When FACE-OR-COLOR is not a string, just return it."
  5200. (if (stringp face-or-color)
  5201. (list :inherit inherit
  5202. (cdr (assoc context org-faces-easy-properties))
  5203. face-or-color)
  5204. face-or-color))
  5205. (defun org-get-todo-face (kwd)
  5206. "Get the right face for a TODO keyword KWD.
  5207. If KWD is a number, get the corresponding match group."
  5208. (when (numberp kwd) (setq kwd (match-string kwd)))
  5209. (or (org-face-from-face-or-color
  5210. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5211. (and (member kwd org-done-keywords) 'org-done)
  5212. 'org-todo))
  5213. (defun org-get-priority-face (priority)
  5214. "Get the right face for PRIORITY.
  5215. PRIORITY is a character."
  5216. (or (org-face-from-face-or-color
  5217. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5218. 'org-priority))
  5219. (defun org-get-tag-face (tag)
  5220. "Get the right face for TAG.
  5221. If TAG is a number, get the corresponding match group."
  5222. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5223. (or (org-face-from-face-or-color
  5224. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5225. 'org-tag)))
  5226. (defvar org-priority-regexp) ; defined later in the file
  5227. (defun org-font-lock-add-priority-faces (limit)
  5228. "Add the special priority faces."
  5229. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5230. (let ((beg (match-beginning 1))
  5231. (end (1+ (match-end 2))))
  5232. (add-face-text-property
  5233. beg end
  5234. (org-get-priority-face (string-to-char (match-string 2))))
  5235. (add-text-properties
  5236. beg end
  5237. (list 'font-lock-fontified t)))))
  5238. (defun org-font-lock-add-tag-faces (limit)
  5239. "Add the special tag faces."
  5240. (when (and org-tag-faces org-tags-special-faces-re)
  5241. (while (re-search-forward org-tags-special-faces-re limit t)
  5242. (add-face-text-property
  5243. (match-beginning 1)
  5244. (match-end 1)
  5245. (org-get-tag-face 1))
  5246. (add-text-properties (match-beginning 1) (match-end 1)
  5247. (list 'font-lock-fontified t))
  5248. (backward-char 1))))
  5249. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5250. "Remove fontification and activation overlays from links."
  5251. (font-lock-default-unfontify-region beg end)
  5252. (let* ((buffer-undo-list t)
  5253. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5254. (inhibit-modification-hooks t)
  5255. deactivate-mark buffer-file-name buffer-file-truename)
  5256. (decompose-region beg end)
  5257. (remove-text-properties beg end
  5258. '(mouse-face t keymap t org-linked-text t
  5259. invisible t intangible t
  5260. org-emphasis t))
  5261. (org-fold-region beg end nil 'org-link)
  5262. (org-fold-region beg end nil 'org-link-description)
  5263. (org-fold-core-update-optimisation beg end)
  5264. (org-remove-font-lock-display-properties beg end)))
  5265. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5266. ((raise 0.3) (height 0.7))
  5267. ((raise -0.5))
  5268. ((raise 0.5)))
  5269. "Display properties for showing superscripts and subscripts.")
  5270. (defun org-remove-font-lock-display-properties (beg end)
  5271. "Remove specific display properties that have been added by font lock.
  5272. The will remove the raise properties that are used to show superscripts
  5273. and subscripts."
  5274. (let (next prop)
  5275. (while (< beg end)
  5276. (setq next (next-single-property-change beg 'display nil end)
  5277. prop (get-text-property beg 'display))
  5278. (when (member prop org-script-display)
  5279. (put-text-property beg next 'display nil))
  5280. (setq beg next))))
  5281. (defun org-raise-scripts (limit)
  5282. "Add raise properties to sub/superscripts."
  5283. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5284. (re-search-forward
  5285. (if (eq org-use-sub-superscripts t)
  5286. org-match-substring-regexp
  5287. org-match-substring-with-braces-regexp)
  5288. limit t))
  5289. (let* ((pos (point)) table-p comment-p
  5290. (mpos (match-beginning 3))
  5291. (emph-p (get-text-property mpos 'org-emphasis))
  5292. (link-p (get-text-property mpos 'mouse-face))
  5293. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5294. (goto-char (point-at-bol))
  5295. (setq table-p (looking-at-p org-table-dataline-regexp)
  5296. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5297. (goto-char pos)
  5298. ;; Handle a_b^c
  5299. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5300. (unless (or comment-p emph-p link-p keyw-p)
  5301. (put-text-property (match-beginning 3) (match-end 0)
  5302. 'display
  5303. (if (equal (char-after (match-beginning 2)) ?^)
  5304. (nth (if table-p 3 1) org-script-display)
  5305. (nth (if table-p 2 0) org-script-display)))
  5306. (put-text-property (match-beginning 2) (match-end 3)
  5307. 'org-emphasis t)
  5308. (add-text-properties (match-beginning 2) (match-end 2)
  5309. (list 'invisible t))
  5310. (when (and (eq (char-after (match-beginning 3)) ?{)
  5311. (eq (char-before (match-end 3)) ?}))
  5312. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5313. (list 'invisible t))
  5314. (add-text-properties (1- (match-end 3)) (match-end 3)
  5315. (list 'invisible t))))
  5316. t)))
  5317. (defun org-remove-empty-overlays-at (pos)
  5318. "Remove outline overlays that do not contain non-white stuff."
  5319. (dolist (o (overlays-at pos))
  5320. (and (eq 'outline (overlay-get o 'invisible))
  5321. (not (string-match-p
  5322. "\\S-" (buffer-substring (overlay-start o)
  5323. (overlay-end o))))
  5324. (delete-overlay o))))
  5325. ;; FIXME: This function is unused.
  5326. (defun org-show-empty-lines-in-parent ()
  5327. "Move to the parent and re-show empty lines before visible headlines."
  5328. (save-excursion
  5329. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5330. (org-cycle-show-empty-lines context))))
  5331. (defun org-files-list ()
  5332. "Return `org-agenda-files' list, plus all open Org files.
  5333. This is useful for operations that need to scan all of a user's
  5334. open and agenda-wise Org files."
  5335. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5336. (dolist (buf (buffer-list))
  5337. (with-current-buffer buf
  5338. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5339. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5340. :test #'equal))))
  5341. files))
  5342. (defsubst org-entry-beginning-position ()
  5343. "Return the beginning position of the current entry."
  5344. (save-excursion (org-back-to-heading t) (point)))
  5345. (defsubst org-entry-end-position ()
  5346. "Return the end position of the current entry."
  5347. (save-excursion (outline-next-heading) (point)))
  5348. (defun org-subtree-end-visible-p ()
  5349. "Is the end of the current subtree visible?"
  5350. (pos-visible-in-window-p
  5351. (save-excursion (org-end-of-subtree t) (point))))
  5352. (defun org-first-headline-recenter ()
  5353. "Move cursor to the first headline and recenter the headline."
  5354. (let ((window (get-buffer-window)))
  5355. (when window
  5356. (goto-char (point-min))
  5357. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5358. (set-window-start window (line-beginning-position))))))
  5359. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5360. (defvar org-called-with-limited-levels nil
  5361. "Non-nil when `org-with-limited-levels' is currently active.")
  5362. ;;; Indirect buffer display of subtrees
  5363. (defvar org-indirect-dedicated-frame nil
  5364. "This is the frame being used for indirect tree display.")
  5365. (defvar org-last-indirect-buffer nil)
  5366. (defun org-tree-to-indirect-buffer (&optional arg)
  5367. "Create indirect buffer and narrow it to current subtree.
  5368. With a numerical prefix ARG, go up to this level and then take that tree.
  5369. If ARG is negative, go up that many levels.
  5370. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5371. indirect buffer previously made with this command, to avoid proliferation of
  5372. indirect buffers. However, when you call the command with a \
  5373. `\\[universal-argument]' prefix, or
  5374. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5375. so that you can work with several indirect buffers at the same time. If
  5376. `org-indirect-buffer-display' is `dedicated-frame', the \
  5377. `\\[universal-argument]' prefix also
  5378. requests that a new frame be made for the new buffer, so that the dedicated
  5379. frame is not changed."
  5380. (interactive "P")
  5381. (let ((cbuf (current-buffer))
  5382. (cwin (selected-window))
  5383. (pos (point))
  5384. beg end level heading ibuf)
  5385. (save-excursion
  5386. (org-back-to-heading t)
  5387. (when (numberp arg)
  5388. (setq level (org-outline-level))
  5389. (when (< arg 0) (setq arg (+ level arg)))
  5390. (while (> (setq level (org-outline-level)) arg)
  5391. (org-up-heading-safe)))
  5392. (setq beg (point)
  5393. heading (org-get-heading 'no-tags))
  5394. (org-end-of-subtree t t)
  5395. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5396. (setq end (point)))
  5397. (when (and (buffer-live-p org-last-indirect-buffer)
  5398. (not (eq org-indirect-buffer-display 'new-frame))
  5399. (not arg))
  5400. (kill-buffer org-last-indirect-buffer))
  5401. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5402. org-last-indirect-buffer ibuf)
  5403. (cond
  5404. ((or (eq org-indirect-buffer-display 'new-frame)
  5405. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5406. (select-frame (make-frame))
  5407. (delete-other-windows)
  5408. (pop-to-buffer-same-window ibuf)
  5409. (org-set-frame-title heading))
  5410. ((eq org-indirect-buffer-display 'dedicated-frame)
  5411. (raise-frame
  5412. (select-frame (or (and org-indirect-dedicated-frame
  5413. (frame-live-p org-indirect-dedicated-frame)
  5414. org-indirect-dedicated-frame)
  5415. (setq org-indirect-dedicated-frame (make-frame)))))
  5416. (delete-other-windows)
  5417. (pop-to-buffer-same-window ibuf)
  5418. (org-set-frame-title (concat "Indirect: " heading)))
  5419. ((eq org-indirect-buffer-display 'current-window)
  5420. (pop-to-buffer-same-window ibuf))
  5421. ((eq org-indirect-buffer-display 'other-window)
  5422. (pop-to-buffer ibuf))
  5423. (t (error "Invalid value")))
  5424. (narrow-to-region beg end)
  5425. (org-fold-show-all '(headings drawers blocks))
  5426. (goto-char pos)
  5427. (run-hook-with-args 'org-cycle-hook 'all)
  5428. (and (window-live-p cwin) (select-window cwin))))
  5429. (defun org-get-indirect-buffer (&optional buffer heading)
  5430. (setq buffer (or buffer (current-buffer)))
  5431. (let ((n 1) (base (buffer-name buffer)) bname)
  5432. (while (buffer-live-p
  5433. (get-buffer
  5434. (setq bname
  5435. (concat base "-"
  5436. (if heading (concat heading "-" (number-to-string n))
  5437. (number-to-string n))))))
  5438. (setq n (1+ n)))
  5439. (condition-case nil
  5440. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5441. ;; Decouple folding state. We need to do it manually since
  5442. ;; `make-indirect-buffer' does not run
  5443. ;; `clone-indirect-buffer-hook'.
  5444. (org-fold-core-decouple-indirect-buffer-folds)
  5445. ;; Return the buffer.
  5446. indirect-buffer)
  5447. (error (make-indirect-buffer buffer bname)))))
  5448. (defun org-set-frame-title (title)
  5449. "Set the title of the current frame to the string TITLE."
  5450. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5451. ;;;; Structure editing
  5452. ;;; Inserting headlines
  5453. (defun org--blank-before-heading-p (&optional parent)
  5454. "Non-nil when an empty line should precede a new heading here.
  5455. When optional argument PARENT is non-nil, consider parent
  5456. headline instead of current one."
  5457. (pcase (assq 'heading org-blank-before-new-entry)
  5458. (`(heading . auto)
  5459. (save-excursion
  5460. (org-with-limited-levels
  5461. (unless (and (org-before-first-heading-p)
  5462. (not (outline-next-heading)))
  5463. (org-back-to-heading t)
  5464. (when parent (org-up-heading-safe))
  5465. (cond ((not (bobp))
  5466. (org-previous-line-empty-p))
  5467. ((outline-next-heading)
  5468. (org-previous-line-empty-p))
  5469. ;; Ignore trailing spaces on last buffer line.
  5470. ((progn (skip-chars-backward " \t") (bolp))
  5471. (org-previous-line-empty-p))
  5472. (t nil))))))
  5473. (`(heading . ,value) value)
  5474. (_ nil)))
  5475. (defun org-insert-heading (&optional arg invisible-ok top)
  5476. "Insert a new heading or an item with the same depth at point.
  5477. If point is at the beginning of a heading, insert a new heading
  5478. or a new headline above the current one. When at the beginning
  5479. of a regular line of text, turn it into a heading.
  5480. If point is in the middle of a line, split it and create a new
  5481. headline with the text in the current line after point (see
  5482. `org-M-RET-may-split-line' on how to modify this behavior). As
  5483. a special case, on a headline, splitting can only happen on the
  5484. title itself. E.g., this excludes breaking stars or tags.
  5485. With a `\\[universal-argument]' prefix, set \
  5486. `org-insert-heading-respect-content' to
  5487. a non-nil value for the duration of the command. This forces the
  5488. insertion of a heading after the current subtree, independently
  5489. on the location of point.
  5490. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5491. insert the heading at the end of the tree
  5492. above the current heading. For example, if point is within a
  5493. 2nd-level heading, then it will insert a 2nd-level heading at
  5494. the end of the 1st-level parent subtree.
  5495. When INVISIBLE-OK is set, stop at invisible headlines when going
  5496. back. This is important for non-interactive uses of the
  5497. command.
  5498. When optional argument TOP is non-nil, insert a level 1 heading,
  5499. unconditionally."
  5500. (interactive "P")
  5501. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5502. (level (org-current-level))
  5503. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5504. (cond
  5505. ((or org-insert-heading-respect-content
  5506. (member arg '((4) (16)))
  5507. (and (not invisible-ok)
  5508. (invisible-p (max (1- (point)) (point-min)))))
  5509. ;; Position point at the location of insertion. Make sure we
  5510. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5511. (org-with-limited-levels
  5512. (if (not level) (outline-next-heading) ;before first headline
  5513. (org-back-to-heading invisible-ok)
  5514. (when (equal arg '(16)) (org-up-heading-safe))
  5515. (org-end-of-subtree)))
  5516. (unless (bolp) (insert "\n"))
  5517. (when (and blank? (save-excursion
  5518. (backward-char)
  5519. (org-before-first-heading-p)))
  5520. (insert "\n")
  5521. (backward-char))
  5522. (when (and (not level) (not (eobp)) (not (bobp)))
  5523. (when (org-at-heading-p) (insert "\n"))
  5524. (backward-char))
  5525. (unless (and blank? (org-previous-line-empty-p))
  5526. (org-N-empty-lines-before-current (if blank? 1 0)))
  5527. (insert stars " ")
  5528. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5529. ;; is visible.
  5530. (unless invisible-ok
  5531. (if (eq org-fold-core-style 'text-properties)
  5532. (cond
  5533. ((org-fold-folded-p
  5534. (max (point-min)
  5535. (1- (line-beginning-position)))
  5536. 'headline)
  5537. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5538. (t nil))
  5539. (pcase (get-char-property-and-overlay (point) 'invisible)
  5540. (`(outline . ,o)
  5541. (move-overlay o (overlay-start o) (line-end-position 0)))
  5542. (_ nil)))))
  5543. ;; At a headline...
  5544. ((org-at-heading-p)
  5545. (cond ((bolp)
  5546. (when blank? (save-excursion (insert "\n")))
  5547. (save-excursion (insert stars " \n"))
  5548. (unless (and blank? (org-previous-line-empty-p))
  5549. (org-N-empty-lines-before-current (if blank? 1 0)))
  5550. (end-of-line))
  5551. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5552. (org-match-line org-complex-heading-regexp)
  5553. (org-pos-in-match-range (point) 4))
  5554. ;; Grab the text that should moved to the new headline.
  5555. ;; Preserve tags.
  5556. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5557. (if (looking-at "[ \t]*$") (replace-match "")
  5558. (org-align-tags))
  5559. (end-of-line)
  5560. (when blank? (insert "\n"))
  5561. (insert "\n" stars " ")
  5562. (when (org-string-nw-p split) (insert split))))
  5563. (t
  5564. (end-of-line)
  5565. (when blank? (insert "\n"))
  5566. (insert "\n" stars " "))))
  5567. ;; On regular text, turn line into a headline or split, if
  5568. ;; appropriate.
  5569. ((bolp)
  5570. (insert stars " ")
  5571. (unless (and blank? (org-previous-line-empty-p))
  5572. (org-N-empty-lines-before-current (if blank? 1 0))))
  5573. (t
  5574. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5575. (end-of-line))
  5576. (insert "\n" stars " ")
  5577. (unless (and blank? (org-previous-line-empty-p))
  5578. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5579. (run-hooks 'org-insert-heading-hook))
  5580. (defun org-N-empty-lines-before-current (n)
  5581. "Make the number of empty lines before current exactly N.
  5582. So this will delete or add empty lines."
  5583. (let ((column (current-column)))
  5584. (beginning-of-line)
  5585. (unless (bobp)
  5586. (let ((start (save-excursion
  5587. (skip-chars-backward " \r\t\n")
  5588. (line-end-position))))
  5589. (delete-region start (line-end-position 0))))
  5590. (insert (make-string n ?\n))
  5591. (move-to-column column)))
  5592. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5593. "Return the heading of the current entry, without the stars.
  5594. When NO-TAGS is non-nil, don't include tags.
  5595. When NO-TODO is non-nil, don't include TODO keywords.
  5596. When NO-PRIORITY is non-nil, don't include priority cookie.
  5597. When NO-COMMENT is non-nil, don't include COMMENT string.
  5598. Return nil before first heading."
  5599. (unless (org-before-first-heading-p)
  5600. (save-excursion
  5601. (org-back-to-heading t)
  5602. (let ((case-fold-search nil))
  5603. (looking-at org-complex-heading-regexp)
  5604. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5605. ;; returned text will be invisible. Clear it up.
  5606. (save-match-data
  5607. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5608. (let ((todo (and (not no-todo) (match-string 2)))
  5609. (priority (and (not no-priority) (match-string 3)))
  5610. (headline (pcase (match-string 4)
  5611. (`nil "")
  5612. ((and (guard no-comment) h)
  5613. (replace-regexp-in-string
  5614. (eval-when-compile
  5615. (format "\\`%s[ \t]+" org-comment-string))
  5616. "" h))
  5617. (h h)))
  5618. (tags (and (not no-tags) (match-string 5))))
  5619. ;; Restore cleared optimisation.
  5620. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5621. (mapconcat #'identity
  5622. (delq nil (list todo priority headline tags))
  5623. " "))))))
  5624. (defun org-heading-components ()
  5625. "Return the components of the current heading.
  5626. This is a list with the following elements:
  5627. - the level as an integer
  5628. - the reduced level, different if `org-odd-levels-only' is set.
  5629. - the TODO keyword, or nil
  5630. - the priority character, like ?A, or nil if no priority is given
  5631. - the headline text itself, or the tags string if no headline text
  5632. - the tags string, or nil."
  5633. (save-excursion
  5634. (org-back-to-heading t)
  5635. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5636. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5637. (prog1
  5638. (list (length (match-string 1))
  5639. (org-reduced-level (length (match-string 1)))
  5640. (match-string-no-properties 2)
  5641. (and (match-end 3) (aref (match-string 3) 2))
  5642. (match-string-no-properties 4)
  5643. (match-string-no-properties 5))
  5644. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5645. (defun org-get-entry ()
  5646. "Get the entry text, after heading, entire subtree."
  5647. (save-excursion
  5648. (org-back-to-heading t)
  5649. (filter-buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  5650. (defun org-edit-headline (&optional heading)
  5651. "Edit the current headline.
  5652. Set it to HEADING when provided."
  5653. (interactive)
  5654. (org-with-wide-buffer
  5655. (org-back-to-heading t)
  5656. (let ((case-fold-search nil))
  5657. (when (looking-at org-complex-heading-regexp)
  5658. (let* ((old (match-string-no-properties 4))
  5659. (new (save-match-data
  5660. (org-trim (or heading (read-string "Edit: " old))))))
  5661. (unless (equal old new)
  5662. (if old (replace-match new t t nil 4)
  5663. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5664. (insert " " new))
  5665. (org-align-tags)
  5666. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5667. (defun org-insert-heading-after-current ()
  5668. "Insert a new heading with same level as current, after current subtree."
  5669. (interactive)
  5670. (org-back-to-heading)
  5671. (org-insert-heading)
  5672. (org-move-subtree-down)
  5673. (end-of-line 1))
  5674. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5675. "Insert heading with `org-insert-heading-respect-content' set to t."
  5676. (interactive)
  5677. (org-insert-heading '(4) invisible-ok))
  5678. (defun org-insert-todo-heading-respect-content (&optional force-state)
  5679. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5680. (interactive)
  5681. (org-insert-todo-heading force-state '(4)))
  5682. (defun org-insert-todo-heading (arg &optional force-heading)
  5683. "Insert a new heading with the same level and TODO state as current heading.
  5684. If the heading has no TODO state, or if the state is DONE, use
  5685. the first state (TODO by default). Also with one prefix arg,
  5686. force first state. With two prefix args, force inserting at the
  5687. end of the parent subtree.
  5688. When called at a plain list item, insert a new item with an
  5689. unchecked check box."
  5690. (interactive "P")
  5691. (when (or force-heading (not (org-insert-item 'checkbox)))
  5692. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5693. force-heading))
  5694. (save-excursion
  5695. (org-forward-heading-same-level -1)
  5696. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5697. (let* ((new-mark-x
  5698. (if (or (equal arg '(4))
  5699. (not (match-beginning 2))
  5700. (member (match-string 2) org-done-keywords))
  5701. (car org-todo-keywords-1)
  5702. (match-string 2)))
  5703. (new-mark
  5704. (or
  5705. (run-hook-with-args-until-success
  5706. 'org-todo-get-default-hook new-mark-x nil)
  5707. new-mark-x)))
  5708. (beginning-of-line 1)
  5709. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5710. (if org-treat-insert-todo-heading-as-state-change
  5711. (org-todo new-mark)
  5712. (insert new-mark " "))))
  5713. (when org-provide-todo-statistics
  5714. (org-update-parent-todo-statistics))))
  5715. (defun org-insert-subheading (arg)
  5716. "Insert a new subheading and demote it.
  5717. Works for outline headings and for plain lists alike."
  5718. (interactive "P")
  5719. (org-insert-heading arg)
  5720. (cond
  5721. ((org-at-heading-p) (org-do-demote))
  5722. ((org-at-item-p) (org-indent-item))))
  5723. (defun org-insert-todo-subheading (arg)
  5724. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5725. Works for outline headings and for plain lists alike."
  5726. (interactive "P")
  5727. (org-insert-todo-heading arg)
  5728. (cond
  5729. ((org-at-heading-p) (org-do-demote))
  5730. ((org-at-item-p) (org-indent-item))))
  5731. ;;; Promotion and Demotion
  5732. (defvar org-after-demote-entry-hook nil
  5733. "Hook run after an entry has been demoted.
  5734. The cursor will be at the beginning of the entry.
  5735. When a subtree is being demoted, the hook will be called for each node.")
  5736. (defvar org-after-promote-entry-hook nil
  5737. "Hook run after an entry has been promoted.
  5738. The cursor will be at the beginning of the entry.
  5739. When a subtree is being promoted, the hook will be called for each node.")
  5740. (defun org-promote-subtree ()
  5741. "Promote the entire subtree.
  5742. See also `org-promote'."
  5743. (interactive)
  5744. (save-excursion
  5745. (org-back-to-heading t)
  5746. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5747. (org-with-limited-levels (org-map-tree 'org-promote))))
  5748. (org-fix-position-after-promote))
  5749. (defun org-demote-subtree ()
  5750. "Demote the entire subtree.
  5751. See `org-demote' and `org-promote'."
  5752. (interactive)
  5753. (save-excursion
  5754. (org-back-to-heading t)
  5755. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5756. (org-with-limited-levels (org-map-tree 'org-demote))))
  5757. (org-fix-position-after-promote))
  5758. (defun org-do-promote ()
  5759. "Promote the current heading higher up the tree.
  5760. If the region is active in `transient-mark-mode', promote all
  5761. headings in the region."
  5762. (interactive)
  5763. (save-excursion
  5764. (if (org-region-active-p)
  5765. (org-map-region 'org-promote (region-beginning) (region-end))
  5766. (org-promote)))
  5767. (org-fix-position-after-promote))
  5768. (defun org-do-demote ()
  5769. "Demote the current heading lower down the tree.
  5770. If the region is active in `transient-mark-mode', demote all
  5771. headings in the region."
  5772. (interactive)
  5773. (save-excursion
  5774. (if (org-region-active-p)
  5775. (org-map-region 'org-demote (region-beginning) (region-end))
  5776. (org-demote)))
  5777. (org-fix-position-after-promote))
  5778. (defun org-fix-position-after-promote ()
  5779. "Fix cursor position and indentation after demoting/promoting."
  5780. (let ((pos (point)))
  5781. (when (save-excursion
  5782. (beginning-of-line)
  5783. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5784. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5785. (cond ((eobp) (insert " "))
  5786. ((eolp) (insert " "))
  5787. ((equal (char-after) ?\s) (forward-char 1))))))
  5788. (defun org-current-level ()
  5789. "Return the level of the current entry, or nil if before the first headline.
  5790. The level is the number of stars at the beginning of the
  5791. headline. Use `org-reduced-level' to remove the effect of
  5792. `org-odd-levels'. Unlike to `org-outline-level', this function
  5793. ignores inlinetasks."
  5794. (let ((level (org-with-limited-levels (org-outline-level))))
  5795. (and (> level 0) level)))
  5796. (defun org-get-previous-line-level ()
  5797. "Return the outline depth of the last headline before the current line.
  5798. Returns 0 for the first headline in the buffer, and nil if before the
  5799. first headline."
  5800. (and (org-current-level)
  5801. (or (and (/= (line-beginning-position) (point-min))
  5802. (save-excursion (beginning-of-line 0) (org-current-level)))
  5803. 0)))
  5804. (defun org-reduced-level (l)
  5805. "Compute the effective level of a heading.
  5806. This takes into account the setting of `org-odd-levels-only'."
  5807. (cond
  5808. ((zerop l) 0)
  5809. (org-odd-levels-only (1+ (floor (/ l 2))))
  5810. (t l)))
  5811. (defun org-level-increment ()
  5812. "Return the number of stars that will be added or removed at a
  5813. time to headlines when structure editing, based on the value of
  5814. `org-odd-levels-only'."
  5815. (if org-odd-levels-only 2 1))
  5816. (defun org-get-valid-level (level &optional change)
  5817. "Rectify a level change under the influence of `org-odd-levels-only'.
  5818. LEVEL is a current level, CHANGE is by how much the level should
  5819. be modified. Even if CHANGE is nil, LEVEL may be returned
  5820. modified because even level numbers will become the next higher
  5821. odd number. Returns values greater than 0."
  5822. (if org-odd-levels-only
  5823. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5824. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5825. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5826. (max 1 (+ level (or change 0)))))
  5827. (defun org-promote ()
  5828. "Promote the current heading higher up the tree."
  5829. (org-with-wide-buffer
  5830. (org-back-to-heading t)
  5831. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5832. after-change-functions))
  5833. (level (save-match-data (funcall outline-level)))
  5834. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5835. (diff (abs (- level (length up-head) -1))))
  5836. (cond
  5837. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5838. (replace-match "# " nil t))
  5839. ((= level 1)
  5840. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5841. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5842. (unless (= level 1)
  5843. (when org-auto-align-tags (org-align-tags))
  5844. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5845. (run-hooks 'org-after-promote-entry-hook))))
  5846. (defun org-demote ()
  5847. "Demote the current heading lower down the tree."
  5848. (org-with-wide-buffer
  5849. (org-back-to-heading t)
  5850. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5851. after-change-functions))
  5852. (level (save-match-data (funcall outline-level)))
  5853. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5854. (diff (abs (- level (length down-head) -1))))
  5855. (org-fold-core-ignore-fragility-checks
  5856. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5857. (when org-auto-align-tags (org-align-tags))
  5858. (when org-adapt-indentation (org-fixup-indentation diff)))
  5859. (run-hooks 'org-after-demote-entry-hook))))
  5860. (defun org-cycle-level ()
  5861. "Cycle the level of an empty headline through possible states.
  5862. This goes first to child, then to parent, level, then up the hierarchy.
  5863. After top level, it switches back to sibling level."
  5864. (interactive)
  5865. (let ((org-adapt-indentation nil))
  5866. (when (org-point-at-end-of-empty-headline)
  5867. (setq this-command 'org-cycle-level) ; Only needed for caching
  5868. (let ((cur-level (org-current-level))
  5869. (prev-level (org-get-previous-line-level)))
  5870. (cond
  5871. ;; If first headline in file, promote to top-level.
  5872. ((= prev-level 0)
  5873. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5874. do (org-do-promote)))
  5875. ;; If same level as prev, demote one.
  5876. ((= prev-level cur-level)
  5877. (org-do-demote))
  5878. ;; If parent is top-level, promote to top level if not already.
  5879. ((= prev-level 1)
  5880. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5881. do (org-do-promote)))
  5882. ;; If top-level, return to prev-level.
  5883. ((= cur-level 1)
  5884. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5885. do (org-do-demote)))
  5886. ;; If less than prev-level, promote one.
  5887. ((< cur-level prev-level)
  5888. (org-do-promote))
  5889. ;; If deeper than prev-level, promote until higher than
  5890. ;; prev-level.
  5891. ((> cur-level prev-level)
  5892. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5893. do (org-do-promote))))
  5894. t))))
  5895. (defun org-map-tree (fun)
  5896. "Call FUN for every heading underneath the current one."
  5897. (org-back-to-heading t)
  5898. (let ((level (funcall outline-level)))
  5899. (save-excursion
  5900. (funcall fun)
  5901. (while (and (progn
  5902. (outline-next-heading)
  5903. (> (funcall outline-level) level))
  5904. (not (eobp)))
  5905. (funcall fun)))))
  5906. (defun org-map-region (fun beg end)
  5907. "Call FUN for every heading between BEG and END."
  5908. (let ((org-ignore-region t))
  5909. (save-excursion
  5910. (setq end (copy-marker end))
  5911. (goto-char beg)
  5912. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5913. (< (point) end))
  5914. (funcall fun))
  5915. (while (and (progn
  5916. (outline-next-heading)
  5917. (< (point) end))
  5918. (not (eobp)))
  5919. (funcall fun)))))
  5920. (defun org-fixup-indentation (diff)
  5921. "Change the indentation in the current entry by DIFF.
  5922. DIFF is an integer. Indentation is done according to the
  5923. following rules:
  5924. - Planning information and property drawers are always indented
  5925. according to the new level of the headline;
  5926. - Footnote definitions and their contents are ignored;
  5927. - Inlinetasks' boundaries are not shifted;
  5928. - Empty lines are ignored;
  5929. - Other lines' indentation are shifted by DIFF columns, unless
  5930. it would introduce a structural change in the document, in
  5931. which case no shifting is done at all.
  5932. Assume point is at a heading or an inlinetask beginning."
  5933. (org-with-wide-buffer
  5934. (narrow-to-region (line-beginning-position)
  5935. (save-excursion
  5936. (if (org-with-limited-levels (org-at-heading-p))
  5937. (org-with-limited-levels (outline-next-heading))
  5938. (org-inlinetask-goto-end))
  5939. (point)))
  5940. (forward-line)
  5941. ;; Indent properly planning info and property drawer.
  5942. (when (looking-at-p org-planning-line-re)
  5943. (org-indent-line)
  5944. (forward-line))
  5945. (when (looking-at org-property-drawer-re)
  5946. (goto-char (match-end 0))
  5947. (forward-line)
  5948. (org-indent-region (match-beginning 0) (match-end 0)))
  5949. (when (looking-at org-logbook-drawer-re)
  5950. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5951. (col (+ (current-indentation) diff)))
  5952. (when (wholenump col)
  5953. (while (< (point) end-marker)
  5954. (if (natnump diff)
  5955. (insert (make-string diff 32))
  5956. (delete-char (abs diff)))
  5957. (forward-line)))))
  5958. (catch 'no-shift
  5959. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5960. (throw 'no-shift nil))
  5961. ;; If DIFF is negative, first check if a shift is possible at all
  5962. ;; (e.g., it doesn't break structure). This can only happen if
  5963. ;; some contents are not properly indented.
  5964. (let ((case-fold-search t))
  5965. (when (< diff 0)
  5966. (let ((diff (- diff))
  5967. (forbidden-re (concat org-outline-regexp
  5968. "\\|"
  5969. (substring org-footnote-definition-re 1))))
  5970. (save-excursion
  5971. (while (not (eobp))
  5972. (cond
  5973. ((looking-at-p "[ \t]*$") (forward-line))
  5974. ((and (looking-at-p org-footnote-definition-re)
  5975. (let ((e (org-element-at-point)))
  5976. (and (eq (org-element-type e) 'footnote-definition)
  5977. (goto-char (org-element-property :end e))))))
  5978. ((looking-at-p org-outline-regexp) (forward-line))
  5979. ;; Give up if shifting would move before column 0 or
  5980. ;; if it would introduce a headline or a footnote
  5981. ;; definition.
  5982. (t
  5983. (skip-chars-forward " \t")
  5984. (let ((ind (current-column)))
  5985. (when (or (< ind diff)
  5986. (and (= ind diff) (looking-at-p forbidden-re)))
  5987. (throw 'no-shift nil)))
  5988. ;; Ignore contents of example blocks and source
  5989. ;; blocks if their indentation is meant to be
  5990. ;; preserved. Jump to block's closing line.
  5991. (beginning-of-line)
  5992. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5993. (let ((e (org-element-at-point)))
  5994. (and (memq (org-element-type e)
  5995. '(example-block src-block))
  5996. (or org-src-preserve-indentation
  5997. (org-element-property :preserve-indent e))
  5998. (goto-char (org-element-property :end e))
  5999. (progn (skip-chars-backward " \r\t\n")
  6000. (beginning-of-line)
  6001. t))))
  6002. (forward-line))))))))
  6003. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6004. ;; by DIFF. Also skip contents of source or example blocks
  6005. ;; when indentation is meant to be preserved.
  6006. (while (not (eobp))
  6007. (cond
  6008. ((and (looking-at-p org-footnote-definition-re)
  6009. (let ((e (org-element-at-point)))
  6010. (and (eq (org-element-type e) 'footnote-definition)
  6011. (goto-char (org-element-property :end e))))))
  6012. ((looking-at-p org-outline-regexp) (forward-line))
  6013. ((looking-at-p "[ \t]*$") (forward-line))
  6014. (t
  6015. (indent-line-to (+ (current-indentation) diff))
  6016. (beginning-of-line)
  6017. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6018. (let ((e (org-element-at-point)))
  6019. (and (memq (org-element-type e)
  6020. '(example-block src-block))
  6021. (or org-src-preserve-indentation
  6022. (org-element-property :preserve-indent e))
  6023. (goto-char (org-element-property :end e))
  6024. (progn (skip-chars-backward " \r\t\n")
  6025. (beginning-of-line)
  6026. t))))
  6027. (forward-line)))))))))
  6028. (defun org-convert-to-odd-levels ()
  6029. "Convert an Org file with all levels allowed to one with odd levels.
  6030. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6031. level 5 etc."
  6032. (interactive)
  6033. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6034. (let ((outline-level 'org-outline-level)
  6035. (org-odd-levels-only nil) n)
  6036. (save-excursion
  6037. (goto-char (point-min))
  6038. (while (re-search-forward "^\\*\\*+ " nil t)
  6039. (setq n (- (length (match-string 0)) 2))
  6040. (while (>= (setq n (1- n)) 0)
  6041. (org-demote))
  6042. (end-of-line 1))))))
  6043. (defun org-convert-to-oddeven-levels ()
  6044. "Convert an Org file with only odd levels to one with odd/even levels.
  6045. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6046. file contains a section with an even level, conversion would
  6047. destroy the structure of the file. An error is signaled in this
  6048. case."
  6049. (interactive)
  6050. (goto-char (point-min))
  6051. ;; First check if there are no even levels
  6052. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6053. (org-fold-show-set-visibility 'canonical)
  6054. (error "Not all levels are odd in this file. Conversion not possible"))
  6055. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6056. (let ((outline-regexp org-outline-regexp)
  6057. (outline-level 'org-outline-level)
  6058. (org-odd-levels-only nil) n)
  6059. (save-excursion
  6060. (goto-char (point-min))
  6061. (while (re-search-forward "^\\*\\*+ " nil t)
  6062. (setq n (/ (1- (length (match-string 0))) 2))
  6063. (while (>= (setq n (1- n)) 0)
  6064. (org-promote))
  6065. (end-of-line 1))))))
  6066. (defun org-tr-level (n)
  6067. "Make N odd if required."
  6068. (if org-odd-levels-only (1+ (/ n 2)) n))
  6069. ;;; Vertical tree motion, cutting and pasting of subtrees
  6070. (defun org-move-subtree-up (&optional arg)
  6071. "Move the current subtree up past ARG headlines of the same level."
  6072. (interactive "p")
  6073. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6074. (defun org-clean-visibility-after-subtree-move ()
  6075. "Fix visibility issues after moving a subtree."
  6076. ;; First, find a reasonable region to look at:
  6077. ;; Start two siblings above, end three below
  6078. (let* ((beg (save-excursion
  6079. (and (org-get-previous-sibling)
  6080. (org-get-previous-sibling))
  6081. (point)))
  6082. (end (save-excursion
  6083. (and (org-get-next-sibling)
  6084. (org-get-next-sibling)
  6085. (org-get-next-sibling))
  6086. (if (org-at-heading-p)
  6087. (point-at-eol)
  6088. (point))))
  6089. (level (looking-at "\\*+"))
  6090. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  6091. (save-excursion
  6092. (save-restriction
  6093. (narrow-to-region beg end)
  6094. (when re
  6095. ;; Properly fold already folded siblings
  6096. (goto-char (point-min))
  6097. (while (re-search-forward re nil t)
  6098. (when (and (not (org-invisible-p))
  6099. (org-invisible-p (line-end-position)))
  6100. (org-fold-heading nil))))
  6101. (org-cycle-hide-drawers 'all)
  6102. (org-cycle-show-empty-lines 'overview)))))
  6103. (defun org-move-subtree-down (&optional arg)
  6104. "Move the current subtree down past ARG headlines of the same level."
  6105. (interactive "p")
  6106. (setq arg (prefix-numeric-value arg))
  6107. (org-preserve-local-variables
  6108. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6109. 'org-get-previous-sibling))
  6110. (ins-point (make-marker))
  6111. (cnt (abs arg))
  6112. (col (current-column))
  6113. beg end txt folded)
  6114. ;; Select the tree
  6115. (org-back-to-heading)
  6116. (setq beg (point))
  6117. (save-match-data
  6118. (save-excursion (outline-end-of-heading)
  6119. (setq folded (org-invisible-p)))
  6120. (progn (org-end-of-subtree nil t)
  6121. (unless (eobp) (backward-char))))
  6122. (outline-next-heading)
  6123. (setq end (point))
  6124. (goto-char beg)
  6125. ;; Find insertion point, with error handling
  6126. (while (> cnt 0)
  6127. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6128. (goto-char beg)
  6129. (user-error "Cannot move past superior level or buffer limit"))
  6130. (setq cnt (1- cnt)))
  6131. (when (> arg 0)
  6132. ;; Moving forward - still need to move over subtree
  6133. (org-end-of-subtree t t)
  6134. (save-excursion
  6135. (org-back-over-empty-lines)
  6136. (or (bolp) (newline))))
  6137. (move-marker ins-point (point))
  6138. (setq txt (buffer-substring beg end))
  6139. (org-save-markers-in-region beg end)
  6140. (delete-region beg end)
  6141. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6142. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6143. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6144. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6145. (let ((bbb (point)))
  6146. (insert-before-markers txt)
  6147. (org-reinstall-markers-in-region bbb)
  6148. (move-marker ins-point bbb))
  6149. (or (bolp) (insert "\n"))
  6150. (goto-char ins-point)
  6151. (org-skip-whitespace)
  6152. (move-marker ins-point nil)
  6153. (if folded
  6154. (org-fold-subtree t)
  6155. (org-fold-show-entry 'hide-drawers)
  6156. (org-fold-show-children))
  6157. (org-clean-visibility-after-subtree-move)
  6158. ;; move back to the initial column we were at
  6159. (move-to-column col))))
  6160. (defvar org-subtree-clip ""
  6161. "Clipboard for cut and paste of subtrees.
  6162. This is actually only a copy of the kill, because we use the normal kill
  6163. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6164. (defvar org-subtree-clip-folded nil
  6165. "Was the last copied subtree folded?
  6166. This is used to fold the tree back after pasting.")
  6167. (defun org-cut-subtree (&optional n)
  6168. "Cut the current subtree into the clipboard.
  6169. With prefix arg N, cut this many sequential subtrees.
  6170. This is a short-hand for marking the subtree and then cutting it."
  6171. (interactive "p")
  6172. (org-copy-subtree n 'cut))
  6173. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6174. "Copy the current subtree into the clipboard.
  6175. With prefix arg N, copy this many sequential subtrees.
  6176. This is a short-hand for marking the subtree and then copying it.
  6177. If CUT is non-nil, actually cut the subtree.
  6178. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6179. of some markers in the region, even if CUT is non-nil. This is
  6180. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6181. (interactive "p")
  6182. (org-preserve-local-variables
  6183. (let (beg end folded (beg0 (point)))
  6184. (if (called-interactively-p 'any)
  6185. (org-back-to-heading nil) ; take what looks like a subtree
  6186. (org-back-to-heading t)) ; take what is really there
  6187. (setq beg (point))
  6188. (skip-chars-forward " \t\r\n")
  6189. (save-match-data
  6190. (if nosubtrees
  6191. (outline-next-heading)
  6192. (save-excursion (outline-end-of-heading)
  6193. (setq folded (org-invisible-p)))
  6194. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6195. (org-end-of-subtree t t)))
  6196. ;; Include the end of an inlinetask
  6197. (when (and (featurep 'org-inlinetask)
  6198. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6199. "END[ \t]*$")))
  6200. (end-of-line))
  6201. (setq end (point))
  6202. (goto-char beg0)
  6203. (when (> end beg)
  6204. (setq org-subtree-clip-folded folded)
  6205. (when (or cut force-store-markers)
  6206. (org-save-markers-in-region beg end))
  6207. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6208. (setq org-subtree-clip (current-kill 0))
  6209. (message "%s: Subtree(s) with %d characters"
  6210. (if cut "Cut" "Copied")
  6211. (length org-subtree-clip))))))
  6212. (defun org-paste-subtree (&optional level tree for-yank remove)
  6213. "Paste the clipboard as a subtree, with modification of headline level.
  6214. The entire subtree is promoted or demoted in order to match a new headline
  6215. level.
  6216. If the cursor is at the beginning of a headline, the same level as
  6217. that headline is used to paste the tree.
  6218. If not, the new level is derived from the *visible* headings
  6219. before and after the insertion point, and taken to be the inferior headline
  6220. level of the two. So if the previous visible heading is level 3 and the
  6221. next is level 4 (or vice versa), level 4 will be used for insertion.
  6222. This makes sure that the subtree remains an independent subtree and does
  6223. not swallow low level entries.
  6224. You can also force a different level, either by using a numeric prefix
  6225. argument, or by inserting the heading marker by hand. For example, if the
  6226. cursor is after \"*****\", then the tree will be shifted to level 5.
  6227. If optional TREE is given, use this text instead of the kill ring.
  6228. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6229. move back over whitespace before inserting, and move point to the end of
  6230. the inserted text when done.
  6231. When REMOVE is non-nil, remove the subtree from the clipboard."
  6232. (interactive "P")
  6233. (setq tree (or tree (and kill-ring (current-kill 0))))
  6234. (unless (org-kill-is-subtree-p tree)
  6235. (user-error
  6236. (substitute-command-keys
  6237. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6238. (org-with-limited-levels
  6239. (org-fold-core-ignore-fragility-checks
  6240. (let* ((visp (not (org-invisible-p)))
  6241. (txt tree)
  6242. (old-level (if (string-match org-outline-regexp-bol txt)
  6243. (- (match-end 0) (match-beginning 0) 1)
  6244. -1))
  6245. (force-level
  6246. (cond
  6247. (level (prefix-numeric-value level))
  6248. ;; When point is after the stars in an otherwise empty
  6249. ;; headline, use the number of stars as the forced level.
  6250. ((and (org-match-line "^\\*+[ \t]*$")
  6251. (not (eq ?* (char-after))))
  6252. (org-outline-level))
  6253. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6254. (previous-level
  6255. (save-excursion
  6256. (org-previous-visible-heading 1)
  6257. (if (org-at-heading-p) (org-outline-level) 1)))
  6258. (next-level
  6259. (save-excursion
  6260. (if (org-at-heading-p) (org-outline-level)
  6261. (org-next-visible-heading 1)
  6262. (if (org-at-heading-p) (org-outline-level) 1))))
  6263. (new-level (or force-level (max previous-level next-level)))
  6264. (shift (if (or (= old-level -1)
  6265. (= new-level -1)
  6266. (= old-level new-level))
  6267. 0
  6268. (- new-level old-level)))
  6269. (delta (if (> shift 0) -1 1))
  6270. (func (if (> shift 0) #'org-demote #'org-promote))
  6271. (org-odd-levels-only nil)
  6272. beg end newend)
  6273. ;; Remove the forced level indicator.
  6274. (when (and force-level (not level))
  6275. (delete-region (line-beginning-position) (point)))
  6276. ;; Paste before the next visible heading or at end of buffer,
  6277. ;; unless point is at the beginning of a headline.
  6278. (unless (and (bolp) (org-at-heading-p))
  6279. (org-next-visible-heading 1)
  6280. (unless (bolp) (insert "\n")))
  6281. (setq beg (point))
  6282. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6283. ;; is inserted and then promoted.
  6284. (combine-change-calls beg beg
  6285. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6286. (insert txt)
  6287. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6288. (setq newend (point))
  6289. (org-reinstall-markers-in-region beg)
  6290. (setq end (point))
  6291. (goto-char beg)
  6292. (skip-chars-forward " \t\n\r")
  6293. (setq beg (point))
  6294. (when (and (org-invisible-p) visp)
  6295. (save-excursion (org-fold-heading nil)))
  6296. ;; Shift if necessary.
  6297. (unless (= shift 0)
  6298. (save-restriction
  6299. (narrow-to-region beg end)
  6300. (while (not (= shift 0))
  6301. (org-map-region func (point-min) (point-max))
  6302. (setq shift (+ delta shift)))
  6303. (goto-char (point-min))
  6304. (setq newend (point-max)))))
  6305. (when (or for-yank (called-interactively-p 'interactive))
  6306. (message "Clipboard pasted as level %d subtree" new-level))
  6307. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6308. kill-ring
  6309. (equal org-subtree-clip (current-kill 0))
  6310. org-subtree-clip-folded)
  6311. ;; The tree was folded before it was killed/copied
  6312. (org-fold-subtree t))
  6313. (when for-yank (goto-char newend))
  6314. (when remove (pop kill-ring))))))
  6315. (defun org-kill-is-subtree-p (&optional txt)
  6316. "Check if the current kill is an outline subtree, or a set of trees.
  6317. Returns nil if kill does not start with a headline, or if the first
  6318. headline level is not the largest headline level in the tree.
  6319. So this will actually accept several entries of equal levels as well,
  6320. which is OK for `org-paste-subtree'.
  6321. If optional TXT is given, check this string instead of the current kill."
  6322. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6323. (re (org-get-limited-outline-regexp))
  6324. (^re (concat "^" re))
  6325. (start-level (and kill
  6326. (string-match
  6327. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6328. kill)
  6329. (- (match-end 2) (match-beginning 2) 1)))
  6330. (start (1+ (or (match-beginning 2) -1))))
  6331. (if (not start-level)
  6332. (progn
  6333. nil) ;; does not even start with a heading
  6334. (catch 'exit
  6335. (while (setq start (string-match ^re kill (1+ start)))
  6336. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6337. (throw 'exit nil)))
  6338. t))))
  6339. (defvar org-markers-to-move nil
  6340. "Markers that should be moved with a cut-and-paste operation.
  6341. Those markers are stored together with their positions relative to
  6342. the start of the region.")
  6343. (defun org-save-markers-in-region (beg end)
  6344. "Check markers in region.
  6345. If these markers are between BEG and END, record their position relative
  6346. to BEG, so that after moving the block of text, we can put the markers back
  6347. into place.
  6348. This function gets called just before an entry or tree gets cut from the
  6349. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6350. called immediately, to move the markers with the entries."
  6351. (setq org-markers-to-move nil)
  6352. (when (featurep 'org-clock)
  6353. (org-clock-save-markers-for-cut-and-paste beg end))
  6354. (when (featurep 'org-agenda)
  6355. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6356. (defun org-check-and-save-marker (marker beg end)
  6357. "Check if MARKER is between BEG and END.
  6358. If yes, remember the marker and the distance to BEG."
  6359. (when (and (marker-buffer marker)
  6360. (or (equal (marker-buffer marker) (current-buffer))
  6361. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6362. (>= marker beg) (< marker end))
  6363. (push (cons marker (- marker beg)) org-markers-to-move)))
  6364. (defun org-reinstall-markers-in-region (beg)
  6365. "Move all remembered markers to their position relative to BEG."
  6366. (dolist (x org-markers-to-move)
  6367. (move-marker (car x) (+ beg (cdr x))))
  6368. (setq org-markers-to-move nil))
  6369. (defun org-narrow-to-subtree (&optional element)
  6370. "Narrow buffer to the current subtree."
  6371. (interactive)
  6372. (if (org-element--cache-active-p)
  6373. (let* ((heading (org-element-lineage
  6374. (or element (org-element-at-point))
  6375. '(headline) t))
  6376. (end (org-element-property :end heading)))
  6377. (if (and heading end)
  6378. (narrow-to-region (org-element-property :begin heading)
  6379. (if (= end (point-max))
  6380. end (1- end)))
  6381. (signal 'outline-before-first-heading nil)))
  6382. (save-excursion
  6383. (save-match-data
  6384. (org-with-limited-levels
  6385. (narrow-to-region
  6386. (progn (org-back-to-heading t) (point))
  6387. (progn (org-end-of-subtree t t)
  6388. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6389. (point))))))))
  6390. (defun org-toggle-narrow-to-subtree ()
  6391. "Narrow to the subtree at point or widen a narrowed buffer."
  6392. (interactive)
  6393. (if (buffer-narrowed-p)
  6394. (progn (widen) (message "Buffer widen"))
  6395. (org-narrow-to-subtree)
  6396. (message "Buffer narrowed to current subtree")))
  6397. (defun org-narrow-to-block ()
  6398. "Narrow buffer to the current block."
  6399. (interactive)
  6400. (let* ((case-fold-search t)
  6401. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6402. "^[ \t]*#\\+end_.*")))
  6403. (if blockp
  6404. (narrow-to-region (car blockp) (cdr blockp))
  6405. (user-error "Not in a block"))))
  6406. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6407. "Clone the task (subtree) at point N times.
  6408. The clones will be inserted as siblings.
  6409. In interactive use, the user will be prompted for the number of
  6410. clones to be produced. If the entry has a timestamp, the user
  6411. will also be prompted for a time shift, which may be a repeater
  6412. as used in time stamps, for example `+3d'. To disable this,
  6413. you can call the function with a universal prefix argument.
  6414. When a valid repeater is given and the entry contains any time
  6415. stamps, the clones will become a sequence in time, with time
  6416. stamps in the subtree shifted for each clone produced. If SHIFT
  6417. is nil or the empty string, time stamps will be left alone. The
  6418. ID property of the original subtree is removed.
  6419. In each clone, all the CLOCK entries will be removed. This
  6420. prevents Org from considering that the clocked times overlap.
  6421. If the original subtree did contain time stamps with a repeater,
  6422. the following will happen:
  6423. - the repeater will be removed in each clone
  6424. - an additional clone will be produced, with the current, unshifted
  6425. date(s) in the entry.
  6426. - the original entry will be placed *after* all the clones, with
  6427. repeater intact.
  6428. - the start days in the repeater in the original entry will be shifted
  6429. to past the last clone.
  6430. In this way you can spell out a number of instances of a repeating task,
  6431. and still retain the repeater to cover future instances of the task.
  6432. As described above, N+1 clones are produced when the original
  6433. subtree has a repeater. Setting N to 0, then, can be used to
  6434. remove the repeater from a subtree and create a shifted clone
  6435. with the original repeater."
  6436. (interactive "nNumber of clones to produce: ")
  6437. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6438. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6439. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6440. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6441. (shift
  6442. (or shift
  6443. (if (and (not (equal current-prefix-arg '(4)))
  6444. (save-excursion
  6445. (goto-char beg)
  6446. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6447. (read-from-minibuffer
  6448. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6449. ""))) ;No time shift
  6450. (doshift
  6451. (and (org-string-nw-p shift)
  6452. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6453. shift)
  6454. (user-error "Invalid shift specification %s" shift)))))
  6455. (goto-char end-of-tree)
  6456. (unless (bolp) (insert "\n"))
  6457. (let* ((end (point))
  6458. (template (buffer-substring beg end))
  6459. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6460. (shift-what (pcase (and doshift (match-string 2 shift))
  6461. (`nil nil)
  6462. ("h" 'hour)
  6463. ("d" 'day)
  6464. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6465. ("m" 'month)
  6466. ("y" 'year)
  6467. (_ (error "Unsupported time unit"))))
  6468. (nmin 1)
  6469. (nmax n)
  6470. (n-no-remove -1)
  6471. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6472. (idprop (org-entry-get beg "ID")))
  6473. (when (and doshift
  6474. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6475. template))
  6476. (delete-region beg end)
  6477. (setq end beg)
  6478. (setq nmin 0)
  6479. (setq nmax (1+ nmax))
  6480. (setq n-no-remove nmax))
  6481. (goto-char end)
  6482. (cl-loop for n from nmin to nmax do
  6483. (insert
  6484. ;; Prepare clone.
  6485. (with-temp-buffer
  6486. (insert template)
  6487. (org-mode)
  6488. (goto-char (point-min))
  6489. (org-fold-show-subtree)
  6490. (and idprop (if org-clone-delete-id
  6491. (org-entry-delete nil "ID")
  6492. (org-id-get-create t)))
  6493. (unless (= n 0)
  6494. (while (re-search-forward org-clock-line-re nil t)
  6495. (delete-region (line-beginning-position)
  6496. (line-beginning-position 2)))
  6497. (goto-char (point-min))
  6498. (while (re-search-forward org-drawer-regexp nil t)
  6499. (org-remove-empty-drawer-at (point))))
  6500. (goto-char (point-min))
  6501. (when doshift
  6502. (while (re-search-forward org-ts-regexp-both nil t)
  6503. (org-timestamp-change (* n shift-n) shift-what))
  6504. (unless (= n n-no-remove)
  6505. (goto-char (point-min))
  6506. (while (re-search-forward org-ts-regexp nil t)
  6507. (save-excursion
  6508. (goto-char (match-beginning 0))
  6509. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6510. (delete-region (match-beginning 1) (match-end 1)))))))
  6511. (buffer-string)))))
  6512. (goto-char beg)))
  6513. ;;; Outline path
  6514. (defvar org-outline-path-cache nil
  6515. "Alist between buffer positions and outline paths.
  6516. It value is an alist (POSITION . PATH) where POSITION is the
  6517. buffer position at the beginning of an entry and PATH is a list
  6518. of strings describing the outline path for that entry, in reverse
  6519. order.")
  6520. (defun org--get-outline-path-1 (&optional use-cache)
  6521. "Return outline path to current headline.
  6522. Outline path is a list of strings, in reverse order. When
  6523. optional argument USE-CACHE is non-nil, make use of a cache. See
  6524. `org-get-outline-path' for details.
  6525. Assume buffer is widened and point is on a headline."
  6526. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6527. (let ((p (point))
  6528. (heading (let ((case-fold-search nil))
  6529. (looking-at org-complex-heading-regexp)
  6530. (if (not (match-end 4)) ""
  6531. ;; Remove statistics cookies.
  6532. (org-trim
  6533. (org-link-display-format
  6534. (replace-regexp-in-string
  6535. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6536. (match-string-no-properties 4))))))))
  6537. (if (org-up-heading-safe)
  6538. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6539. (when use-cache
  6540. (push (cons p path) org-outline-path-cache))
  6541. path)
  6542. ;; This is a new root node. Since we assume we are moving
  6543. ;; forward, we can drop previous cache so as to limit number
  6544. ;; of associations there.
  6545. (let ((path (list heading)))
  6546. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6547. path)))))
  6548. (defun org-get-outline-path (&optional with-self use-cache)
  6549. "Return the outline path to the current entry.
  6550. An outline path is a list of ancestors for current headline, as
  6551. a list of strings. Statistics cookies are removed and links are
  6552. replaced with their description, if any, or their path otherwise.
  6553. When optional argument WITH-SELF is non-nil, the path also
  6554. includes the current headline.
  6555. When optional argument USE-CACHE is non-nil, cache outline paths
  6556. between calls to this function so as to avoid backtracking. This
  6557. argument is useful when planning to find more than one outline
  6558. path in the same document. In that case, there are two
  6559. conditions to satisfy:
  6560. - `org-outline-path-cache' is set to nil before starting the
  6561. process;
  6562. - outline paths are computed by increasing buffer positions."
  6563. (org-with-wide-buffer
  6564. (and (or (and with-self (org-back-to-heading t))
  6565. (org-up-heading-safe))
  6566. (reverse (org--get-outline-path-1 use-cache)))))
  6567. (defun org-format-outline-path (path &optional width prefix separator)
  6568. "Format the outline path PATH for display.
  6569. WIDTH is the maximum number of characters that is available.
  6570. PREFIX is a prefix to be included in the returned string,
  6571. such as the file name.
  6572. SEPARATOR is inserted between the different parts of the path,
  6573. the default is \"/\"."
  6574. (setq width (or width 79))
  6575. (setq path (delq nil path))
  6576. (unless (> width 0)
  6577. (user-error "Argument `width' must be positive"))
  6578. (setq separator (or separator "/"))
  6579. (let* ((org-odd-levels-only nil)
  6580. (fpath (concat
  6581. prefix (and prefix path separator)
  6582. (mapconcat
  6583. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6584. (cl-loop for head in path
  6585. for n from 0
  6586. collect (org-add-props
  6587. head nil 'face
  6588. (nth (% n org-n-level-faces) org-level-faces)))
  6589. separator))))
  6590. (when (> (length fpath) width)
  6591. (if (< width 7)
  6592. ;; It's unlikely that `width' will be this small, but don't
  6593. ;; waste characters by adding ".." if it is.
  6594. (setq fpath (substring fpath 0 width))
  6595. (setf (substring fpath (- width 2)) "..")))
  6596. fpath))
  6597. (defun org-display-outline-path (&optional file current separator just-return-string)
  6598. "Display the current outline path in the echo area.
  6599. If FILE is non-nil, prepend the output with the file name.
  6600. If CURRENT is non-nil, append the current heading to the output.
  6601. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6602. the different parts of the path and defaults to \"/\".
  6603. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6604. (interactive "P")
  6605. (let* (case-fold-search
  6606. (bfn (buffer-file-name (buffer-base-buffer)))
  6607. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6608. res)
  6609. (when current (setq path (append path
  6610. (save-excursion
  6611. (org-back-to-heading t)
  6612. (when (looking-at org-complex-heading-regexp)
  6613. (list (match-string 4)))))))
  6614. (setq res
  6615. (org-format-outline-path
  6616. path
  6617. (1- (frame-width))
  6618. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6619. separator))
  6620. (add-face-text-property 0 (length res)
  6621. `(:height ,(face-attribute 'default :height))
  6622. nil res)
  6623. (if just-return-string
  6624. res
  6625. (org-unlogged-message "%s" res))))
  6626. ;;; Outline Sorting
  6627. (defun org-sort (&optional with-case)
  6628. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6629. Optional argument WITH-CASE means sort case-sensitively."
  6630. (interactive "P")
  6631. (org-call-with-arg
  6632. (cond ((org-at-table-p) #'org-table-sort-lines)
  6633. ((org-at-item-p) #'org-sort-list)
  6634. (t #'org-sort-entries))
  6635. with-case))
  6636. (defun org-sort-remove-invisible (s)
  6637. "Remove emphasis markers and any invisible property from string S.
  6638. Assume S may contain only objects."
  6639. ;; org-element-interpret-data clears any text property, including
  6640. ;; invisible part.
  6641. (org-element-interpret-data
  6642. (let ((tree (org-element-parse-secondary-string
  6643. s (org-element-restriction 'paragraph))))
  6644. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6645. (lambda (o)
  6646. (pcase (org-element-type o)
  6647. ;; Terminal object. Replace it with its value.
  6648. ((or `code `verbatim)
  6649. (let ((new (org-element-property :value o)))
  6650. (org-element-insert-before new o)
  6651. (org-element-put-property
  6652. new :post-blank (org-element-property :post-blank o))))
  6653. ;; Non-terminal objects. Splice contents.
  6654. (type
  6655. (let ((contents
  6656. (or (org-element-contents o)
  6657. (and (eq type 'link)
  6658. (list (org-element-property :raw-link o)))))
  6659. (c nil))
  6660. (while contents
  6661. (setq c (pop contents))
  6662. (org-element-insert-before c o))
  6663. (org-element-put-property
  6664. c :post-blank (org-element-property :post-blank o)))))
  6665. (org-element-extract-element o)))
  6666. ;; Return modified tree.
  6667. tree)))
  6668. (defvar org-after-sorting-entries-or-items-hook nil
  6669. "Hook that is run after a bunch of entries or items have been sorted.
  6670. When children are sorted, the cursor is in the parent line when this
  6671. hook gets called. When a region or a plain list is sorted, the cursor
  6672. will be in the first entry of the sorted region/list.")
  6673. (defun org-sort-entries
  6674. (&optional with-case sorting-type getkey-func compare-func property
  6675. interactive?)
  6676. "Sort entries on a certain level of an outline tree.
  6677. If there is an active region, the entries in the region are sorted.
  6678. Else, if the cursor is before the first entry, sort the top-level items.
  6679. Else, the children of the entry at point are sorted.
  6680. Sorting can be alphabetically, numerically, by date/time as given by
  6681. a time stamp, by a property, by priority order, or by a custom function.
  6682. The command prompts for the sorting type unless it has been given to the
  6683. function through the SORTING-TYPE argument, which needs to be a character,
  6684. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6685. the precise meaning of each character:
  6686. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6687. c By creation time, which is assumed to be the first inactive time stamp
  6688. at the beginning of a line.
  6689. d By deadline date/time.
  6690. k By clocking time.
  6691. n Numerically, by converting the beginning of the entry/item to a number.
  6692. o By order of TODO keywords.
  6693. p By priority according to the cookie.
  6694. r By the value of a property.
  6695. s By scheduled date/time.
  6696. t By date/time, either the first active time stamp in the entry, or, if
  6697. none exist, by the first inactive one.
  6698. Capital letters will reverse the sort order.
  6699. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6700. called with point at the beginning of the record. It must return a
  6701. value that is compatible with COMPARE-FUNC, the function used to
  6702. compare entries.
  6703. Comparing entries ignores case by default. However, with an optional argument
  6704. WITH-CASE, the sorting considers case as well.
  6705. Sorting is done against the visible part of the headlines, it ignores hidden
  6706. links.
  6707. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6708. A non-nil value for INTERACTIVE? is used to signal that this
  6709. function is being called interactively."
  6710. (interactive (list current-prefix-arg nil nil nil nil t))
  6711. (let ((case-func (if with-case 'identity 'downcase))
  6712. start beg end stars re re2
  6713. txt what tmp)
  6714. ;; Find beginning and end of region to sort
  6715. (cond
  6716. ((org-region-active-p)
  6717. ;; we will sort the region
  6718. (setq end (region-end)
  6719. what "region")
  6720. (goto-char (region-beginning))
  6721. (unless (org-at-heading-p) (outline-next-heading))
  6722. (setq start (point)))
  6723. ((or (org-at-heading-p)
  6724. (ignore-errors (progn (org-back-to-heading) t)))
  6725. ;; we will sort the children of the current headline
  6726. (org-back-to-heading)
  6727. (setq start (point)
  6728. end (progn (org-end-of-subtree t t)
  6729. (or (bolp) (insert "\n"))
  6730. (when (>= (org-back-over-empty-lines) 1)
  6731. (forward-line 1))
  6732. (point))
  6733. what "children")
  6734. (goto-char start)
  6735. (org-fold-show-subtree)
  6736. (outline-next-heading))
  6737. (t
  6738. ;; we will sort the top-level entries in this file
  6739. (goto-char (point-min))
  6740. (or (org-at-heading-p) (outline-next-heading))
  6741. (setq start (point))
  6742. (goto-char (point-max))
  6743. (beginning-of-line 1)
  6744. (when (looking-at ".*?\\S-")
  6745. ;; File ends in a non-white line
  6746. (end-of-line 1)
  6747. (insert "\n"))
  6748. (setq end (point-max))
  6749. (setq what "top-level")
  6750. (goto-char start)
  6751. (org-fold-show-all '(headings drawers blocks))))
  6752. (setq beg (point))
  6753. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6754. (looking-at "\\(\\*+\\)")
  6755. (setq stars (match-string 1)
  6756. re (concat "^" (regexp-quote stars) " +")
  6757. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6758. txt (buffer-substring beg end))
  6759. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6760. (when (and (not (equal stars "*")) (string-match re2 txt))
  6761. (user-error "Region to sort contains a level above the first entry"))
  6762. (unless sorting-type
  6763. (message
  6764. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6765. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6766. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6767. what)
  6768. (setq sorting-type (read-char-exclusive)))
  6769. (unless getkey-func
  6770. (and (= (downcase sorting-type) ?f)
  6771. (setq getkey-func
  6772. (or (and interactive?
  6773. (org-read-function
  6774. "Function for extracting keys: "))
  6775. (error "Missing key extractor")))))
  6776. (and (= (downcase sorting-type) ?r)
  6777. (not property)
  6778. (setq property
  6779. (completing-read "Property: "
  6780. (mapcar #'list (org-buffer-property-keys t))
  6781. nil t)))
  6782. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6783. (message "Sorting entries...")
  6784. (save-restriction
  6785. (narrow-to-region start end)
  6786. (let ((restore-clock?
  6787. ;; The clock marker is lost when using `sort-subr'; mark
  6788. ;; the clock with temporary `:org-clock-marker-backup'
  6789. ;; text property.
  6790. (when (and (eq (org-clocking-buffer) (current-buffer))
  6791. (<= start (marker-position org-clock-marker))
  6792. (>= end (marker-position org-clock-marker)))
  6793. (with-silent-modifications
  6794. (put-text-property (1- org-clock-marker) org-clock-marker
  6795. :org-clock-marker-backup t))
  6796. t))
  6797. (dcst (downcase sorting-type))
  6798. (case-fold-search nil)
  6799. (now (current-time)))
  6800. (org-preserve-local-variables
  6801. (sort-subr
  6802. (/= dcst sorting-type)
  6803. ;; This function moves to the beginning character of the
  6804. ;; "record" to be sorted.
  6805. (lambda nil
  6806. (if (re-search-forward re nil t)
  6807. (goto-char (match-beginning 0))
  6808. (goto-char (point-max))))
  6809. ;; This function moves to the last character of the "record" being
  6810. ;; sorted.
  6811. (lambda nil
  6812. (save-match-data
  6813. (condition-case nil
  6814. (outline-forward-same-level 1)
  6815. (error
  6816. (goto-char (point-max))))))
  6817. ;; This function returns the value that gets sorted against.
  6818. (lambda ()
  6819. (cond
  6820. ((= dcst ?n)
  6821. (string-to-number
  6822. (org-sort-remove-invisible (org-get-heading t t t t))))
  6823. ((= dcst ?a)
  6824. (funcall case-func
  6825. (org-sort-remove-invisible (org-get-heading t t t t))))
  6826. ((= dcst ?k)
  6827. (or (get-text-property (point) :org-clock-minutes) 0))
  6828. ((= dcst ?t)
  6829. (let ((end (save-excursion (outline-next-heading) (point))))
  6830. (if (or (re-search-forward org-ts-regexp end t)
  6831. (re-search-forward org-ts-regexp-both end t))
  6832. (org-time-string-to-seconds (match-string 0))
  6833. (float-time now))))
  6834. ((= dcst ?c)
  6835. (let ((end (save-excursion (outline-next-heading) (point))))
  6836. (if (re-search-forward
  6837. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6838. end t)
  6839. (org-time-string-to-seconds (match-string 0))
  6840. (float-time now))))
  6841. ((= dcst ?s)
  6842. (let ((end (save-excursion (outline-next-heading) (point))))
  6843. (if (re-search-forward org-scheduled-time-regexp end t)
  6844. (org-time-string-to-seconds (match-string 1))
  6845. (float-time now))))
  6846. ((= dcst ?d)
  6847. (let ((end (save-excursion (outline-next-heading) (point))))
  6848. (if (re-search-forward org-deadline-time-regexp end t)
  6849. (org-time-string-to-seconds (match-string 1))
  6850. (float-time now))))
  6851. ((= dcst ?p)
  6852. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  6853. (string-to-char (match-string 2))
  6854. org-priority-default))
  6855. ((= dcst ?r)
  6856. (or (org-entry-get nil property) ""))
  6857. ((= dcst ?o)
  6858. (when (looking-at org-complex-heading-regexp)
  6859. (let* ((m (match-string 2))
  6860. (s (if (member m org-done-keywords) '- '+)))
  6861. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6862. ((= dcst ?f)
  6863. (if getkey-func
  6864. (progn
  6865. (setq tmp (funcall getkey-func))
  6866. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6867. tmp)
  6868. (error "Invalid key function `%s'" getkey-func)))
  6869. (t (error "Invalid sorting type `%c'" sorting-type))))
  6870. nil
  6871. (cond
  6872. ((= dcst ?a) 'string-collate-lessp)
  6873. ((= dcst ?f)
  6874. (or compare-func
  6875. (and interactive?
  6876. (org-read-function
  6877. (concat "Function for comparing keys "
  6878. "(empty for default `sort-subr' predicate): ")
  6879. 'allow-empty))))
  6880. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6881. (org-cycle-hide-drawers 'all)
  6882. (when restore-clock?
  6883. (move-marker org-clock-marker
  6884. (1+ (next-single-property-change
  6885. start :org-clock-marker-backup)))
  6886. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6887. '(:org-clock-marker-backup t)))))
  6888. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6889. (message "Sorting entries...done")))
  6890. (defun org-contextualize-keys (alist contexts)
  6891. "Return valid elements in ALIST depending on CONTEXTS.
  6892. `org-agenda-custom-commands' or `org-capture-templates' are the
  6893. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6894. or `org-capture-templates-contexts' are the associated contexts
  6895. definitions."
  6896. (let ((contexts
  6897. ;; normalize contexts
  6898. (mapcar
  6899. (lambda(c) (cond ((listp (cadr c))
  6900. (list (car c) (car c) (nth 1 c)))
  6901. ((string= "" (cadr c))
  6902. (list (car c) (car c) (nth 2 c)))
  6903. (t c)))
  6904. contexts))
  6905. (a alist) r s)
  6906. ;; loop over all commands or templates
  6907. (dolist (c a)
  6908. (let (vrules repl)
  6909. (cond
  6910. ((not (assoc (car c) contexts))
  6911. (push c r))
  6912. ((and (assoc (car c) contexts)
  6913. (setq vrules (org-contextualize-validate-key
  6914. (car c) contexts)))
  6915. (mapc (lambda (vr)
  6916. (unless (equal (car vr) (cadr vr))
  6917. (setq repl vr)))
  6918. vrules)
  6919. (if (not repl) (push c r)
  6920. (push (cadr repl) s)
  6921. (push
  6922. (cons (car c)
  6923. (cdr (or (assoc (cadr repl) alist)
  6924. (error "Undefined key `%s' as contextual replacement for `%s'"
  6925. (cadr repl) (car c)))))
  6926. r))))))
  6927. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6928. (delq
  6929. nil
  6930. (delete-dups
  6931. (mapcar (lambda (x)
  6932. (let ((tpl (car x)))
  6933. (unless (delq
  6934. nil
  6935. (mapcar (lambda (y)
  6936. (equal y tpl))
  6937. s))
  6938. x)))
  6939. (reverse r))))))
  6940. (defun org-contextualize-validate-key (key contexts)
  6941. "Check CONTEXTS for agenda or capture KEY."
  6942. (let (res)
  6943. (dolist (r contexts)
  6944. (dolist (rr (car (last r)))
  6945. (when
  6946. (and (equal key (car r))
  6947. (if (functionp rr) (funcall rr)
  6948. (or (and (eq (car rr) 'in-file)
  6949. (buffer-file-name)
  6950. (string-match (cdr rr) (buffer-file-name)))
  6951. (and (eq (car rr) 'in-mode)
  6952. (string-match (cdr rr) (symbol-name major-mode)))
  6953. (and (eq (car rr) 'in-buffer)
  6954. (string-match (cdr rr) (buffer-name)))
  6955. (when (and (eq (car rr) 'not-in-file)
  6956. (buffer-file-name))
  6957. (not (string-match (cdr rr) (buffer-file-name))))
  6958. (when (eq (car rr) 'not-in-mode)
  6959. (not (string-match (cdr rr) (symbol-name major-mode))))
  6960. (when (eq (car rr) 'not-in-buffer)
  6961. (not (string-match (cdr rr) (buffer-name)))))))
  6962. (push r res))))
  6963. (delete-dups (delq nil res))))
  6964. ;; Defined to provide a value for defcustom, since there is no
  6965. ;; string-collate-greaterp in Emacs.
  6966. (defun org-string-collate-greaterp (s1 s2)
  6967. "Return non-nil if S1 is greater than S2 in collation order."
  6968. (not (string-collate-lessp s1 s2)))
  6969. ;;;###autoload
  6970. (defun org-run-like-in-org-mode (cmd)
  6971. "Run a command, pretending that the current buffer is in Org mode.
  6972. This will temporarily bind local variables that are typically bound in
  6973. Org mode to the values they have in Org mode, and then interactively
  6974. call CMD."
  6975. (org-load-modules-maybe)
  6976. (let (vars vals)
  6977. (dolist (var (org-get-local-variables))
  6978. (when (or (not (boundp (car var)))
  6979. (eq (symbol-value (car var))
  6980. (default-value (car var))))
  6981. (push (car var) vars)
  6982. (push (cadr var) vals)))
  6983. (cl-progv vars vals
  6984. (call-interactively cmd))))
  6985. (defun org-get-category (&optional pos force-refresh)
  6986. "Get the category applying to position POS."
  6987. (save-match-data
  6988. (when force-refresh (org-refresh-category-properties))
  6989. (let ((pos (or pos (point))))
  6990. (if (org-element--cache-active-p)
  6991. ;; Sync cache.
  6992. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  6993. (or (org-entry-get-with-inheritance "CATEGORY")
  6994. "???"))
  6995. (or (get-text-property pos 'org-category)
  6996. (progn
  6997. (org-refresh-category-properties)
  6998. (get-text-property pos 'org-category)))))))
  6999. ;;; Refresh properties
  7000. (defun org-refresh-properties (dprop tprop)
  7001. "Refresh buffer text properties.
  7002. DPROP is the drawer property and TPROP is either the
  7003. corresponding text property to set, or an alist with each element
  7004. being a text property (as a symbol) and a function to apply to
  7005. the value of the drawer property."
  7006. (let* ((case-fold-search t)
  7007. (inhibit-read-only t)
  7008. (inherit? (org-property-inherit-p dprop))
  7009. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7010. (global-or-keyword (and inherit?
  7011. (org--property-global-or-keyword-value dprop nil))))
  7012. (with-silent-modifications
  7013. (org-with-point-at 1
  7014. ;; Set global and keyword based values to the whole buffer.
  7015. (when global-or-keyword
  7016. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7017. ;; Set values based on property-drawers throughout the document.
  7018. (while (re-search-forward property-re nil t)
  7019. (when (org-at-property-p)
  7020. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7021. (outline-next-heading))))))
  7022. (defun org-refresh-property (tprop p &optional inherit)
  7023. "Refresh the buffer text property TPROP from the drawer property P.
  7024. The refresh happens only for the current entry, or the whole
  7025. sub-tree if optional argument INHERIT is non-nil.
  7026. If point is before first headline, the function applies to the
  7027. part before the first headline. In that particular case, when
  7028. optional argument INHERIT is non-nil, it refreshes properties for
  7029. the whole buffer."
  7030. (save-excursion
  7031. (org-back-to-heading-or-point-min t)
  7032. (let ((start (point))
  7033. (end (save-excursion
  7034. (cond ((and inherit (org-before-first-heading-p))
  7035. (point-max))
  7036. (inherit
  7037. (org-end-of-subtree t t))
  7038. ((outline-next-heading))
  7039. ((point-max))))))
  7040. (with-silent-modifications
  7041. (if (symbolp tprop)
  7042. ;; TPROP is a text property symbol.
  7043. (put-text-property start end tprop p)
  7044. ;; TPROP is an alist with (property . function) elements.
  7045. (pcase-dolist (`(,prop . ,f) tprop)
  7046. (put-text-property start end prop (funcall f p))))))))
  7047. (defun org-refresh-category-properties ()
  7048. "Refresh category text properties in the buffer."
  7049. (unless (org-element--cache-active-p)
  7050. (let ((case-fold-search t)
  7051. (inhibit-read-only t)
  7052. (default-category
  7053. (cond ((null org-category)
  7054. (if buffer-file-name
  7055. (file-name-sans-extension
  7056. (file-name-nondirectory buffer-file-name))
  7057. "???"))
  7058. ((symbolp org-category) (symbol-name org-category))
  7059. (t org-category))))
  7060. (let ((category (catch 'buffer-category
  7061. (org-with-wide-buffer
  7062. (goto-char (point-max))
  7063. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7064. (let ((element (org-element-at-point-no-context)))
  7065. (when (eq (org-element-type element) 'keyword)
  7066. (throw 'buffer-category
  7067. (org-element-property :value element))))))
  7068. default-category)))
  7069. (with-silent-modifications
  7070. (org-with-wide-buffer
  7071. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7072. ;; keyword. If none is found, fall-back to `org-category' or
  7073. ;; buffer file name, or set it by the document property drawer.
  7074. (put-text-property (point-min) (point-max)
  7075. 'org-category category)
  7076. ;; Set categories from the document property drawer or
  7077. ;; property drawers in the outline. If category is found in
  7078. ;; the property drawer for the whole buffer that value
  7079. ;; overrides the keyword-based value set above.
  7080. (goto-char (point-min))
  7081. (let ((regexp (org-re-property "CATEGORY")))
  7082. (while (re-search-forward regexp nil t)
  7083. (let ((value (match-string-no-properties 3)))
  7084. (when (org-at-property-p)
  7085. (put-text-property
  7086. (save-excursion (org-back-to-heading-or-point-min t))
  7087. (save-excursion (if (org-before-first-heading-p)
  7088. (point-max)
  7089. (org-end-of-subtree t t)))
  7090. 'org-category
  7091. value)))))))))))
  7092. (defun org-refresh-stats-properties ()
  7093. "Refresh stats text properties in the buffer."
  7094. (with-silent-modifications
  7095. (org-with-point-at 1
  7096. (let ((regexp (concat org-outline-regexp-bol
  7097. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7098. (while (re-search-forward regexp nil t)
  7099. (let* ((numerator (string-to-number (match-string 1)))
  7100. (denominator (and (match-end 2)
  7101. (string-to-number (match-string 2))))
  7102. (stats (cond ((not denominator) numerator) ;percent
  7103. ((= denominator 0) 0)
  7104. (t (/ (* numerator 100) denominator)))))
  7105. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7106. 'org-stats stats)))))))
  7107. (defun org-refresh-effort-properties ()
  7108. "Refresh effort properties."
  7109. (org-refresh-properties
  7110. org-effort-property
  7111. '((effort . identity)
  7112. (effort-minutes . org-duration-to-minutes))))
  7113. (defun org-find-file-at-mouse (ev)
  7114. "Open file link or URL at mouse."
  7115. (interactive "e")
  7116. (mouse-set-point ev)
  7117. (org-open-at-point 'in-emacs))
  7118. (defun org-open-at-mouse (ev)
  7119. "Open file link or URL at mouse.
  7120. See the docstring of `org-open-file' for details."
  7121. (interactive "e")
  7122. (mouse-set-point ev)
  7123. (when (eq major-mode 'org-agenda-mode)
  7124. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7125. (org-open-at-point))
  7126. (defvar org-window-config-before-follow-link nil
  7127. "The window configuration before following a link.
  7128. This is saved in case the need arises to restore it.")
  7129. (defun org--file-default-apps ()
  7130. "Return the default applications for this operating system."
  7131. (pcase system-type
  7132. (`darwin org-file-apps-macos)
  7133. (`windows-nt org-file-apps-windowsnt)
  7134. (_ org-file-apps-gnu)))
  7135. (defun org--file-apps-entry-dlink-p (entry)
  7136. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7137. It assumes that is the case when the entry uses a regular
  7138. expression which has at least one grouping construct and the
  7139. action is either a Lisp form or a command string containing
  7140. \"%1\", i.e., using at least one subexpression match as
  7141. a parameter."
  7142. (pcase entry
  7143. (`(,selector . ,action)
  7144. (and (stringp selector)
  7145. (> (regexp-opt-depth selector) 0)
  7146. (or (and (stringp action)
  7147. (string-match "%[0-9]" action))
  7148. (consp action))))
  7149. (_ nil)))
  7150. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7151. "Convert extensions to regular expressions in the cars of LIST.
  7152. Also, weed out any non-string entries, because the return value
  7153. is used only for regexp matching.
  7154. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7155. point to the symbol `emacs', indicating that the file should be
  7156. opened in Emacs."
  7157. (append
  7158. (delq nil
  7159. (mapcar (lambda (x)
  7160. (unless (not (stringp (car x)))
  7161. (if (string-match "\\W" (car x))
  7162. x
  7163. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7164. list))
  7165. (when add-auto-mode
  7166. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7167. ;;;###autoload
  7168. (defun org-open-file (path &optional in-emacs line search)
  7169. "Open the file at PATH.
  7170. First, this expands any special file name abbreviations. Then the
  7171. configuration variable `org-file-apps' is checked if it contains an
  7172. entry for this file type, and if yes, the corresponding command is launched.
  7173. If no application is found, Emacs simply visits the file.
  7174. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7175. With a double \\[universal-argument] \\[universal-argument] \
  7176. prefix arg, Org tries to avoid opening in Emacs
  7177. and to use an external application to visit the file.
  7178. Optional LINE specifies a line to go to, optional SEARCH a string
  7179. to search for. If LINE or SEARCH is given, the file will be
  7180. opened in Emacs, unless an entry from `org-file-apps' that makes
  7181. use of groups in a regexp matches.
  7182. If you want to change the way frames are used when following a
  7183. link, please customize `org-link-frame-setup'.
  7184. If the file does not exist, throw an error."
  7185. (let* ((file (if (equal path "") buffer-file-name
  7186. (substitute-in-file-name (expand-file-name path))))
  7187. (file-apps (append org-file-apps (org--file-default-apps)))
  7188. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7189. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7190. file-apps))
  7191. (remp (and (assq 'remote apps) (file-remote-p file)))
  7192. (dirp (unless remp (file-directory-p file)))
  7193. (file (if (and dirp org-open-directory-means-index-dot-org)
  7194. (concat (file-name-as-directory file) "index.org")
  7195. file))
  7196. (a-m-a-p (assq 'auto-mode apps))
  7197. (dfile (downcase file))
  7198. ;; Reconstruct the original link from the PATH, LINE and
  7199. ;; SEARCH args.
  7200. (link (cond (line (concat file "::" (number-to-string line)))
  7201. (search (concat file "::" search))
  7202. (t file)))
  7203. (dlink (downcase link))
  7204. (ext
  7205. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7206. (match-string 1 dfile)))
  7207. (save-position-maybe
  7208. (let ((old-buffer (current-buffer))
  7209. (old-pos (point))
  7210. (old-mode major-mode))
  7211. (lambda ()
  7212. (and (derived-mode-p 'org-mode)
  7213. (eq old-mode 'org-mode)
  7214. (or (not (eq old-buffer (current-buffer)))
  7215. (not (eq old-pos (point))))
  7216. (org-mark-ring-push old-pos old-buffer)))))
  7217. cmd link-match-data)
  7218. (cond
  7219. ((member in-emacs '((16) system))
  7220. (setq cmd (cdr (assq 'system apps))))
  7221. (in-emacs (setq cmd 'emacs))
  7222. (t
  7223. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7224. (and dirp (cdr (assq 'directory apps)))
  7225. ;; First, try matching against apps-dlink if we
  7226. ;; get a match here, store the match data for
  7227. ;; later.
  7228. (let ((match (assoc-default dlink apps-dlink
  7229. 'string-match)))
  7230. (if match
  7231. (progn (setq link-match-data (match-data))
  7232. match)
  7233. (progn (setq in-emacs (or in-emacs line search))
  7234. nil))) ; if we have no match in apps-dlink,
  7235. ; always open the file in emacs if line or search
  7236. ; is given (for backwards compatibility)
  7237. (assoc-default dfile
  7238. (org--file-apps-regexp-alist apps a-m-a-p)
  7239. 'string-match)
  7240. (cdr (assoc ext apps))
  7241. (cdr (assq t apps))))))
  7242. (when (eq cmd 'system)
  7243. (setq cmd (cdr (assq 'system apps))))
  7244. (when (eq cmd 'default)
  7245. (setq cmd (cdr (assoc t apps))))
  7246. (when (eq cmd 'mailcap)
  7247. (require 'mailcap)
  7248. (mailcap-parse-mailcaps)
  7249. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7250. (command (mailcap-mime-info mime-type)))
  7251. (if (stringp command)
  7252. (setq cmd command)
  7253. (setq cmd 'emacs))))
  7254. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7255. (not (file-exists-p file))
  7256. (not org-open-non-existing-files))
  7257. (user-error "No such file: %s" file))
  7258. (cond
  7259. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7260. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7261. (while (string-match "['\"]%s['\"]" cmd)
  7262. (setq cmd (replace-match "%s" t t cmd)))
  7263. (setq cmd (replace-regexp-in-string
  7264. "%s"
  7265. (shell-quote-argument (convert-standard-filename file))
  7266. cmd
  7267. nil t))
  7268. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7269. (save-match-data
  7270. (let ((match-index 1)
  7271. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7272. (set-match-data link-match-data)
  7273. (while (<= match-index number-of-groups)
  7274. (let ((regex (concat "%" (number-to-string match-index)))
  7275. (replace-with (match-string match-index dlink)))
  7276. (while (string-match regex cmd)
  7277. (setq cmd (replace-match replace-with t t cmd))))
  7278. (setq match-index (+ match-index 1)))))
  7279. (save-window-excursion
  7280. (message "Running %s...done" cmd)
  7281. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7282. ;; and exit immediately. Use pipe connection type instead of pty to
  7283. ;; avoid killing children processes with SIGHUP when temporary terminal
  7284. ;; session is finished.
  7285. ;;
  7286. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7287. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7288. ;; error messages.
  7289. (let ((process-connection-type nil))
  7290. (start-process-shell-command cmd nil cmd))
  7291. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7292. ((or (stringp cmd)
  7293. (eq cmd 'emacs))
  7294. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7295. (widen)
  7296. (cond (line (org-goto-line line)
  7297. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7298. (search (condition-case err
  7299. (org-link-search search)
  7300. ;; Save position before error-ing out so user
  7301. ;; can easily move back to the original buffer.
  7302. (error (funcall save-position-maybe)
  7303. (error (nth 1 err)))))))
  7304. ((functionp cmd)
  7305. (save-match-data
  7306. (set-match-data link-match-data)
  7307. (condition-case nil
  7308. (funcall cmd file link)
  7309. ;; FIXME: Remove this check when most default installations
  7310. ;; of Emacs have at least Org 9.0.
  7311. ((debug wrong-number-of-arguments wrong-type-argument
  7312. invalid-function)
  7313. (user-error "Please see Org News for version 9.0 about \
  7314. `org-file-apps'--Lisp error: %S" cmd)))))
  7315. ((consp cmd)
  7316. ;; FIXME: Remove this check when most default installations of
  7317. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7318. ;; fall back to `org-link-frame-setup' for an old usage of
  7319. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7320. (user-error "Please see Org News for version 9.0 about \
  7321. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7322. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7323. (funcall save-position-maybe)))
  7324. ;;;###autoload
  7325. (defun org-open-at-point-global ()
  7326. "Follow a link or a time-stamp like Org mode does.
  7327. Also follow links and emails as seen by `thing-at-point'.
  7328. This command can be called in any mode to follow an external
  7329. link or a time-stamp that has Org mode syntax. Its behavior
  7330. is undefined when called on internal links like fuzzy links.
  7331. Raise a user error when there is nothing to follow."
  7332. (interactive)
  7333. (let ((tap-url (thing-at-point 'url))
  7334. (tap-email (thing-at-point 'email)))
  7335. (cond ((org-in-regexp org-link-any-re)
  7336. (org-link-open-from-string (match-string-no-properties 0)))
  7337. ((or (org-in-regexp org-ts-regexp-both nil t)
  7338. (org-in-regexp org-tsr-regexp-both nil t))
  7339. (org-follow-timestamp-link))
  7340. (tap-url (org-link-open-from-string tap-url))
  7341. (tap-email (org-link-open-from-string
  7342. (concat "mailto:" tap-email)))
  7343. (t (user-error "No link found")))))
  7344. (defvar org-open-at-point-functions nil
  7345. "Hook that is run when following a link at point.
  7346. Functions in this hook must return t if they identify and follow
  7347. a link at point. If they don't find anything interesting at point,
  7348. they must return nil.")
  7349. (defun org-open-at-point (&optional arg)
  7350. "Open thing at point.
  7351. The thing can be a link, citation, timestamp, footnote, src-block or
  7352. tags.
  7353. When point is on a link, follow it. Normally, files will be
  7354. opened by an appropriate application. If the optional prefix
  7355. argument ARG is non-nil, Emacs will visit the file. With
  7356. a double prefix argument, try to open outside of Emacs, in the
  7357. application the system uses for this file type.
  7358. When point is on a timestamp, open the agenda at the day
  7359. specified.
  7360. When point is a footnote definition, move to the first reference
  7361. found. If it is on a reference, move to the associated
  7362. definition.
  7363. When point is on a src-block of inline src-block, open its result.
  7364. When point is on a citation, follow it.
  7365. When point is on a headline, display a list of every link in the
  7366. entry, so it is possible to pick one, or all, of them. If point
  7367. is on a tag, call `org-tags-view' instead.
  7368. On top of syntactically correct links, this function also tries
  7369. to open links and time-stamps in comments, node properties, and
  7370. keywords if point is on something looking like a timestamp or
  7371. a link."
  7372. (interactive "P")
  7373. (org-load-modules-maybe)
  7374. (setq org-window-config-before-follow-link (current-window-configuration))
  7375. (org-remove-occur-highlights nil nil t)
  7376. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7377. (let* ((context
  7378. ;; Only consider supported types, even if they are not the
  7379. ;; closest one.
  7380. (org-element-lineage
  7381. (org-element-context)
  7382. '(citation citation-reference clock comment comment-block
  7383. footnote-definition footnote-reference headline
  7384. inline-src-block inlinetask keyword link node-property
  7385. planning src-block timestamp)
  7386. t))
  7387. (type (org-element-type context))
  7388. (value (org-element-property :value context)))
  7389. (cond
  7390. ((not type) (user-error "No link found"))
  7391. ;; No valid link at point. For convenience, look if something
  7392. ;; looks like a link under point in some specific places.
  7393. ((memq type '(comment comment-block node-property keyword))
  7394. (call-interactively #'org-open-at-point-global))
  7395. ;; On a headline or an inlinetask, but not on a timestamp,
  7396. ;; a link, a footnote reference or a citation.
  7397. ((memq type '(headline inlinetask))
  7398. (org-match-line org-complex-heading-regexp)
  7399. (let ((tags-beg (match-beginning 5))
  7400. (tags-end (match-end 5)))
  7401. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7402. ;; On tags.
  7403. (org-tags-view
  7404. arg
  7405. (save-excursion
  7406. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7407. (end-tag (search-forward ":" tags-end nil 2)))
  7408. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7409. ;; Not on tags.
  7410. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7411. (`(nil . ,_)
  7412. (require 'org-attach)
  7413. (when (org-attach-dir)
  7414. (message "Opening attachment")
  7415. (if (equal arg '(4))
  7416. (org-attach-reveal-in-emacs)
  7417. (org-attach-reveal))))
  7418. (`(,links . ,links-end)
  7419. (dolist (link (if (stringp links) (list links) links))
  7420. (search-forward link nil links-end)
  7421. (goto-char (match-beginning 0))
  7422. (org-open-at-point arg)))))))
  7423. ;; On a footnote reference or at definition's label.
  7424. ((or (eq type 'footnote-reference)
  7425. (and (eq type 'footnote-definition)
  7426. (save-excursion
  7427. ;; Do not validate action when point is on the
  7428. ;; spaces right after the footnote label, in order
  7429. ;; to be on par with behavior on links.
  7430. (skip-chars-forward " \t")
  7431. (let ((begin
  7432. (org-element-property :contents-begin context)))
  7433. (if begin (< (point) begin)
  7434. (= (org-element-property :post-affiliated context)
  7435. (line-beginning-position)))))))
  7436. (org-footnote-action))
  7437. ;; On a planning line. Check if we are really on a timestamp.
  7438. ((and (eq type 'planning)
  7439. (org-in-regexp org-ts-regexp-both nil t))
  7440. (org-follow-timestamp-link))
  7441. ;; On a clock line, make sure point is on the timestamp
  7442. ;; before opening it.
  7443. ((and (eq type 'clock)
  7444. value
  7445. (>= (point) (org-element-property :begin value))
  7446. (<= (point) (org-element-property :end value)))
  7447. (org-follow-timestamp-link))
  7448. ((eq type 'src-block) (org-babel-open-src-block-result))
  7449. ;; Do nothing on white spaces after an object.
  7450. ((>= (point)
  7451. (save-excursion
  7452. (goto-char (org-element-property :end context))
  7453. (skip-chars-backward " \t")
  7454. (point)))
  7455. (user-error "No link found"))
  7456. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7457. ((eq type 'timestamp) (org-follow-timestamp-link))
  7458. ((eq type 'link) (org-link-open context arg))
  7459. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7460. (t (user-error "No link found")))))
  7461. (run-hook-with-args 'org-follow-link-hook))
  7462. ;;;###autoload
  7463. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7464. "Offer links in the current entry and return the selected link.
  7465. If there is only one link, return it.
  7466. If NTH is an integer, return the NTH link found.
  7467. If ZERO is a string, check also this string for a link, and if
  7468. there is one, return it."
  7469. (with-current-buffer buffer
  7470. (org-with-wide-buffer
  7471. (goto-char marker)
  7472. (let ((cnt ?0)
  7473. have-zero end links link c)
  7474. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7475. (push (match-string 0 zero) links)
  7476. (setq cnt (1- cnt) have-zero t))
  7477. (save-excursion
  7478. (org-back-to-heading t)
  7479. (setq end (save-excursion (outline-next-heading) (point)))
  7480. (while (re-search-forward org-link-any-re end t)
  7481. ;; Only consider valid links or links openable via
  7482. ;; `org-open-at-point'.
  7483. (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
  7484. (push (match-string 0) links)))
  7485. (setq links (org-uniquify (reverse links))))
  7486. (cond
  7487. ((null links)
  7488. (message "No links"))
  7489. ((equal (length links) 1)
  7490. (setq link (car links)))
  7491. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7492. (setq link (nth (if have-zero nth (1- nth)) links)))
  7493. (t ; we have to select a link
  7494. (save-excursion
  7495. (save-window-excursion
  7496. (delete-other-windows)
  7497. (with-output-to-temp-buffer "*Select Link*"
  7498. (dolist (l links)
  7499. (cond
  7500. ((not (string-match org-link-bracket-re l))
  7501. (princ (format "[%c] %s\n" (cl-incf cnt)
  7502. (org-unbracket-string "<" ">" l))))
  7503. ((match-end 2)
  7504. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7505. (match-string 2 l) (match-string 1 l))))
  7506. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7507. (match-string 1 l)))))))
  7508. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7509. (message "Select link to open, RET to open all:")
  7510. (setq c (read-char-exclusive))
  7511. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7512. (when (equal c ?q) (user-error "Abort"))
  7513. (if (equal c ?\C-m)
  7514. (setq link links)
  7515. (setq nth (- c ?0))
  7516. (when have-zero (setq nth (1+ nth)))
  7517. (unless (and (integerp nth) (>= (length links) nth))
  7518. (user-error "Invalid link selection"))
  7519. (setq link (nth (1- nth) links)))))
  7520. (cons link end)))))
  7521. ;;; File search
  7522. (defun org-do-occur (regexp &optional cleanup)
  7523. "Call the Emacs command `occur'.
  7524. If CLEANUP is non-nil, remove the printout of the regular expression
  7525. in the *Occur* buffer. This is useful if the regex is long and not useful
  7526. to read."
  7527. (occur regexp)
  7528. (when cleanup
  7529. (let ((cwin (selected-window)) win beg end)
  7530. (when (setq win (get-buffer-window "*Occur*"))
  7531. (select-window win))
  7532. (goto-char (point-min))
  7533. (when (re-search-forward "match[a-z]+" nil t)
  7534. (setq beg (match-end 0))
  7535. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7536. (setq end (1- (match-beginning 0)))))
  7537. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7538. (goto-char (point-min))
  7539. (select-window cwin))))
  7540. ;;; The Mark Ring
  7541. (defvar org-mark-ring nil
  7542. "Mark ring for positions before jumps in Org mode.")
  7543. (defvar org-mark-ring-last-goto nil
  7544. "Last position in the mark ring used to go back.")
  7545. ;; Fill and close the ring
  7546. (setq org-mark-ring nil)
  7547. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7548. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7549. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7550. org-mark-ring)
  7551. (defun org-mark-ring-push (&optional pos buffer)
  7552. "Put the current position into the mark ring and rotate it.
  7553. Also push position into the Emacs mark ring. If optional
  7554. argument POS and BUFFER are not nil, mark this location instead."
  7555. (interactive)
  7556. (let ((pos (or pos (point)))
  7557. (buffer (or buffer (current-buffer))))
  7558. (with-current-buffer buffer
  7559. (org-with-point-at pos (push-mark nil t)))
  7560. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7561. (move-marker (car org-mark-ring) pos buffer))
  7562. (message
  7563. (substitute-command-keys
  7564. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7565. (defun org-mark-ring-goto (&optional n)
  7566. "Jump to the previous position in the mark ring.
  7567. With prefix arg N, jump back that many stored positions. When
  7568. called several times in succession, walk through the entire ring.
  7569. Org mode commands jumping to a different position in the current file,
  7570. or to another Org file, automatically push the old position onto the ring."
  7571. (interactive "p")
  7572. (let (p m)
  7573. (if (eq last-command this-command)
  7574. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7575. (setq p org-mark-ring))
  7576. (setq org-mark-ring-last-goto p)
  7577. (setq m (car p))
  7578. (pop-to-buffer-same-window (marker-buffer m))
  7579. (goto-char m)
  7580. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7581. ;;; Following specific links
  7582. (defvar org-agenda-buffer-tmp-name)
  7583. (defvar org-agenda-start-on-weekday)
  7584. (defvar org-agenda-buffer-name)
  7585. (defun org-follow-timestamp-link ()
  7586. "Open an agenda view for the time-stamp date/range at point."
  7587. ;; Avoid changing the global value.
  7588. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7589. (cond
  7590. ((org-at-date-range-p t)
  7591. (let ((org-agenda-start-on-weekday)
  7592. (t1 (match-string 1))
  7593. (t2 (match-string 2)) tt1 tt2)
  7594. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7595. tt2 (time-to-days (org-time-string-to-time t2)))
  7596. (let ((org-agenda-buffer-tmp-name
  7597. (format "*Org Agenda(a:%s)"
  7598. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7599. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7600. ((org-at-timestamp-p 'lax)
  7601. (let ((org-agenda-buffer-tmp-name
  7602. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7603. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7604. (substring (match-string 1) 0 10)))
  7605. 1)))
  7606. (t (error "This should not happen")))))
  7607. ;;; Following file links
  7608. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7609. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7610. (declare-function mailcap-mime-info
  7611. "mailcap" (string &optional request no-decode))
  7612. (defvar org-wait nil)
  7613. ;;;; Refiling
  7614. (defun org-get-org-file ()
  7615. "Read a filename, with default directory `org-directory'."
  7616. (let ((default (or org-default-notes-file remember-data-file)))
  7617. (read-file-name (format "File name [%s]: " default)
  7618. (file-name-as-directory org-directory)
  7619. default)))
  7620. (defun org-notes-order-reversed-p ()
  7621. "Check if the current file should receive notes in reversed order."
  7622. (cond
  7623. ((not org-reverse-note-order) nil)
  7624. ((eq t org-reverse-note-order) t)
  7625. ((not (listp org-reverse-note-order)) nil)
  7626. (t (catch 'exit
  7627. (dolist (entry org-reverse-note-order)
  7628. (when (string-match (car entry) buffer-file-name)
  7629. (throw 'exit (cdr entry))))))))
  7630. (defvar org-agenda-new-buffers nil
  7631. "Buffers created to visit agenda files.")
  7632. (declare-function org-string-nw-p "org-macs" (s))
  7633. ;;;; Dynamic blocks
  7634. (defun org-find-dblock (name)
  7635. "Find the first dynamic block with name NAME in the buffer.
  7636. If not found, stay at current position and return nil."
  7637. (let ((case-fold-search t) pos)
  7638. (save-excursion
  7639. (goto-char (point-min))
  7640. (setq pos (and (re-search-forward
  7641. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7642. (match-beginning 0))))
  7643. (when pos (goto-char pos))
  7644. pos))
  7645. (defun org-create-dblock (plist)
  7646. "Create a dynamic block section, with parameters taken from PLIST.
  7647. PLIST must contain a :name entry which is used as the name of the block."
  7648. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7649. (end-of-line 1)
  7650. (newline))
  7651. (let ((col (current-column))
  7652. (name (plist-get plist :name)))
  7653. (insert "#+BEGIN: " name)
  7654. (while plist
  7655. (if (eq (car plist) :name)
  7656. (setq plist (cddr plist))
  7657. (insert " " (prin1-to-string (pop plist)))))
  7658. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7659. (beginning-of-line -2)))
  7660. (defun org-prepare-dblock ()
  7661. "Prepare dynamic block for refresh.
  7662. This empties the block, puts the cursor at the insert position and returns
  7663. the property list including an extra property :name with the block name."
  7664. (unless (looking-at org-dblock-start-re)
  7665. (user-error "Not at a dynamic block"))
  7666. (let* ((begdel (1+ (match-end 0)))
  7667. (name (org-no-properties (match-string 1)))
  7668. (params (append (list :name name)
  7669. (read (concat "(" (match-string 3) ")")))))
  7670. (save-excursion
  7671. (beginning-of-line 1)
  7672. (skip-chars-forward " \t")
  7673. (setq params (plist-put params :indentation-column (current-column))))
  7674. (unless (re-search-forward org-dblock-end-re nil t)
  7675. (error "Dynamic block not terminated"))
  7676. (setq params
  7677. (append params
  7678. (list :content (buffer-substring
  7679. begdel (match-beginning 0)))))
  7680. (delete-region begdel (match-beginning 0))
  7681. (goto-char begdel)
  7682. (open-line 1)
  7683. params))
  7684. (defun org-map-dblocks (&optional command)
  7685. "Apply COMMAND to all dynamic blocks in the current buffer.
  7686. If COMMAND is not given, use `org-update-dblock'."
  7687. (let ((cmd (or command 'org-update-dblock)))
  7688. (save-excursion
  7689. (goto-char (point-min))
  7690. (while (re-search-forward org-dblock-start-re nil t)
  7691. (goto-char (match-beginning 0))
  7692. (save-excursion
  7693. (condition-case nil
  7694. (funcall cmd)
  7695. (error (message "Error during update of dynamic block"))))
  7696. (unless (re-search-forward org-dblock-end-re nil t)
  7697. (error "Dynamic block not terminated"))))))
  7698. (defvar org-dynamic-block-alist nil
  7699. "Alist defining all the Org dynamic blocks.
  7700. The key is the dynamic block type name, as a string. The value
  7701. is the function used to insert the dynamic block.
  7702. Use `org-dynamic-block-define' to populate it.")
  7703. (defun org-dynamic-block-function (type)
  7704. "Return function associated to a given dynamic block type.
  7705. TYPE is the dynamic block type, as a string."
  7706. (cdr (assoc type org-dynamic-block-alist)))
  7707. (defun org-dynamic-block-types ()
  7708. "List all defined dynamic block types."
  7709. (mapcar #'car org-dynamic-block-alist))
  7710. (defun org-dynamic-block-define (type func)
  7711. "Define dynamic block TYPE with FUNC.
  7712. TYPE is a string. FUNC is the function creating the dynamic
  7713. block of such type."
  7714. (pcase (assoc type org-dynamic-block-alist)
  7715. (`nil (push (cons type func) org-dynamic-block-alist))
  7716. (def (setcdr def func))))
  7717. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7718. "Insert a dynamic block of type TYPE.
  7719. When used interactively, select the dynamic block types among
  7720. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7721. is non-nil, call the dynamic block function interactively."
  7722. (interactive (list (completing-read "Dynamic block: "
  7723. (org-dynamic-block-types))
  7724. t))
  7725. (pcase (org-dynamic-block-function type)
  7726. (`nil (error "No such dynamic block: %S" type))
  7727. ((and f (pred functionp))
  7728. (if interactive-p (call-interactively f) (funcall f)))
  7729. (_ (error "Invalid function for dynamic block %S" type))))
  7730. (defun org-dblock-update (&optional arg)
  7731. "User command for updating dynamic blocks.
  7732. Update the dynamic block at point. With prefix ARG, update all dynamic
  7733. blocks in the buffer."
  7734. (interactive "P")
  7735. (if arg
  7736. (org-update-all-dblocks)
  7737. (or (looking-at org-dblock-start-re)
  7738. (org-beginning-of-dblock))
  7739. (org-update-dblock)))
  7740. (defun org-update-dblock ()
  7741. "Update the dynamic block at point.
  7742. This means to empty the block, parse for parameters and then call
  7743. the correct writing function."
  7744. (interactive)
  7745. (save-excursion
  7746. (let* ((win (selected-window))
  7747. (pos (point))
  7748. (line (org-current-line))
  7749. (params (org-prepare-dblock))
  7750. (name (plist-get params :name))
  7751. (indent (plist-get params :indentation-column))
  7752. (cmd (intern (concat "org-dblock-write:" name))))
  7753. (message "Updating dynamic block `%s' at line %d..." name line)
  7754. (funcall cmd params)
  7755. (message "Updating dynamic block `%s' at line %d...done" name line)
  7756. (goto-char pos)
  7757. (when (and indent (> indent 0))
  7758. (setq indent (make-string indent ?\ ))
  7759. (save-excursion
  7760. (select-window win)
  7761. (org-beginning-of-dblock)
  7762. (forward-line 1)
  7763. (while (not (looking-at org-dblock-end-re))
  7764. (insert indent)
  7765. (beginning-of-line 2))
  7766. (when (looking-at org-dblock-end-re)
  7767. (and (looking-at "[ \t]+")
  7768. (replace-match ""))
  7769. (insert indent)))))))
  7770. (defun org-beginning-of-dblock ()
  7771. "Find the beginning of the dynamic block at point.
  7772. Error if there is no such block at point."
  7773. (let ((pos (point))
  7774. beg)
  7775. (end-of-line 1)
  7776. (if (and (re-search-backward org-dblock-start-re nil t)
  7777. (setq beg (match-beginning 0))
  7778. (re-search-forward org-dblock-end-re nil t)
  7779. (> (match-end 0) pos))
  7780. (goto-char beg)
  7781. (goto-char pos)
  7782. (error "Not in a dynamic block"))))
  7783. (defun org-update-all-dblocks ()
  7784. "Update all dynamic blocks in the buffer.
  7785. This function can be used in a hook."
  7786. (interactive)
  7787. (when (derived-mode-p 'org-mode)
  7788. (org-map-dblocks 'org-update-dblock)))
  7789. ;;;; Completion
  7790. (declare-function org-export-backend-options "ox" (cl-x) t)
  7791. (defun org-get-export-keywords ()
  7792. "Return a list of all currently understood export keywords.
  7793. Export keywords include options, block names, attributes and
  7794. keywords relative to each registered export back-end."
  7795. (let (keywords)
  7796. (dolist (backend
  7797. (bound-and-true-p org-export-registered-backends)
  7798. (delq nil keywords))
  7799. ;; Back-end name (for keywords, like #+LATEX:)
  7800. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7801. (dolist (option-entry (org-export-backend-options backend))
  7802. ;; Back-end options.
  7803. (push (nth 1 option-entry) keywords)))))
  7804. (defconst org-options-keywords
  7805. '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
  7806. "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
  7807. "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
  7808. "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
  7809. "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
  7810. "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7811. (defcustom org-structure-template-alist
  7812. '(("a" . "export ascii")
  7813. ("c" . "center")
  7814. ("C" . "comment")
  7815. ("e" . "example")
  7816. ("E" . "export")
  7817. ("h" . "export html")
  7818. ("l" . "export latex")
  7819. ("q" . "quote")
  7820. ("s" . "src")
  7821. ("v" . "verse"))
  7822. "An alist of keys and block types.
  7823. `org-insert-structure-template' will display a menu with this list of
  7824. templates to choose from. The block type is inserted, with
  7825. \"#+begin_\" and \"#+end_\" added automatically. If the block type
  7826. consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
  7827. added instead.
  7828. The menu keys are defined by the car of each entry in this alist.
  7829. If two entries have the keys \"a\" and \"aa\" respectively, the
  7830. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7831. latter will be inserted by typing \"aa\". If an entry with the
  7832. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7833. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7834. block can be inserted by pressing TAB after the string \"<KEY\"."
  7835. :group 'org-edit-structure
  7836. :type '(repeat
  7837. (cons (string :tag "Key")
  7838. (string :tag "Template")))
  7839. :package-version '(Org . "9.2"))
  7840. (defun org--check-org-structure-template-alist (&optional checklist)
  7841. "Check whether `org-structure-template-alist' is set up correctly.
  7842. In particular, check if the Org 9.2 format is used as opposed to
  7843. previous format."
  7844. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7845. (or (symbol-value checklist)
  7846. org-structure-template-alist))))
  7847. (when elm
  7848. (org-display-warning
  7849. (format "
  7850. Please update the entries of `%s'.
  7851. In Org 9.2 the format was changed from something like
  7852. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7853. to something like
  7854. (\"s\" . \"src\")
  7855. Please refer to the documentation of `org-structure-template-alist'.
  7856. The following entries must be updated:
  7857. %s"
  7858. (or checklist 'org-structure-template-alist)
  7859. (pp-to-string elm))))))
  7860. (defun org--insert-structure-template-mks ()
  7861. "Present `org-structure-template-alist' with `org-mks'.
  7862. Menus are added if keys require more than one keystroke. Tabs
  7863. are added to single key entries when more than one stroke is
  7864. needed. Keys longer than two characters are reduced to two
  7865. characters."
  7866. (org--check-org-structure-template-alist)
  7867. (let* (case-fold-search
  7868. (templates (append org-structure-template-alist
  7869. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7870. (keys (mapcar #'car templates))
  7871. (start-letters
  7872. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7873. ;; Sort each element of `org-structure-template-alist' into
  7874. ;; sublists according to the first letter.
  7875. (superlist
  7876. (mapcar (lambda (letter)
  7877. (list letter
  7878. (cl-remove-if-not
  7879. (apply-partially #'string-match-p (concat "^" letter))
  7880. templates :key #'car)))
  7881. start-letters)))
  7882. (org-mks
  7883. (apply #'append
  7884. ;; Make an `org-mks' table. If only one element is
  7885. ;; present in a sublist, make it part of the top-menu,
  7886. ;; otherwise make a submenu according to the starting
  7887. ;; letter and populate it.
  7888. (mapcar (lambda (sublist)
  7889. (if (eq 1 (length (cadr sublist)))
  7890. (mapcar (lambda (elm)
  7891. (list (substring (car elm) 0 1)
  7892. (cdr elm) ""))
  7893. (cadr sublist))
  7894. ;; Create submenu.
  7895. (let* ((topkey (car sublist))
  7896. (elms (cadr sublist))
  7897. (keys (mapcar #'car elms))
  7898. (long (> (length elms) 3)))
  7899. (append
  7900. (list
  7901. ;; Make a description of the submenu.
  7902. (list topkey
  7903. (concat
  7904. (mapconcat #'cdr
  7905. (cl-subseq elms 0 (if long 3 (length elms)))
  7906. ", ")
  7907. (when long ", ..."))))
  7908. ;; List of entries in submenu.
  7909. (cl-mapcar #'list
  7910. (org--insert-structure-template-unique-keys keys)
  7911. (mapcar #'cdr elms)
  7912. (make-list (length elms) ""))))))
  7913. superlist))
  7914. "Select a key\n============"
  7915. "Key: ")))
  7916. (defun org--insert-structure-template-unique-keys (keys)
  7917. "Make a list of unique, two characters long elements from KEYS.
  7918. Elements of length one have a tab appended. Elements of length
  7919. two are kept as is. Longer elements are truncated to length two.
  7920. If an element cannot be made unique, an error is raised."
  7921. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7922. menu-keys)
  7923. (dolist (key ordered-keys)
  7924. (let ((potential-key
  7925. (cl-case (length key)
  7926. (1 (concat key "\t"))
  7927. (2 key)
  7928. (otherwise
  7929. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7930. (mapcar (apply-partially #'concat (substring key 0 1))
  7931. (split-string (substring key 1) "" t)))))))
  7932. (if (or (not potential-key) (assoc potential-key menu-keys))
  7933. (user-error "Could not make unique key for `%s'" key)
  7934. (push (cons potential-key key) menu-keys))))
  7935. (mapcar #'car
  7936. (cl-sort menu-keys #'<
  7937. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  7938. (defun org-insert-structure-template (type)
  7939. "Insert a block structure of the type #+begin_foo/#+end_foo.
  7940. Select a block from `org-structure-template-alist' then type
  7941. either RET, TAB or SPC to write the block type. With an active
  7942. region, wrap the region in the block. Otherwise, insert an empty
  7943. block.
  7944. When foo is written as FOO, upcase the #+BEGIN/END as well."
  7945. (interactive
  7946. (list (pcase (org--insert-structure-template-mks)
  7947. (`("\t" . ,_) (read-string "Structure type: "))
  7948. (`(,_ ,choice . ,_) choice))))
  7949. (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
  7950. (region? (use-region-p))
  7951. (region-start (and region? (region-beginning)))
  7952. (region-end (and region? (copy-marker (region-end))))
  7953. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  7954. (verbatim? (string-match-p
  7955. (concat "\\`" (regexp-opt '("example" "export" "src")))
  7956. type))
  7957. (upcase? (string= (car (split-string type))
  7958. (upcase (car (split-string type))))))
  7959. (when region? (goto-char region-start))
  7960. (let ((column (current-indentation)))
  7961. (if (save-excursion (skip-chars-backward " \t") (bolp))
  7962. (beginning-of-line)
  7963. (insert "\n"))
  7964. (save-excursion
  7965. (indent-to column)
  7966. (insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
  7967. (when region?
  7968. (when verbatim? (org-escape-code-in-region (point) region-end))
  7969. (goto-char region-end)
  7970. ;; Ignore empty lines at the end of the region.
  7971. (skip-chars-backward " \r\t\n")
  7972. (end-of-line))
  7973. (unless (bolp) (insert "\n"))
  7974. (indent-to column)
  7975. (insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
  7976. (if (looking-at "[ \t]*$") (replace-match "")
  7977. (insert "\n"))
  7978. (when (and (eobp) (not (bolp))) (insert "\n")))
  7979. (if extended? (end-of-line)
  7980. (forward-line)
  7981. (skip-chars-forward " \t")))))
  7982. ;;;; TODO, DEADLINE, Comments
  7983. (defun org-toggle-comment ()
  7984. "Change the COMMENT state of an entry."
  7985. (interactive)
  7986. (save-excursion
  7987. (org-back-to-heading)
  7988. (let ((case-fold-search nil))
  7989. (looking-at org-complex-heading-regexp))
  7990. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7991. (skip-chars-forward " \t")
  7992. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  7993. (if (org-in-commented-heading-p t)
  7994. (delete-region (point)
  7995. (progn (search-forward " " (line-end-position) 'move)
  7996. (skip-chars-forward " \t")
  7997. (point)))
  7998. (insert org-comment-string)
  7999. (unless (eolp) (insert " ")))))
  8000. (defvar org-last-todo-state-is-todo nil
  8001. "This is non-nil when the last TODO state change led to a TODO state.
  8002. If the last change removed the TODO tag or switched to DONE, then
  8003. this is nil.")
  8004. (defvar org-todo-setup-filter-hook nil
  8005. "Hook for functions that pre-filter todo specs.
  8006. Each function takes a todo spec and returns either nil or the spec
  8007. transformed into canonical form." )
  8008. (defvar org-todo-get-default-hook nil
  8009. "Hook for functions that get a default item for todo.
  8010. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8011. nil or a string to be used for the todo mark." )
  8012. (defvar org-agenda-headline-snapshot-before-repeat)
  8013. (defun org-current-effective-time ()
  8014. "Return current time adjusted for `org-extend-today-until' variable."
  8015. (let* ((ct (org-current-time))
  8016. (dct (decode-time ct))
  8017. (ct1
  8018. (cond
  8019. (org-use-last-clock-out-time-as-effective-time
  8020. (or (org-clock-get-last-clock-out-time) ct))
  8021. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8022. (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8023. (t ct))))
  8024. ct1))
  8025. (defun org-todo-yesterday (&optional arg)
  8026. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8027. (interactive "P")
  8028. (if (eq major-mode 'org-agenda-mode)
  8029. (org-agenda-todo-yesterday arg)
  8030. (let* ((org-use-effective-time t)
  8031. (hour (nth 2 (decode-time (org-current-time))))
  8032. (org-extend-today-until (1+ hour)))
  8033. (org-todo arg))))
  8034. (defvar org-block-entry-blocking ""
  8035. "First entry preventing the TODO state change.")
  8036. (defun org-cancel-repeater ()
  8037. "Cancel a repeater by setting its numeric value to zero."
  8038. (interactive)
  8039. (save-excursion
  8040. (org-back-to-heading t)
  8041. (let ((bound1 (point))
  8042. (bound0 (save-excursion (outline-next-heading) (point))))
  8043. (when (and (re-search-forward
  8044. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8045. org-deadline-time-regexp "\\)\\|\\("
  8046. org-ts-regexp "\\)")
  8047. bound0 t)
  8048. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8049. bound1 t))
  8050. (replace-match "0" t nil nil 1)))))
  8051. (defvar org-state)
  8052. (defvar org-blocked-by-checkboxes)
  8053. (defun org-todo (&optional arg)
  8054. "Change the TODO state of an item.
  8055. The state of an item is given by a keyword at the start of the heading,
  8056. like
  8057. *** TODO Write paper
  8058. *** DONE Call mom
  8059. The different keywords are specified in the variable `org-todo-keywords'.
  8060. By default the available states are \"TODO\" and \"DONE\". So, for this
  8061. example: when the item starts with TODO, it is changed to DONE.
  8062. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8063. DONE are present, add TODO at the beginning of the heading.
  8064. You can set up single-character keys to fast-select the new state. See the
  8065. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8066. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8067. and take a
  8068. logging note.
  8069. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8070. next set of TODO \
  8071. keywords (nextset).
  8072. Another way to achieve this is `S-C-<right>'.
  8073. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8074. prefix, circumvent any state blocking.
  8075. With numeric prefix arg, switch to the Nth state.
  8076. With a numeric prefix arg of 0, inhibit note taking for the change.
  8077. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8078. When called through ELisp, arg is also interpreted in the following way:
  8079. `none' -> empty state
  8080. \"\" -> switch to empty state
  8081. `done' -> switch to DONE
  8082. `nextset' -> switch to the next set of keywords
  8083. `previousset' -> switch to the previous set of keywords
  8084. \"WAITING\" -> switch to the specified keyword, but only if it
  8085. really is a member of `org-todo-keywords'."
  8086. (interactive "P")
  8087. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8088. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8089. 'region-start-level 'region))
  8090. org-loop-over-headlines-in-active-region)
  8091. (org-map-entries
  8092. (lambda () (org-todo arg))
  8093. nil cl
  8094. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8095. (when (equal arg '(16)) (setq arg 'nextset))
  8096. (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
  8097. (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
  8098. (let ((org-blocker-hook org-blocker-hook)
  8099. commentp
  8100. case-fold-search)
  8101. (when (equal arg '(64))
  8102. (setq arg nil org-blocker-hook nil))
  8103. (when (and org-blocker-hook
  8104. (or org-inhibit-blocking
  8105. (org-entry-get nil "NOBLOCKING")))
  8106. (setq org-blocker-hook nil))
  8107. (save-excursion
  8108. (catch 'exit
  8109. (org-back-to-heading t)
  8110. (when (org-in-commented-heading-p t)
  8111. (org-toggle-comment)
  8112. (setq commentp t))
  8113. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8114. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8115. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8116. (let* ((match-data (match-data))
  8117. (startpos (copy-marker (line-beginning-position)))
  8118. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8119. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8120. (org-log-done org-log-done)
  8121. (org-log-repeat org-log-repeat)
  8122. (org-todo-log-states org-todo-log-states)
  8123. (org-inhibit-logging
  8124. (if (equal arg 0)
  8125. (progn (setq arg nil) 'note) org-inhibit-logging))
  8126. (this (match-string 1))
  8127. (hl-pos (match-beginning 0))
  8128. (head (org-get-todo-sequence-head this))
  8129. (ass (assoc head org-todo-kwd-alist))
  8130. (interpret (nth 1 ass))
  8131. (done-word (nth 3 ass))
  8132. (final-done-word (nth 4 ass))
  8133. (org-last-state (or this ""))
  8134. (completion-ignore-case t)
  8135. (member (member this org-todo-keywords-1))
  8136. (tail (cdr member))
  8137. (org-state (cond
  8138. ((eq arg 'right)
  8139. ;; Next state
  8140. (if this
  8141. (if tail (car tail) nil)
  8142. (car org-todo-keywords-1)))
  8143. ((eq arg 'left)
  8144. ;; Previous state
  8145. (unless (equal member org-todo-keywords-1)
  8146. (if this
  8147. (nth (- (length org-todo-keywords-1)
  8148. (length tail) 2)
  8149. org-todo-keywords-1)
  8150. (org-last org-todo-keywords-1))))
  8151. (arg
  8152. ;; User or caller requests a specific state.
  8153. (cond
  8154. ((equal arg "") nil)
  8155. ((eq arg 'none) nil)
  8156. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8157. ((eq arg 'nextset)
  8158. (or (car (cdr (member head org-todo-heads)))
  8159. (car org-todo-heads)))
  8160. ((eq arg 'previousset)
  8161. (let ((org-todo-heads (reverse org-todo-heads)))
  8162. (or (car (cdr (member head org-todo-heads)))
  8163. (car org-todo-heads))))
  8164. ((car (member arg org-todo-keywords-1)))
  8165. ((stringp arg)
  8166. (user-error "State `%s' not valid in this file" arg))
  8167. ((nth (1- (prefix-numeric-value arg))
  8168. org-todo-keywords-1))))
  8169. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8170. ;; Use fast selection.
  8171. (org-fast-todo-selection this))
  8172. ((null member) (or head (car org-todo-keywords-1)))
  8173. ((equal this final-done-word) nil) ;-> make empty
  8174. ((null tail) nil) ;-> first entry
  8175. ((memq interpret '(type priority))
  8176. (if (eq this-command last-command)
  8177. (car tail)
  8178. (if (> (length tail) 0)
  8179. (or done-word (car org-done-keywords))
  8180. nil)))
  8181. (t
  8182. (car tail))))
  8183. (org-state (or
  8184. (run-hook-with-args-until-success
  8185. 'org-todo-get-default-hook org-state org-last-state)
  8186. org-state))
  8187. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8188. (change-plist (list :type 'todo-state-change :from this :to org-state
  8189. :position startpos))
  8190. dolog now-done-p)
  8191. (when org-blocker-hook
  8192. (let (org-blocked-by-checkboxes block-reason)
  8193. (setq org-last-todo-state-is-todo
  8194. (not (member this org-done-keywords)))
  8195. (unless (save-excursion
  8196. (save-match-data
  8197. (org-with-wide-buffer
  8198. (run-hook-with-args-until-failure
  8199. 'org-blocker-hook change-plist))))
  8200. (setq block-reason (if org-blocked-by-checkboxes
  8201. "contained checkboxes"
  8202. (format "\"%s\"" org-block-entry-blocking)))
  8203. (if (called-interactively-p 'interactive)
  8204. (user-error "TODO state change from %s to %s blocked (by %s)"
  8205. this org-state block-reason)
  8206. ;; Fail silently.
  8207. (message "TODO state change from %s to %s blocked (by %s)"
  8208. this org-state block-reason)
  8209. (throw 'exit nil)))))
  8210. (store-match-data match-data)
  8211. (org-fold-core-ignore-modifications
  8212. (goto-char (match-beginning 0))
  8213. (replace-match "")
  8214. ;; We need to use `insert-before-markers-and-inherit'
  8215. ;; because: (1) We want to preserve the folding state
  8216. ;; text properties; (2) We do not want to make point
  8217. ;; move before new todo state when inserting a new todo
  8218. ;; into an empty heading. In (2), the above
  8219. ;; `save-excursion' is relying on markers saved before.
  8220. (insert-before-markers-and-inherit next)
  8221. (unless (org-invisible-p (line-beginning-position))
  8222. (org-fold-region (line-beginning-position)
  8223. (line-end-position)
  8224. nil)))
  8225. (cond ((and org-state (equal this org-state))
  8226. (message "TODO state was already %s" (org-trim next)))
  8227. ((not (pos-visible-in-window-p hl-pos))
  8228. (message "TODO state changed to %s" (org-trim next))))
  8229. (unless head
  8230. (setq head (org-get-todo-sequence-head org-state)
  8231. ass (assoc head org-todo-kwd-alist)
  8232. interpret (nth 1 ass)
  8233. done-word (nth 3 ass)
  8234. final-done-word (nth 4 ass)))
  8235. (when (memq arg '(nextset previousset))
  8236. (message "Keyword-Set %d/%d: %s"
  8237. (- (length org-todo-sets) -1
  8238. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8239. (length org-todo-sets)
  8240. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8241. (setq org-last-todo-state-is-todo
  8242. (not (member org-state org-done-keywords)))
  8243. (setq now-done-p (and (member org-state org-done-keywords)
  8244. (not (member this org-done-keywords))))
  8245. (and logging (org-local-logging logging))
  8246. (when (or (and (or org-todo-log-states org-log-done)
  8247. (not (eq org-inhibit-logging t))
  8248. (not (memq arg '(nextset previousset))))
  8249. force-log)
  8250. ;; We need to look at recording a time and note.
  8251. (setq dolog (or (if force-log 'note)
  8252. (nth 1 (assoc org-state org-todo-log-states))
  8253. (nth 2 (assoc this org-todo-log-states))))
  8254. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8255. (setq dolog 'time))
  8256. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8257. (and org-state
  8258. (member org-state org-not-done-keywords)
  8259. (not (member this org-not-done-keywords))))
  8260. ;; This is now a todo state and was not one before
  8261. ;; If there was a CLOSED time stamp, get rid of it.
  8262. (org-add-planning-info nil nil 'closed))
  8263. (when (and now-done-p org-log-done)
  8264. ;; It is now done, and it was not done before.
  8265. (org-add-planning-info 'closed (org-current-effective-time))
  8266. (when (and (not dolog) (eq 'note org-log-done))
  8267. (org-add-log-setup 'done org-state this 'note)))
  8268. (when (and org-state dolog)
  8269. ;; This is a non-nil state, and we need to log it.
  8270. (org-add-log-setup 'state org-state this dolog)))
  8271. ;; Fixup tag positioning.
  8272. (org-todo-trigger-tag-changes org-state)
  8273. (when org-auto-align-tags (org-align-tags))
  8274. (when org-provide-todo-statistics
  8275. (org-update-parent-todo-statistics))
  8276. (when (bound-and-true-p org-clock-out-when-done)
  8277. (org-clock-out-if-current))
  8278. (run-hooks 'org-after-todo-state-change-hook)
  8279. (when (and arg (not (member org-state org-done-keywords)))
  8280. (setq head (org-get-todo-sequence-head org-state)))
  8281. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8282. ;; Do we need to trigger a repeat?
  8283. (when now-done-p
  8284. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8285. ;; This is for the agenda, take a snapshot of the headline.
  8286. (save-match-data
  8287. (setq org-agenda-headline-snapshot-before-repeat
  8288. (org-get-heading))))
  8289. (org-auto-repeat-maybe org-state))
  8290. ;; Fixup cursor location if close to the keyword.
  8291. (when (and (outline-on-heading-p)
  8292. (not (bolp))
  8293. (save-excursion (beginning-of-line 1)
  8294. (looking-at org-todo-line-regexp))
  8295. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8296. (goto-char (or (match-end 2) (match-end 1)))
  8297. (and (looking-at " ")
  8298. (not (looking-at " *:"))
  8299. (just-one-space)))
  8300. (when org-trigger-hook
  8301. (save-excursion
  8302. (run-hook-with-args 'org-trigger-hook change-plist)))
  8303. (when commentp (org-toggle-comment))))))))
  8304. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8305. "Block turning an entry into a TODO, using the hierarchy.
  8306. This checks whether the current task should be blocked from state
  8307. changes. Such blocking occurs when:
  8308. 1. The task has children which are not all in a completed state.
  8309. 2. A task has a parent with the property :ORDERED:, and there
  8310. are siblings prior to the current task with incomplete
  8311. status.
  8312. 3. The parent of the task is blocked because it has siblings that should
  8313. be done first, or is child of a block grandparent TODO entry."
  8314. (if (not org-enforce-todo-dependencies)
  8315. t ; if locally turned off don't block
  8316. (catch 'dont-block
  8317. ;; If this is not a todo state change, or if this entry is already DONE,
  8318. ;; do not block
  8319. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8320. (member (plist-get change-plist :from)
  8321. (cons 'done org-done-keywords))
  8322. (member (plist-get change-plist :to)
  8323. (cons 'todo org-not-done-keywords))
  8324. (not (plist-get change-plist :to)))
  8325. (throw 'dont-block t))
  8326. ;; If this task has children, and any are undone, it's blocked
  8327. (save-excursion
  8328. (org-back-to-heading t)
  8329. (let ((this-level (funcall outline-level)))
  8330. (outline-next-heading)
  8331. (let ((child-level (funcall outline-level)))
  8332. (while (and (not (eobp))
  8333. (> child-level this-level))
  8334. ;; this todo has children, check whether they are all
  8335. ;; completed
  8336. (when (and (not (org-entry-is-done-p))
  8337. (org-entry-is-todo-p))
  8338. (setq org-block-entry-blocking (org-get-heading))
  8339. (throw 'dont-block nil))
  8340. (outline-next-heading)
  8341. (setq child-level (funcall outline-level))))))
  8342. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8343. ;; any previous siblings are undone, it's blocked
  8344. (save-excursion
  8345. (org-back-to-heading t)
  8346. (let* ((pos (point))
  8347. (parent-pos (and (org-up-heading-safe) (point)))
  8348. (case-fold-search nil))
  8349. (unless parent-pos (throw 'dont-block t)) ; no parent
  8350. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8351. (forward-line 1)
  8352. (re-search-forward org-not-done-heading-regexp pos t))
  8353. (setq org-block-entry-blocking (match-string 0))
  8354. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8355. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8356. (while t
  8357. (goto-char parent-pos)
  8358. (unless (looking-at org-not-done-heading-regexp)
  8359. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8360. (setq pos (point))
  8361. (setq parent-pos (and (org-up-heading-safe) (point)))
  8362. (unless parent-pos (throw 'dont-block t)) ; no parent
  8363. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8364. (forward-line 1)
  8365. (re-search-forward org-not-done-heading-regexp pos t)
  8366. (setq org-block-entry-blocking (org-get-heading)))
  8367. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8368. (defcustom org-track-ordered-property-with-tag nil
  8369. "Should the ORDERED property also be shown as a tag?
  8370. The ORDERED property decides if an entry should require subtasks to be
  8371. completed in sequence. Since a property is not very visible, setting
  8372. this option means that toggling the ORDERED property with the command
  8373. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8374. not relevant for the behavior, but it makes things more visible.
  8375. Note that toggling the tag with tags commands will not change the property
  8376. and therefore not influence behavior!
  8377. This can be t, meaning the tag ORDERED should be used. It can also be a
  8378. string to select a different tag for this task."
  8379. :group 'org-todo
  8380. :type '(choice
  8381. (const :tag "No tracking" nil)
  8382. (const :tag "Track with ORDERED tag" t)
  8383. (string :tag "Use other tag")))
  8384. (defun org-toggle-ordered-property ()
  8385. "Toggle the ORDERED property of the current entry.
  8386. For better visibility, you can track the value of this property with a tag.
  8387. See variable `org-track-ordered-property-with-tag'."
  8388. (interactive)
  8389. (let* ((t1 org-track-ordered-property-with-tag)
  8390. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8391. (save-excursion
  8392. (org-back-to-heading)
  8393. (if (org-entry-get nil "ORDERED")
  8394. (progn
  8395. (org-delete-property "ORDERED")
  8396. (and tag (org-toggle-tag tag 'off))
  8397. (message "Subtasks can be completed in arbitrary order"))
  8398. (org-entry-put nil "ORDERED" "t")
  8399. (and tag (org-toggle-tag tag 'on))
  8400. (message "Subtasks must be completed in sequence")))))
  8401. (defun org-block-todo-from-checkboxes (change-plist)
  8402. "Block turning an entry into a TODO, using checkboxes.
  8403. This checks whether the current task should be blocked from state
  8404. changes because there are unchecked boxes in this entry."
  8405. (if (not org-enforce-todo-checkbox-dependencies)
  8406. t ; if locally turned off don't block
  8407. (catch 'dont-block
  8408. ;; If this is not a todo state change, or if this entry is already DONE,
  8409. ;; do not block
  8410. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8411. (member (plist-get change-plist :from)
  8412. (cons 'done org-done-keywords))
  8413. (member (plist-get change-plist :to)
  8414. (cons 'todo org-not-done-keywords))
  8415. (not (plist-get change-plist :to)))
  8416. (throw 'dont-block t))
  8417. ;; If this task has checkboxes that are not checked, it's blocked
  8418. (save-excursion
  8419. (org-back-to-heading t)
  8420. (let ((beg (point)) end)
  8421. (outline-next-heading)
  8422. (setq end (point))
  8423. (goto-char beg)
  8424. (when (org-list-search-forward
  8425. (concat (org-item-beginning-re)
  8426. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8427. "\\[[- ]\\]")
  8428. end t)
  8429. (when (boundp 'org-blocked-by-checkboxes)
  8430. (setq org-blocked-by-checkboxes t))
  8431. (throw 'dont-block nil))))
  8432. t))) ; do not block
  8433. (defun org-entry-blocked-p ()
  8434. "Non-nil if entry at point is blocked."
  8435. (and (not (org-entry-get nil "NOBLOCKING"))
  8436. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8437. (not (run-hook-with-args-until-failure
  8438. 'org-blocker-hook
  8439. (list :type 'todo-state-change
  8440. :position (point)
  8441. :from 'todo
  8442. :to 'done)))))
  8443. (defun org-update-statistics-cookies (all)
  8444. "Update the statistics cookie, either from TODO or from checkboxes.
  8445. This should be called with the cursor in a line with a statistics
  8446. cookie. When called with a \\[universal-argument] prefix, update
  8447. all statistics cookies in the buffer."
  8448. (interactive "P")
  8449. (if all
  8450. (progn
  8451. (org-update-checkbox-count 'all)
  8452. (org-map-region 'org-update-parent-todo-statistics
  8453. (point-min) (point-max)))
  8454. (if (not (org-at-heading-p))
  8455. (org-update-checkbox-count)
  8456. (let ((pos (point-marker))
  8457. end l1 l2)
  8458. (ignore-errors (org-back-to-heading t))
  8459. (if (not (org-at-heading-p))
  8460. (org-update-checkbox-count)
  8461. (setq l1 (org-outline-level))
  8462. (setq end
  8463. (save-excursion
  8464. (outline-next-heading)
  8465. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8466. (point)))
  8467. (if (and (save-excursion
  8468. (re-search-forward
  8469. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8470. (not (save-excursion
  8471. (re-search-forward
  8472. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8473. (org-update-checkbox-count)
  8474. (if (and l2 (> l2 l1))
  8475. (progn
  8476. (goto-char end)
  8477. (org-update-parent-todo-statistics))
  8478. (goto-char pos)
  8479. (beginning-of-line 1)
  8480. (while (re-search-forward
  8481. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8482. (point-at-eol) t)
  8483. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8484. (goto-char pos)
  8485. (move-marker pos nil)))))
  8486. (defvar org-entry-property-inherited-from) ;; defined below
  8487. (defun org-update-parent-todo-statistics ()
  8488. "Update any statistics cookie in the parent of the current headline.
  8489. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8490. the entire subtree and this will travel up the hierarchy and update
  8491. statistics everywhere."
  8492. (let* ((prop (save-excursion
  8493. (org-up-heading-safe)
  8494. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8495. (recursive (or (not org-hierarchical-todo-statistics)
  8496. (and prop (string-match "\\<recursive\\>" prop))))
  8497. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8498. 0))
  8499. (first t)
  8500. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8501. level ltoggle l1 new ndel
  8502. (cnt-all 0) (cnt-done 0) is-percent kwd
  8503. checkbox-beg cookie-present)
  8504. (catch 'exit
  8505. (save-excursion
  8506. (beginning-of-line 1)
  8507. (setq ltoggle (funcall outline-level))
  8508. ;; Three situations are to consider:
  8509. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8510. ;; to the top-level ancestor on the headline;
  8511. ;; 2. If parent has "recursive" property, repeat up to the
  8512. ;; headline setting that property, taking inheritance into
  8513. ;; account;
  8514. ;; 3. Else, move up to direct parent and proceed only once.
  8515. (while (and (setq level (org-up-heading-safe))
  8516. (or recursive first)
  8517. (>= (point) lim))
  8518. (setq first nil cookie-present nil)
  8519. (unless (and level
  8520. (not (string-match
  8521. "\\<checkbox\\>"
  8522. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8523. "")))))
  8524. (throw 'exit nil))
  8525. (while (re-search-forward box-re (point-at-eol) t)
  8526. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8527. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8528. (save-match-data
  8529. (unless (outline-next-heading) (throw 'exit nil))
  8530. (while (and (looking-at org-complex-heading-regexp)
  8531. (> (setq l1 (length (match-string 1))) level))
  8532. (setq kwd (and (or recursive (= l1 ltoggle))
  8533. (match-string 2)))
  8534. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8535. (and (eq org-provide-todo-statistics t)
  8536. (or (member kwd org-done-keywords)))
  8537. (and (listp org-provide-todo-statistics)
  8538. (stringp (car org-provide-todo-statistics))
  8539. (or (member kwd org-provide-todo-statistics)
  8540. (member kwd org-done-keywords)))
  8541. (and (listp org-provide-todo-statistics)
  8542. (listp (car org-provide-todo-statistics))
  8543. (or (member kwd (car org-provide-todo-statistics))
  8544. (and (member kwd org-done-keywords)
  8545. (member kwd (cadr org-provide-todo-statistics))))))
  8546. (setq cnt-all (1+ cnt-all))
  8547. (and (eq org-provide-todo-statistics t)
  8548. kwd
  8549. (setq cnt-all (1+ cnt-all))))
  8550. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8551. (member kwd org-done-keywords))
  8552. (and (listp org-provide-todo-statistics)
  8553. (listp (car org-provide-todo-statistics))
  8554. (member kwd org-done-keywords)
  8555. (member kwd (cadr org-provide-todo-statistics)))
  8556. (and (listp org-provide-todo-statistics)
  8557. (stringp (car org-provide-todo-statistics))
  8558. (member kwd org-done-keywords)))
  8559. (setq cnt-done (1+ cnt-done)))
  8560. (outline-next-heading)))
  8561. (setq new
  8562. (if is-percent
  8563. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8564. (max 1 cnt-all)))
  8565. (format "[%d/%d]" cnt-done cnt-all))
  8566. ndel (- (match-end 0) checkbox-beg))
  8567. (goto-char checkbox-beg)
  8568. (insert new)
  8569. (delete-region (point) (+ (point) ndel))
  8570. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8571. (when cookie-present
  8572. (run-hook-with-args 'org-after-todo-statistics-hook
  8573. cnt-done (- cnt-all cnt-done))))))
  8574. (run-hooks 'org-todo-statistics-hook)))
  8575. (defvar org-after-todo-statistics-hook nil
  8576. "Hook that is called after a TODO statistics cookie has been updated.
  8577. Each function is called with two arguments: the number of not-done entries
  8578. and the number of done entries.
  8579. For example, the following function, when added to this hook, will switch
  8580. an entry to DONE when all children are done, and back to TODO when new
  8581. entries are set to a TODO status. Note that this hook is only called
  8582. when there is a statistics cookie in the headline!
  8583. (defun org-summary-todo (n-done n-not-done)
  8584. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8585. (let (org-log-done org-log-states) ; turn off logging
  8586. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8587. (defvar org-todo-statistics-hook nil
  8588. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8589. This hook runs even if there is no statistics cookie present, in which case
  8590. `org-after-todo-statistics-hook' would not run.")
  8591. (defun org-todo-trigger-tag-changes (state)
  8592. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8593. (let ((l org-todo-state-tags-triggers)
  8594. changes)
  8595. (when (or (not state) (equal state ""))
  8596. (setq changes (append changes (cdr (assoc "" l)))))
  8597. (when (and (stringp state) (> (length state) 0))
  8598. (setq changes (append changes (cdr (assoc state l)))))
  8599. (when (member state org-not-done-keywords)
  8600. (setq changes (append changes (cdr (assq 'todo l)))))
  8601. (when (member state org-done-keywords)
  8602. (setq changes (append changes (cdr (assq 'done l)))))
  8603. (dolist (c changes)
  8604. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8605. (defun org-local-logging (value)
  8606. "Get logging settings from a property VALUE."
  8607. ;; Directly set the variables, they are already local.
  8608. (setq org-log-done nil
  8609. org-log-repeat nil
  8610. org-todo-log-states nil)
  8611. (dolist (w (split-string value))
  8612. (let (a)
  8613. (cond
  8614. ((setq a (assoc w org-startup-options))
  8615. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8616. (set (nth 1 a) (nth 2 a))))
  8617. ((setq a (org-extract-log-state-settings w))
  8618. (and (member (car a) org-todo-keywords-1)
  8619. (push a org-todo-log-states)))))))
  8620. (defun org-get-todo-sequence-head (kwd)
  8621. "Return the head of the TODO sequence to which KWD belongs.
  8622. If KWD is not set, check if there is a text property remembering the
  8623. right sequence."
  8624. (let (p)
  8625. (cond
  8626. ((not kwd)
  8627. (or (get-text-property (point-at-bol) 'org-todo-head)
  8628. (progn
  8629. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8630. nil (point-at-eol)))
  8631. (get-text-property p 'org-todo-head))))
  8632. ((not (member kwd org-todo-keywords-1))
  8633. (car org-todo-keywords-1))
  8634. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8635. (defun org-fast-todo-selection (&optional current-state)
  8636. "Fast TODO keyword selection with single keys.
  8637. Returns the new TODO keyword, or nil if no state change should occur.
  8638. When CURRENT-STATE is given and selection letters are not unique globally,
  8639. prefer a state in the current sequence over on in another sequence."
  8640. (let* ((fulltable org-todo-key-alist)
  8641. (head (org-get-todo-sequence-head current-state))
  8642. (done-keywords org-done-keywords) ;; needed for the faces.
  8643. (maxlen (apply 'max (mapcar
  8644. (lambda (x)
  8645. (if (stringp (car x)) (string-width (car x)) 0))
  8646. fulltable)))
  8647. (expert (equal org-use-fast-todo-selection 'expert))
  8648. (prompt "")
  8649. (fwidth (+ maxlen 3 1 3))
  8650. (ncol (/ (- (window-width) 4) fwidth))
  8651. tg cnt e c tbl subtable
  8652. groups ingroup in-current-sequence)
  8653. (save-excursion
  8654. (save-window-excursion
  8655. (if expert
  8656. (set-buffer (get-buffer-create " *Org todo*"))
  8657. (delete-other-windows)
  8658. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8659. (org-switch-to-buffer-other-window " *Org todo*"))
  8660. (erase-buffer)
  8661. (setq-local org-done-keywords done-keywords)
  8662. (setq tbl fulltable cnt 0)
  8663. (while (setq e (pop tbl))
  8664. (cond
  8665. ((equal e '(:startgroup))
  8666. (push '() groups) (setq ingroup t)
  8667. (unless (= cnt 0)
  8668. (setq cnt 0)
  8669. (insert "\n"))
  8670. (setq prompt (concat prompt "{"))
  8671. (insert "{ "))
  8672. ((equal e '(:endgroup))
  8673. (setq ingroup nil cnt 0 in-current-sequence nil)
  8674. (setq prompt (concat prompt "}"))
  8675. (insert "}\n"))
  8676. ((equal e '(:newline))
  8677. (unless (= cnt 0)
  8678. (setq cnt 0)
  8679. (insert "\n")
  8680. (setq e (car tbl))
  8681. (while (equal (car tbl) '(:newline))
  8682. (insert "\n")
  8683. (setq tbl (cdr tbl)))))
  8684. (t
  8685. (setq tg (car e) c (cdr e))
  8686. (if (equal tg head) (setq in-current-sequence t))
  8687. (when ingroup (push tg (car groups)))
  8688. (when in-current-sequence (push e subtable))
  8689. (setq tg (org-add-props tg nil 'face
  8690. (org-get-todo-face tg)))
  8691. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8692. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8693. (insert "[" c "] " tg (make-string
  8694. (- fwidth 4 (length tg)) ?\ ))
  8695. (when (and (= (setq cnt (1+ cnt)) ncol)
  8696. ;; Avoid lines with just a closing delimiter.
  8697. (not (equal (car tbl) '(:endgroup))))
  8698. (insert "\n")
  8699. (when ingroup (insert " "))
  8700. (setq cnt 0)))))
  8701. (insert "\n")
  8702. (goto-char (point-min))
  8703. (unless expert (org-fit-window-to-buffer))
  8704. (message (concat "[a-z..]:Set [SPC]:clear"
  8705. (if expert (concat "\n" prompt) "")))
  8706. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8707. (setq subtable (nreverse subtable))
  8708. (cond
  8709. ((or (= c ?\C-g)
  8710. (and (= c ?q) (not (rassoc c fulltable))))
  8711. (setq quit-flag t))
  8712. ((= c ?\ ) nil)
  8713. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8714. tg (car e))
  8715. tg)
  8716. (t (setq quit-flag t)))))))
  8717. (defun org-entry-is-todo-p ()
  8718. (member (org-get-todo-state) org-not-done-keywords))
  8719. (defun org-entry-is-done-p ()
  8720. (member (org-get-todo-state) org-done-keywords))
  8721. (defun org-get-todo-state ()
  8722. "Return the TODO keyword of the current subtree."
  8723. (save-excursion
  8724. (org-back-to-heading t)
  8725. (and (let ((case-fold-search nil))
  8726. (looking-at org-todo-line-regexp))
  8727. (match-end 2)
  8728. (match-string 2))))
  8729. (defun org-at-date-range-p (&optional inactive-ok)
  8730. "Non-nil if point is inside a date range.
  8731. When optional argument INACTIVE-OK is non-nil, also consider
  8732. inactive time ranges.
  8733. When this function returns a non-nil value, match data is set
  8734. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8735. on INACTIVE-OK."
  8736. (interactive)
  8737. (save-excursion
  8738. (catch 'exit
  8739. (let ((pos (point)))
  8740. (skip-chars-backward "^[<\r\n")
  8741. (skip-chars-backward "<[")
  8742. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8743. (>= (match-end 0) pos)
  8744. (throw 'exit t))
  8745. (skip-chars-backward "^<[\r\n")
  8746. (skip-chars-backward "<[")
  8747. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8748. (>= (match-end 0) pos)
  8749. (throw 'exit t)))
  8750. nil)))
  8751. (defun org-get-repeat (&optional timestamp)
  8752. "Check if there is a time-stamp with repeater in this entry.
  8753. Return the repeater, as a string, or nil. Also return nil when
  8754. this function is called before first heading.
  8755. When optional argument TIMESTAMP is a string, extract the
  8756. repeater from there instead."
  8757. (save-match-data
  8758. (cond
  8759. (timestamp
  8760. (and (string-match org-repeat-re timestamp)
  8761. (match-string-no-properties 1 timestamp)))
  8762. ((org-before-first-heading-p) nil)
  8763. (t
  8764. (save-excursion
  8765. (org-back-to-heading t)
  8766. (let ((end (org-entry-end-position)))
  8767. (catch :repeat
  8768. (while (re-search-forward org-repeat-re end t)
  8769. (when (save-match-data (org-at-timestamp-p 'agenda))
  8770. (throw :repeat (match-string-no-properties 1)))))))))))
  8771. (defvar org-last-changed-timestamp)
  8772. (defvar org-last-inserted-timestamp)
  8773. (defvar org-log-post-message)
  8774. (defvar org-log-note-purpose)
  8775. (defvar org-log-note-how nil)
  8776. (defvar org-log-note-extra)
  8777. (defvar org-log-setup nil)
  8778. (defun org-auto-repeat-maybe (done-word)
  8779. "Check if the current headline contains a repeated time-stamp.
  8780. If yes, set TODO state back to what it was and change the base date
  8781. of repeating deadline/scheduled time stamps to new date.
  8782. This function is run automatically after each state change to a DONE state."
  8783. (let* ((repeat (org-get-repeat))
  8784. (aa (assoc org-last-state org-todo-kwd-alist))
  8785. (interpret (nth 1 aa))
  8786. (head (nth 2 aa))
  8787. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8788. (msg "Entry repeats: ")
  8789. (org-log-done nil)
  8790. (org-todo-log-states nil)
  8791. (end (copy-marker (org-entry-end-position))))
  8792. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8793. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8794. (let ((to-state
  8795. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8796. (and (stringp org-todo-repeat-to-state)
  8797. org-todo-repeat-to-state)
  8798. (and org-todo-repeat-to-state org-last-state))))
  8799. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8800. to-state)
  8801. ((eq interpret 'type) org-last-state)
  8802. (head)
  8803. (t 'none))))
  8804. (org-back-to-heading t)
  8805. (org-add-planning-info nil nil 'closed)
  8806. ;; When `org-log-repeat' is non-nil or entry contains
  8807. ;; a clock, set LAST_REPEAT property.
  8808. (when (or org-log-repeat
  8809. (catch :clock
  8810. (save-excursion
  8811. (while (re-search-forward org-clock-line-re end t)
  8812. (when (org-at-clock-log-p) (throw :clock t))))))
  8813. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8814. (org-time-stamp-format t t)
  8815. (org-current-effective-time))))
  8816. (when org-log-repeat
  8817. (if org-log-setup
  8818. ;; We are already setup for some record.
  8819. (when (eq org-log-repeat 'note)
  8820. ;; Make sure we take a note, not only a time stamp.
  8821. (setq org-log-note-how 'note))
  8822. ;; Set up for taking a record.
  8823. (org-add-log-setup 'state
  8824. (or done-word (car org-done-keywords))
  8825. org-last-state
  8826. org-log-repeat)))
  8827. ;; Time-stamps without a repeater are usually skipped. However,
  8828. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8829. ;; longer relevant.
  8830. (save-excursion
  8831. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8832. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8833. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8834. ;; Update every time-stamp with a repeater in the entry.
  8835. (let ((planning-re (regexp-opt
  8836. (list org-scheduled-string org-deadline-string))))
  8837. (while (re-search-forward org-repeat-re end t)
  8838. (let* ((ts (match-string 0))
  8839. (type (if (not (org-at-planning-p)) "Plain:"
  8840. (save-excursion
  8841. (re-search-backward
  8842. planning-re (line-beginning-position) t)
  8843. (match-string 0)))))
  8844. (when (and (org-at-timestamp-p 'agenda)
  8845. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8846. (let ((n (string-to-number (match-string 2 ts)))
  8847. (what (match-string 3 ts)))
  8848. (when (equal what "w") (setq n (* n 7) what "d"))
  8849. (when (and (equal what "h")
  8850. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8851. ts)))
  8852. (user-error
  8853. "Cannot repeat in %d hour(s) because no hour has been set"
  8854. n))
  8855. ;; Preparation, see if we need to modify the start
  8856. ;; date for the change.
  8857. (when (match-end 1)
  8858. (let ((time (save-match-data (org-time-string-to-time ts)))
  8859. (repeater-type (match-string 1 ts)))
  8860. (cond
  8861. ((equal "." repeater-type)
  8862. ;; Shift starting date to today, or now if
  8863. ;; repeater is by hours.
  8864. (if (equal what "h")
  8865. (org-timestamp-change
  8866. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8867. (org-timestamp-change
  8868. (- (org-today) (time-to-days time)) 'day)))
  8869. ((equal "+" repeater-type)
  8870. (let ((nshiftmax 10)
  8871. (nshift 0))
  8872. (while (or (= nshift 0)
  8873. (not (time-less-p nil time)))
  8874. (when (= nshiftmax (cl-incf nshift))
  8875. (or (y-or-n-p
  8876. (format "%d repeater intervals were not \
  8877. enough to shift date past today. Continue? "
  8878. nshift))
  8879. (user-error "Abort")))
  8880. (org-timestamp-change n (cdr (assoc what whata)))
  8881. (org-in-regexp org-ts-regexp3)
  8882. (setq ts (match-string 1))
  8883. (setq time
  8884. (save-match-data
  8885. (org-time-string-to-time ts)))))
  8886. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8887. ;; Rematch, so that we have everything in place
  8888. ;; for the real shift.
  8889. (org-in-regexp org-ts-regexp3)
  8890. (setq ts (match-string 1))
  8891. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8892. ts)))))
  8893. (save-excursion
  8894. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8895. (setq msg
  8896. (concat msg type " " org-last-changed-timestamp " ")))))))
  8897. (run-hooks 'org-todo-repeat-hook)
  8898. (setq org-log-post-message msg)
  8899. (message msg))))
  8900. (defun org-show-todo-tree (arg)
  8901. "Make a compact tree which shows all headlines marked with TODO.
  8902. The tree will show the lines where the regexp matches, and all higher
  8903. headlines above the match.
  8904. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8905. With a numeric prefix N, construct a sparse tree for the Nth element
  8906. of `org-todo-keywords-1'."
  8907. (interactive "P")
  8908. (let ((case-fold-search nil)
  8909. (kwd-re
  8910. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8911. ((equal arg '(4))
  8912. (let ((kwd
  8913. (completing-read "Keyword (or KWD1|KWD2|...): "
  8914. (mapcar #'list org-todo-keywords-1))))
  8915. (concat "\\("
  8916. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8917. "\\)\\>")))
  8918. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8919. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8920. org-todo-keywords-1)))
  8921. (t (user-error "Invalid prefix argument: %s" arg)))))
  8922. (message "%d TODO entries found"
  8923. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8924. (defun org--deadline-or-schedule (arg type time)
  8925. "Insert DEADLINE or SCHEDULE information in current entry.
  8926. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8927. `org-schedule' for information about ARG and TIME arguments."
  8928. (org-fold-core-ignore-modifications
  8929. (let* ((deadline? (eq type 'deadline))
  8930. (keyword (if deadline? org-deadline-string org-scheduled-string))
  8931. (log (if deadline? org-log-redeadline org-log-reschedule))
  8932. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  8933. (old-date-time (and old-date (org-time-string-to-time old-date)))
  8934. ;; Save repeater cookie from either TIME or current scheduled
  8935. ;; time stamp. We are going to insert it back at the end of
  8936. ;; the process.
  8937. (repeater (or (and (org-string-nw-p time)
  8938. ;; We use `org-ts-regexp-both' because we
  8939. ;; need to tell the difference between a
  8940. ;; real repeater and a time delta, e.g.
  8941. ;; "+2d".
  8942. (string-match-p org-ts-regexp-both time)
  8943. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8944. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8945. time)
  8946. (match-string 1 time))
  8947. (and (org-string-nw-p old-date)
  8948. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8949. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8950. old-date)
  8951. (match-string 1 old-date)))))
  8952. (pcase arg
  8953. (`(4)
  8954. (if (not old-date)
  8955. (message (if deadline? "Entry had no deadline to remove"
  8956. "Entry was not scheduled"))
  8957. (when (and old-date log)
  8958. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  8959. nil old-date log))
  8960. (org-remove-timestamp-with-keyword keyword)
  8961. (message (if deadline? "Entry no longer has a deadline."
  8962. "Entry is no longer scheduled."))))
  8963. (`(16)
  8964. (save-excursion
  8965. (org-back-to-heading t)
  8966. (let ((regexp (if deadline? org-deadline-time-regexp
  8967. org-scheduled-time-regexp)))
  8968. (if (not (re-search-forward regexp (line-end-position 2) t))
  8969. (user-error (if deadline? "No deadline information to update"
  8970. "No scheduled information to update"))
  8971. (let* ((rpl0 (match-string 1))
  8972. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  8973. (msg (if deadline? "Warn starting from" "Delay until")))
  8974. (replace-match
  8975. (concat keyword
  8976. " <" rpl
  8977. (format " -%dd"
  8978. (abs (- (time-to-days
  8979. (save-match-data
  8980. (org-read-date
  8981. nil t nil msg old-date-time)))
  8982. (time-to-days old-date-time))))
  8983. ">") t t))))))
  8984. (_
  8985. (org-add-planning-info type time 'closed)
  8986. (when (and old-date
  8987. log
  8988. (not (equal old-date org-last-inserted-timestamp)))
  8989. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  8990. org-last-inserted-timestamp
  8991. old-date
  8992. log))
  8993. (when repeater
  8994. (save-excursion
  8995. (org-back-to-heading t)
  8996. (when (re-search-forward
  8997. (concat keyword " " org-last-inserted-timestamp)
  8998. (line-end-position 2)
  8999. t)
  9000. (goto-char (1- (match-end 0)))
  9001. (insert-and-inherit " " repeater)
  9002. (setq org-last-inserted-timestamp
  9003. (concat (substring org-last-inserted-timestamp 0 -1)
  9004. " " repeater
  9005. (substring org-last-inserted-timestamp -1))))))
  9006. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9007. org-last-inserted-timestamp))))))
  9008. (defun org-deadline (arg &optional time)
  9009. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9010. When called interactively, this command pops up the Emacs calendar to let
  9011. the user select a date.
  9012. With one universal prefix argument, remove any deadline from the item.
  9013. With two universal prefix arguments, prompt for a warning delay.
  9014. With argument TIME, set the deadline at the corresponding date. TIME
  9015. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9016. (interactive "P")
  9017. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9018. (org-map-entries
  9019. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9020. nil
  9021. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9022. 'region-start-level
  9023. 'region)
  9024. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9025. (org--deadline-or-schedule arg 'deadline time)))
  9026. (defun org-schedule (arg &optional time)
  9027. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9028. When called interactively, this command pops up the Emacs calendar to let
  9029. the user select a date.
  9030. With one universal prefix argument, remove any scheduling date from the item.
  9031. With two universal prefix arguments, prompt for a delay cookie.
  9032. With argument TIME, scheduled at the corresponding date. TIME can
  9033. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9034. (interactive "P")
  9035. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9036. (org-map-entries
  9037. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9038. nil
  9039. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9040. 'region-start-level
  9041. 'region)
  9042. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9043. (org--deadline-or-schedule arg 'scheduled time)))
  9044. (defun org-get-scheduled-time (pom &optional inherit)
  9045. "Get the scheduled time as a time tuple, of a format suitable
  9046. for calling org-schedule with, or if there is no scheduling,
  9047. returns nil."
  9048. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9049. (when time
  9050. (org-time-string-to-time time))))
  9051. (defun org-get-deadline-time (pom &optional inherit)
  9052. "Get the deadline as a time tuple, of a format suitable for
  9053. calling org-deadline with, or if there is no scheduling, returns
  9054. nil."
  9055. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9056. (when time
  9057. (org-time-string-to-time time))))
  9058. (defun org-remove-timestamp-with-keyword (keyword)
  9059. "Remove all time stamps with KEYWORD in the current entry."
  9060. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9061. beg)
  9062. (save-excursion
  9063. (org-back-to-heading t)
  9064. (setq beg (point))
  9065. (outline-next-heading)
  9066. (while (re-search-backward re beg t)
  9067. (replace-match "")
  9068. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9069. (equal (char-before) ?\ ))
  9070. (backward-delete-char 1)
  9071. (when (string-match "^[ \t]*$" (buffer-substring
  9072. (point-at-bol) (point-at-eol)))
  9073. (delete-region (point-at-bol)
  9074. (min (point-max) (1+ (point-at-eol))))))))))
  9075. (defvar org-time-was-given) ; dynamically scoped parameter
  9076. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9077. (defun org-at-planning-p ()
  9078. "Non-nil when point is on a planning info line."
  9079. ;; This is as accurate and faster than `org-element-at-point' since
  9080. ;; planning info location is fixed in the section.
  9081. (or (let ((cached (org-element-at-point nil 'cached)))
  9082. (and cached
  9083. (eq 'planning (org-element-type cached))))
  9084. (org-with-wide-buffer
  9085. (beginning-of-line)
  9086. (and (looking-at-p org-planning-line-re)
  9087. (eq (point)
  9088. (ignore-errors
  9089. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9090. (org-back-to-heading t)
  9091. (org-with-limited-levels (org-back-to-heading t)))
  9092. (line-beginning-position 2)))))))
  9093. (defun org-add-planning-info (what &optional time &rest remove)
  9094. "Insert new timestamp with keyword in the planning line.
  9095. WHAT indicates what kind of time stamp to add. It is a symbol
  9096. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9097. the time to use. If none is given, the user is prompted for
  9098. a date. REMOVE indicates what kind of entries to remove. An old
  9099. WHAT entry will also be removed."
  9100. (org-fold-core-ignore-modifications
  9101. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9102. (when (and (memq what '(scheduled deadline))
  9103. (or (not time)
  9104. (and (stringp time)
  9105. (string-match "^[-+]+[0-9]" time))))
  9106. ;; Try to get a default date/time from existing timestamp
  9107. (save-excursion
  9108. (org-back-to-heading t)
  9109. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9110. (when (re-search-forward (if (eq what 'scheduled)
  9111. org-scheduled-time-regexp
  9112. org-deadline-time-regexp)
  9113. end t)
  9114. (setq ts (match-string 1)
  9115. default-time (org-time-string-to-time ts)
  9116. default-input (and ts (org-get-compact-tod ts)))))))
  9117. (when what
  9118. (setq time
  9119. (if (stringp time)
  9120. ;; This is a string (relative or absolute), set
  9121. ;; proper date.
  9122. (org-encode-time
  9123. (org-read-date-analyze
  9124. time default-time (decode-time default-time)))
  9125. ;; If necessary, get the time from the user
  9126. (or time (org-read-date nil 'to-time nil
  9127. (cl-case what
  9128. (deadline "DEADLINE")
  9129. (scheduled "SCHEDULED")
  9130. (otherwise nil))
  9131. default-time default-input)))))
  9132. (org-with-wide-buffer
  9133. (org-back-to-heading t)
  9134. (let ((planning? (save-excursion
  9135. (forward-line)
  9136. (looking-at-p org-planning-line-re))))
  9137. (cond
  9138. (planning?
  9139. (forward-line)
  9140. ;; Move to current indentation.
  9141. (skip-chars-forward " \t")
  9142. ;; Check if we have to remove something.
  9143. (dolist (type (if what (cons what remove) remove))
  9144. (save-excursion
  9145. (when (re-search-forward
  9146. (cl-case type
  9147. (closed org-closed-time-regexp)
  9148. (deadline org-deadline-time-regexp)
  9149. (scheduled org-scheduled-time-regexp)
  9150. (otherwise (error "Invalid planning type: %s" type)))
  9151. (line-end-position)
  9152. t)
  9153. ;; Delete until next keyword or end of line.
  9154. (delete-region
  9155. (match-beginning 0)
  9156. (if (re-search-forward org-keyword-time-not-clock-regexp
  9157. (line-end-position)
  9158. t)
  9159. (match-beginning 0)
  9160. (line-end-position))))))
  9161. ;; If there is nothing more to add and no more keyword is
  9162. ;; left, remove the line completely.
  9163. (if (and (looking-at-p "[ \t]*$") (not what))
  9164. (delete-region (line-end-position 0)
  9165. (line-end-position))
  9166. ;; If we removed last keyword, do not leave trailing white
  9167. ;; space at the end of line.
  9168. (let ((p (point)))
  9169. (save-excursion
  9170. (end-of-line)
  9171. (unless (= (skip-chars-backward " \t" p) 0)
  9172. (delete-region (point) (line-end-position)))))))
  9173. (what
  9174. (end-of-line)
  9175. (insert-and-inherit "\n")
  9176. (when org-adapt-indentation
  9177. (indent-to-column (1+ (org-outline-level)))))
  9178. (t nil)))
  9179. (when what
  9180. ;; Insert planning keyword.
  9181. (insert-and-inherit (cl-case what
  9182. (closed org-closed-string)
  9183. (deadline org-deadline-string)
  9184. (scheduled org-scheduled-string)
  9185. (otherwise (error "Invalid planning type: %s" what)))
  9186. " ")
  9187. ;; Insert associated timestamp.
  9188. (let ((ts (org-insert-time-stamp
  9189. time
  9190. (or org-time-was-given
  9191. (and (eq what 'closed) org-log-done-with-time))
  9192. (eq what 'closed)
  9193. nil nil (list org-end-time-was-given))))
  9194. (unless (eolp) (insert " "))
  9195. ts))))))
  9196. (defvar org-log-note-marker (make-marker)
  9197. "Marker pointing at the entry where the note is to be inserted.")
  9198. (defvar org-log-note-purpose nil)
  9199. (defvar org-log-note-state nil)
  9200. (defvar org-log-note-previous-state nil)
  9201. (defvar org-log-note-extra nil)
  9202. (defvar org-log-note-window-configuration nil)
  9203. (defvar org-log-note-return-to (make-marker))
  9204. (defvar org-log-note-effective-time nil
  9205. "Remembered current time.
  9206. So that dynamically scoped `org-extend-today-until' affects
  9207. timestamps in state change log.")
  9208. (defvar org-log-post-message nil
  9209. "Message to be displayed after a log note has been stored.
  9210. The auto-repeater uses this.")
  9211. (defun org-add-note ()
  9212. "Add a note to the current entry.
  9213. This is done in the same way as adding a state change note."
  9214. (interactive)
  9215. (org-add-log-setup 'note))
  9216. (defun org-log-beginning (&optional create)
  9217. "Return expected start of log notes in current entry.
  9218. When optional argument CREATE is non-nil, the function creates
  9219. a drawer to store notes, if necessary. Returned position ignores
  9220. narrowing."
  9221. (org-with-wide-buffer
  9222. (let ((drawer (org-log-into-drawer)))
  9223. (cond
  9224. (drawer
  9225. (org-end-of-meta-data)
  9226. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9227. (end (if (org-at-heading-p) (point)
  9228. (save-excursion (outline-next-heading) (point))))
  9229. (case-fold-search t))
  9230. (catch 'exit
  9231. ;; Try to find existing drawer.
  9232. (while (re-search-forward regexp end t)
  9233. (let ((element (org-element-at-point)))
  9234. (when (eq (org-element-type element) 'drawer)
  9235. (let ((cend (org-element-property :contents-end element)))
  9236. (when (and (not org-log-states-order-reversed) cend)
  9237. (goto-char cend)))
  9238. (throw 'exit nil))))
  9239. ;; No drawer found. Create one, if permitted.
  9240. (when create
  9241. ;; Avoid situation when we insert drawer right before
  9242. ;; first "*". Otherwise, if the previous heading is
  9243. ;; folded, we are inserting after visible newline at
  9244. ;; the end of the fold, thus breaking the fold
  9245. ;; continuity.
  9246. (when (org-at-heading-p) (backward-char))
  9247. (org-fold-core-ignore-modifications
  9248. (unless (bolp) (insert-and-inherit "\n"))
  9249. (let ((beg (point)))
  9250. (insert-and-inherit ":" drawer ":\n:END:\n")
  9251. (org-indent-region beg (point))
  9252. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9253. (end-of-line -1))))
  9254. (t
  9255. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9256. (skip-chars-forward " \t\n")
  9257. (beginning-of-line)
  9258. (unless org-log-states-order-reversed
  9259. (org-skip-over-state-notes)
  9260. (skip-chars-backward " \t\n")
  9261. (beginning-of-line 2)))))
  9262. (if (bolp) (point) (line-beginning-position 2))))
  9263. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9264. "Set up the post command hook to take a note.
  9265. If this is about to TODO state change, the new state is expected in STATE.
  9266. HOW is an indicator what kind of note should be created.
  9267. EXTRA is additional text that will be inserted into the notes buffer."
  9268. (move-marker org-log-note-marker (point))
  9269. (setq org-log-note-purpose purpose
  9270. org-log-note-state state
  9271. org-log-note-previous-state prev-state
  9272. org-log-note-how how
  9273. org-log-note-extra extra
  9274. org-log-note-effective-time (org-current-effective-time)
  9275. org-log-setup t)
  9276. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9277. (defun org-skip-over-state-notes ()
  9278. "Skip past the list of State notes in an entry."
  9279. (when (ignore-errors (goto-char (org-in-item-p)))
  9280. (let* ((struct (org-list-struct))
  9281. (prevs (org-list-prevs-alist struct))
  9282. (regexp
  9283. (concat "[ \t]*- +"
  9284. (replace-regexp-in-string
  9285. " +" " +"
  9286. (org-replace-escapes
  9287. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9288. `(("%d" . ,org-ts-regexp-inactive)
  9289. ("%D" . ,org-ts-regexp)
  9290. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9291. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9292. ("%t" . ,org-ts-regexp-inactive)
  9293. ("%T" . ,org-ts-regexp)
  9294. ("%u" . ".*?")
  9295. ("%U" . ".*?")))))))
  9296. (while (looking-at-p regexp)
  9297. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9298. (org-list-get-item-end (point) struct)))))))
  9299. (defun org-add-log-note (&optional _purpose)
  9300. "Pop up a window for taking a note, and add this note later."
  9301. (remove-hook 'post-command-hook 'org-add-log-note)
  9302. (setq org-log-setup nil)
  9303. (setq org-log-note-window-configuration (current-window-configuration))
  9304. (delete-other-windows)
  9305. (move-marker org-log-note-return-to (point))
  9306. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9307. (goto-char org-log-note-marker)
  9308. (org-switch-to-buffer-other-window "*Org Note*")
  9309. (erase-buffer)
  9310. (if (memq org-log-note-how '(time state))
  9311. (org-store-log-note)
  9312. (let ((org-inhibit-startup t)) (org-mode))
  9313. (insert (format "# Insert note for %s.
  9314. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9315. (cl-case org-log-note-purpose
  9316. (clock-out "stopped clock")
  9317. (done "closed todo item")
  9318. (reschedule "rescheduling")
  9319. (delschedule "no longer scheduled")
  9320. (redeadline "changing deadline")
  9321. (deldeadline "removing deadline")
  9322. (refile "refiling")
  9323. (note "this entry")
  9324. (state
  9325. (format "state change from \"%s\" to \"%s\""
  9326. (or org-log-note-previous-state "")
  9327. (or org-log-note-state "")))
  9328. (t (error "This should not happen")))))
  9329. (when org-log-note-extra (insert org-log-note-extra))
  9330. (setq-local org-finish-function 'org-store-log-note)
  9331. (run-hooks 'org-log-buffer-setup-hook)))
  9332. (defvar org-note-abort nil) ; dynamically scoped
  9333. (defun org-store-log-note ()
  9334. "Finish taking a log note, and insert it to where it belongs."
  9335. (let ((txt (prog1 (buffer-string)
  9336. (kill-buffer)))
  9337. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9338. lines)
  9339. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9340. (setq txt (replace-match "" t t txt)))
  9341. (when (string-match "\\s-+\\'" txt)
  9342. (setq txt (replace-match "" t t txt)))
  9343. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9344. (when (org-string-nw-p note)
  9345. (setq note
  9346. (org-replace-escapes
  9347. note
  9348. (list (cons "%u" (user-login-name))
  9349. (cons "%U" user-full-name)
  9350. (cons "%t" (format-time-string
  9351. (org-time-stamp-format 'long 'inactive)
  9352. org-log-note-effective-time))
  9353. (cons "%T" (format-time-string
  9354. (org-time-stamp-format 'long nil)
  9355. org-log-note-effective-time))
  9356. (cons "%d" (format-time-string
  9357. (org-time-stamp-format nil 'inactive)
  9358. org-log-note-effective-time))
  9359. (cons "%D" (format-time-string
  9360. (org-time-stamp-format nil nil)
  9361. org-log-note-effective-time))
  9362. (cons "%s" (cond
  9363. ((not org-log-note-state) "")
  9364. ((string-match-p org-ts-regexp
  9365. org-log-note-state)
  9366. (format "\"[%s]\""
  9367. (substring org-log-note-state 1 -1)))
  9368. (t (format "\"%s\"" org-log-note-state))))
  9369. (cons "%S"
  9370. (cond
  9371. ((not org-log-note-previous-state) "")
  9372. ((string-match-p org-ts-regexp
  9373. org-log-note-previous-state)
  9374. (format "\"[%s]\""
  9375. (substring
  9376. org-log-note-previous-state 1 -1)))
  9377. (t (format "\"%s\""
  9378. org-log-note-previous-state)))))))
  9379. (when lines (setq note (concat note " \\\\")))
  9380. (push note lines))
  9381. (when (and lines (not org-note-abort))
  9382. (with-current-buffer (marker-buffer org-log-note-marker)
  9383. (org-fold-core-ignore-modifications
  9384. (org-with-wide-buffer
  9385. ;; Find location for the new note.
  9386. (goto-char org-log-note-marker)
  9387. (set-marker org-log-note-marker nil)
  9388. ;; Note associated to a clock is to be located right after
  9389. ;; the clock. Do not move point.
  9390. (unless (eq org-log-note-purpose 'clock-out)
  9391. (goto-char (org-log-beginning t)))
  9392. ;; Make sure point is at the beginning of an empty line.
  9393. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9394. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9395. ;; In an existing list, add a new item at the top level.
  9396. ;; Otherwise, indent line like a regular one.
  9397. (let ((itemp (org-in-item-p)))
  9398. (if itemp
  9399. (indent-line-to
  9400. (let ((struct (save-excursion
  9401. (goto-char itemp) (org-list-struct))))
  9402. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9403. (org-indent-line)))
  9404. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9405. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9406. (dolist (line lines)
  9407. (insert-and-inherit "\n")
  9408. (unless (string-empty-p line)
  9409. (indent-line-to ind)
  9410. (insert-and-inherit line))))
  9411. (message "Note stored")
  9412. (org-back-to-heading t))))))
  9413. ;; Don't add undo information when called from `org-agenda-todo'.
  9414. (set-window-configuration org-log-note-window-configuration)
  9415. (with-current-buffer (marker-buffer org-log-note-return-to)
  9416. (goto-char org-log-note-return-to))
  9417. (move-marker org-log-note-return-to nil)
  9418. (when org-log-post-message (message "%s" org-log-post-message)))
  9419. (defun org-remove-empty-drawer-at (pos)
  9420. "Remove an empty drawer at position POS.
  9421. POS may also be a marker."
  9422. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9423. (org-with-wide-buffer
  9424. (goto-char pos)
  9425. (let ((drawer (org-element-at-point)))
  9426. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9427. (not (org-element-property :contents-begin drawer)))
  9428. (delete-region (org-element-property :begin drawer)
  9429. (progn (goto-char (org-element-property :end drawer))
  9430. (skip-chars-backward " \r\t\n")
  9431. (forward-line)
  9432. (point))))))))
  9433. (defvar org-ts-type nil)
  9434. (defun org-sparse-tree (&optional arg type)
  9435. "Create a sparse tree, prompt for the details.
  9436. This command can create sparse trees. You first need to select the type
  9437. of match used to create the tree:
  9438. t Show all TODO entries.
  9439. T Show entries with a specific TODO keyword.
  9440. m Show entries selected by a tags/property match.
  9441. p Enter a property name and its value (both with completion on existing
  9442. names/values) and show entries with that property.
  9443. r Show entries matching a regular expression (`/' can be used as well).
  9444. b Show deadlines and scheduled items before a date.
  9445. a Show deadlines and scheduled items after a date.
  9446. d Show deadlines due within `org-deadline-warning-days'.
  9447. D Show deadlines and scheduled items between a date range."
  9448. (interactive "P")
  9449. (setq type (or type org-sparse-tree-default-date-type))
  9450. (setq org-ts-type type)
  9451. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9452. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9453. [c]ycle through date types: %s"
  9454. (cl-case type
  9455. (all "all timestamps")
  9456. (scheduled "only scheduled")
  9457. (deadline "only deadline")
  9458. (active "only active timestamps")
  9459. (inactive "only inactive timestamps")
  9460. (closed "with a closed time-stamp")
  9461. (otherwise "scheduled/deadline")))
  9462. (let ((answer (read-char-exclusive)))
  9463. (cl-case answer
  9464. (?c
  9465. (org-sparse-tree
  9466. arg
  9467. (cadr
  9468. (memq type '(nil all scheduled deadline active inactive closed)))))
  9469. (?d (call-interactively 'org-check-deadlines))
  9470. (?b (call-interactively 'org-check-before-date))
  9471. (?a (call-interactively 'org-check-after-date))
  9472. (?D (call-interactively 'org-check-dates-range))
  9473. (?t (call-interactively 'org-show-todo-tree))
  9474. (?T (org-show-todo-tree '(4)))
  9475. (?m (call-interactively 'org-match-sparse-tree))
  9476. ((?p ?P)
  9477. (let* ((kwd (completing-read
  9478. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9479. (value (completing-read
  9480. "Value: " (mapcar #'list (org-property-values kwd)))))
  9481. (unless (string-match "\\`{.*}\\'" value)
  9482. (setq value (concat "\"" value "\"")))
  9483. (org-match-sparse-tree arg (concat kwd "=" value))))
  9484. ((?r ?R ?/) (call-interactively 'org-occur))
  9485. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9486. (defvar-local org-occur-highlights nil
  9487. "List of overlays used for occur matches.")
  9488. (defvar-local org-occur-parameters nil
  9489. "Parameters of the active org-occur calls.
  9490. This is a list, each call to org-occur pushes as cons cell,
  9491. containing the regular expression and the callback, onto the list.
  9492. The list can contain several entries if `org-occur' has been called
  9493. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9494. will only contain one set of parameters. When the highlights are
  9495. removed (for example with `C-c C-c', or with the next edit (depending
  9496. on `org-remove-highlights-with-change'), this variable is emptied
  9497. as well.")
  9498. (defun org-occur (regexp &optional keep-previous callback)
  9499. "Make a compact tree showing all matches of REGEXP.
  9500. The tree will show the lines where the regexp matches, and any other context
  9501. defined in `org-fold-show-context-detail', which see.
  9502. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9503. done by a previous call to `org-occur' will be kept, to allow stacking of
  9504. calls to this command.
  9505. Optional argument CALLBACK can be a function of no argument. In this case,
  9506. it is called with point at the end of the match, match data being set
  9507. accordingly. Current match is shown only if the return value is non-nil.
  9508. The function must neither move point nor alter narrowing."
  9509. (interactive "sRegexp: \nP")
  9510. (when (equal regexp "")
  9511. (user-error "Regexp cannot be empty"))
  9512. (unless keep-previous
  9513. (org-remove-occur-highlights nil nil t))
  9514. (push (cons regexp callback) org-occur-parameters)
  9515. (let ((cnt 0))
  9516. (save-excursion
  9517. (goto-char (point-min))
  9518. (when (or (not keep-previous) ; do not want to keep
  9519. (not org-occur-highlights)) ; no previous matches
  9520. ;; hide everything
  9521. (org-cycle-overview))
  9522. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9523. (isearch-no-upper-case-p regexp t)
  9524. org-occur-case-fold-search)))
  9525. (while (re-search-forward regexp nil t)
  9526. (when (or (not callback)
  9527. (save-match-data (funcall callback)))
  9528. (setq cnt (1+ cnt))
  9529. (when org-highlight-sparse-tree-matches
  9530. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9531. (org-fold-show-context 'occur-tree)))))
  9532. (when org-remove-highlights-with-change
  9533. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9534. nil 'local))
  9535. (unless org-sparse-tree-open-archived-trees
  9536. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9537. (run-hooks 'org-occur-hook)
  9538. (when (called-interactively-p 'interactive)
  9539. (message "%d match(es) for regexp %s" cnt regexp))
  9540. cnt))
  9541. (defun org-occur-next-match (&optional n _reset)
  9542. "Function for `next-error-function' to find sparse tree matches.
  9543. N is the number of matches to move, when negative move backwards.
  9544. This function always goes back to the starting point when no
  9545. match is found."
  9546. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9547. (search-func (if (< n 0)
  9548. 'previous-single-char-property-change
  9549. 'next-single-char-property-change))
  9550. (n (abs n))
  9551. (pos (point))
  9552. p1)
  9553. (catch 'exit
  9554. (while (setq p1 (funcall search-func (point) 'org-type))
  9555. (when (equal p1 limit)
  9556. (goto-char pos)
  9557. (user-error "No more matches"))
  9558. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9559. (setq n (1- n))
  9560. (when (= n 0)
  9561. (goto-char p1)
  9562. (throw 'exit (point))))
  9563. (goto-char p1))
  9564. (goto-char p1)
  9565. (user-error "No more matches"))))
  9566. (defun org-highlight-new-match (beg end)
  9567. "Highlight from BEG to END and mark the highlight is an occur headline."
  9568. (let ((ov (make-overlay beg end)))
  9569. (overlay-put ov 'face 'secondary-selection)
  9570. (overlay-put ov 'org-type 'org-occur)
  9571. (push ov org-occur-highlights)))
  9572. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9573. "Remove the occur highlights from the buffer.
  9574. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9575. from the `before-change-functions' in the current buffer."
  9576. (interactive)
  9577. (unless org-inhibit-highlight-removal
  9578. (mapc #'delete-overlay org-occur-highlights)
  9579. (setq org-occur-highlights nil)
  9580. (setq org-occur-parameters nil)
  9581. (unless noremove
  9582. (remove-hook 'before-change-functions
  9583. 'org-remove-occur-highlights 'local))))
  9584. ;;;; Priorities
  9585. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9586. "Regular expression matching the priority indicator.
  9587. A priority indicator can be e.g. [#A] or [#1].
  9588. This regular expression matches these groups:
  9589. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9590. 1 : the priority cookie, e.g. \"[#A]\"
  9591. 2 : the value of the priority cookie, e.g. \"A\".")
  9592. (defun org-priority-up ()
  9593. "Increase the priority of the current item."
  9594. (interactive)
  9595. (org-priority 'up))
  9596. (defun org-priority-down ()
  9597. "Decrease the priority of the current item."
  9598. (interactive)
  9599. (org-priority 'down))
  9600. (defun org-priority (&optional action show)
  9601. "Change the priority of an item.
  9602. When called interactively with a `\\[universal-argument]' prefix,
  9603. show the priority in the minibuffer instead of changing it.
  9604. When called programmatically, ACTION can be `set', `up', `down',
  9605. or a character."
  9606. (interactive "P")
  9607. (when show
  9608. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9609. ;; passed the SHOW argument should be removed.
  9610. (warn "`org-priority' called with deprecated SHOW argument"))
  9611. (if (equal action '(4))
  9612. (org-priority-show)
  9613. (unless org-priority-enable-commands
  9614. (user-error "Priority commands are disabled"))
  9615. (setq action (or action 'set))
  9616. (let ((nump (< org-priority-lowest 65))
  9617. current new news have remove)
  9618. (save-excursion
  9619. (org-back-to-heading t)
  9620. (when (looking-at org-priority-regexp)
  9621. (let ((ms (match-string 2)))
  9622. (setq current (org-priority-to-value ms)
  9623. have t)))
  9624. (cond
  9625. ((eq action 'remove)
  9626. (setq remove t new ?\ ))
  9627. ((or (eq action 'set)
  9628. (integerp action))
  9629. (if (not (eq action 'set))
  9630. (setq new action)
  9631. (setq
  9632. new
  9633. (if nump
  9634. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9635. (number-to-string org-priority-highest)
  9636. (number-to-string org-priority-lowest)))
  9637. (s (if (< 9 org-priority-lowest)
  9638. (read-string msg)
  9639. (message msg)
  9640. (char-to-string (read-char-exclusive)))))
  9641. (if (equal s " ") ?\s (string-to-number s)))
  9642. (progn (message "Priority %c-%c, SPC to remove: "
  9643. org-priority-highest org-priority-lowest)
  9644. (save-match-data
  9645. (setq new (read-char-exclusive)))))))
  9646. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9647. (= (upcase org-priority-lowest) org-priority-lowest))
  9648. (setq new (upcase new)))
  9649. (cond ((equal new ?\s) (setq remove t))
  9650. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9651. (user-error
  9652. (if nump
  9653. "Priority must be between `%s' and `%s'"
  9654. "Priority must be between `%c' and `%c'")
  9655. org-priority-highest org-priority-lowest))))
  9656. ((eq action 'up)
  9657. (setq new (if have
  9658. (1- current) ; normal cycling
  9659. ;; last priority was empty
  9660. (if (eq last-command this-command)
  9661. org-priority-lowest ; wrap around empty to lowest
  9662. ;; default
  9663. (if org-priority-start-cycle-with-default
  9664. org-priority-default
  9665. (1- org-priority-default))))))
  9666. ((eq action 'down)
  9667. (setq new (if have
  9668. (1+ current) ; normal cycling
  9669. ;; last priority was empty
  9670. (if (eq last-command this-command)
  9671. org-priority-highest ; wrap around empty to highest
  9672. ;; default
  9673. (if org-priority-start-cycle-with-default
  9674. org-priority-default
  9675. (1+ org-priority-default))))))
  9676. (t (user-error "Invalid action")))
  9677. (when (or (< (upcase new) org-priority-highest)
  9678. (> (upcase new) org-priority-lowest))
  9679. (if (and (memq action '(up down))
  9680. (not have) (not (eq last-command this-command)))
  9681. ;; `new' is from default priority
  9682. (error
  9683. "The default can not be set, see `org-priority-default' why")
  9684. ;; normal cycling: `new' is beyond highest/lowest priority
  9685. ;; and is wrapped around to the empty priority
  9686. (setq remove t)))
  9687. ;; Numerical priorities are limited to 64, beyond that number,
  9688. ;; assume the priority cookie is a character.
  9689. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9690. (if have
  9691. (if remove
  9692. (replace-match "" t t nil 1)
  9693. (replace-match news t t nil 2))
  9694. (if remove
  9695. (user-error "No priority cookie found in line")
  9696. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9697. (if (match-end 2)
  9698. (progn
  9699. (goto-char (match-end 2))
  9700. (insert " [#" news "]"))
  9701. (goto-char (match-beginning 3))
  9702. (insert "[#" news "] "))))
  9703. (org-align-tags))
  9704. (if remove
  9705. (message "Priority removed")
  9706. (message "Priority of current item set to %s" news)))))
  9707. (defalias 'org-show-priority 'org-priority-show)
  9708. (defun org-priority-show ()
  9709. "Show the priority of the current item.
  9710. This priority is composed of the main priority given with the [#A] cookies,
  9711. and by additional input from the age of a schedules or deadline entry."
  9712. (interactive)
  9713. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9714. (org-get-at-bol 'priority)
  9715. (save-excursion
  9716. (save-match-data
  9717. (beginning-of-line)
  9718. (and (looking-at org-heading-regexp)
  9719. (org-get-priority (match-string 0))))))))
  9720. (message "Priority is %d" (if pri pri -1000))))
  9721. (defun org-get-priority (s)
  9722. "Find priority cookie and return priority.
  9723. S is a string against which you can match `org-priority-regexp'.
  9724. If `org-priority-get-priority-function' is set to a custom
  9725. function, use it. Otherwise process S and output the priority
  9726. value, an integer."
  9727. (save-match-data
  9728. (if (functionp org-priority-get-priority-function)
  9729. (funcall org-priority-get-priority-function s)
  9730. (if (not (string-match org-priority-regexp s))
  9731. (* 1000 (- org-priority-lowest org-priority-default))
  9732. (* 1000 (- org-priority-lowest
  9733. (org-priority-to-value (match-string 2 s))))))))
  9734. ;;;; Tags
  9735. (defvar org-agenda-archives-mode)
  9736. (defvar org-map-continue-from nil
  9737. "Position from where mapping should continue.
  9738. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9739. (defvar org-scanner-tags nil
  9740. "The current tag list while the tags scanner is running.")
  9741. (defvar org-trust-scanner-tags nil
  9742. "Should `org-get-tags' use the tags for the scanner.
  9743. This is for internal dynamical scoping only.
  9744. When this is non-nil, the function `org-get-tags' will return the value
  9745. of `org-scanner-tags' instead of building the list by itself. This
  9746. can lead to large speed-ups when the tags scanner is used in a file with
  9747. many entries, and when the list of tags is retrieved, for example to
  9748. obtain a list of properties. Building the tags list for each entry in such
  9749. a file becomes an N^2 operation - but with this variable set, it scales
  9750. as N.")
  9751. (defvar org--matcher-tags-todo-only nil)
  9752. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9753. "Scan headline tags with inheritance and produce output ACTION.
  9754. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9755. or `agenda' to produce an entry list for an agenda view. It can also be
  9756. a Lisp form or a function that should be called at each matched headline, in
  9757. this case the return value is a list of all return values from these calls.
  9758. MATCHER is a function accepting three arguments, returning
  9759. a non-nil value whenever a given set of tags qualifies a headline
  9760. for inclusion. See `org-make-tags-matcher' for more information.
  9761. As a special case, it can also be set to t (respectively nil) in
  9762. order to match all (respectively none) headline.
  9763. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9764. included in the output.
  9765. START-LEVEL can be a string with asterisks, reducing the scope to
  9766. headlines matching this string."
  9767. (require 'org-agenda)
  9768. (let* ((re (concat "^"
  9769. (if start-level
  9770. ;; Get the correct level to match
  9771. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9772. org-outline-regexp)
  9773. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9774. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9775. (props (list 'face 'default
  9776. 'done-face 'org-agenda-done
  9777. 'undone-face 'default
  9778. 'mouse-face 'highlight
  9779. 'org-not-done-regexp org-not-done-regexp
  9780. 'org-todo-regexp org-todo-regexp
  9781. 'org-complex-heading-regexp org-complex-heading-regexp
  9782. 'help-echo
  9783. (format "mouse-2 or RET jump to Org file %S"
  9784. (abbreviate-file-name
  9785. (or (buffer-file-name (buffer-base-buffer))
  9786. (buffer-name (buffer-base-buffer)))))))
  9787. (org-map-continue-from nil)
  9788. lspos tags tags-list
  9789. (tags-alist (list (cons 0 org-file-tags)))
  9790. (llast 0) rtn rtn1 level category i txt
  9791. todo marker entry priority
  9792. ts-date ts-date-type ts-date-pair)
  9793. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9794. (setq action (list 'lambda nil action)))
  9795. (save-excursion
  9796. (goto-char (point-min))
  9797. (when (eq action 'sparse-tree)
  9798. (org-cycle-overview)
  9799. (org-remove-occur-highlights))
  9800. (if (org-element--cache-active-p)
  9801. (let ((fast-re (concat "^"
  9802. (if start-level
  9803. ;; Get the correct level to match
  9804. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9805. org-outline-regexp))))
  9806. (org-element-cache-map
  9807. (lambda (el)
  9808. (goto-char (org-element-property :begin el))
  9809. (setq todo (org-element-property :todo-keyword el)
  9810. level (org-element-property :level el)
  9811. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9812. tags-list (org-get-tags el)
  9813. org-scanner-tags tags-list)
  9814. (when (eq action 'agenda)
  9815. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9816. ts-date (car ts-date-pair)
  9817. ts-date-type (cdr ts-date-pair)))
  9818. (catch :skip
  9819. (when (and
  9820. ;; eval matcher only when the todo condition is OK
  9821. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9822. (if (functionp matcher)
  9823. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9824. (funcall matcher todo tags-list level))
  9825. matcher))
  9826. ;; Call the skipper, but return t if it does not
  9827. ;; skip, so that the `and' form continues evaluating.
  9828. (progn
  9829. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9830. t)
  9831. ;; Check if timestamps are deselecting this entry
  9832. (or (not todo-only)
  9833. (and (member todo org-todo-keywords-1)
  9834. (or (not org-agenda-tags-todo-honor-ignore-options)
  9835. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9836. ;; select this headline
  9837. (cond
  9838. ((eq action 'sparse-tree)
  9839. (and org-highlight-sparse-tree-matches
  9840. (org-get-heading) (match-end 0)
  9841. (org-highlight-new-match
  9842. (match-beginning 1) (match-end 1)))
  9843. (org-fold-show-context 'tags-tree))
  9844. ((eq action 'agenda)
  9845. (let* ((effort (org-entry-get (point) org-effort-property))
  9846. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9847. (setq txt (org-agenda-format-item
  9848. ""
  9849. ;; Add `effort' and `effort-minutes'
  9850. ;; properties for prefix format.
  9851. (org-add-props
  9852. (concat
  9853. (if (eq org-tags-match-list-sublevels 'indented)
  9854. (make-string (1- level) ?.) "")
  9855. (org-get-heading))
  9856. nil
  9857. 'effort effort
  9858. 'effort-minutes effort-minutes)
  9859. (make-string level ?\s)
  9860. category
  9861. tags-list)
  9862. priority (org-get-priority txt))
  9863. ;; Now add `effort' and `effort-minutes' to
  9864. ;; full agenda line.
  9865. (setq txt (org-add-props txt nil
  9866. 'effort effort
  9867. 'effort-minutes effort-minutes)))
  9868. (goto-char (org-element-property :begin el))
  9869. (setq marker (org-agenda-new-marker))
  9870. (org-add-props txt props
  9871. 'org-marker marker 'org-hd-marker marker 'org-category category
  9872. 'todo-state todo
  9873. 'ts-date ts-date
  9874. 'priority priority
  9875. 'type (concat "tagsmatch" ts-date-type))
  9876. (push txt rtn))
  9877. ((functionp action)
  9878. (setq org-map-continue-from nil)
  9879. (save-excursion
  9880. (setq rtn1 (funcall action))
  9881. (push rtn1 rtn)))
  9882. (t (user-error "Invalid action")))
  9883. ;; if we are to skip sublevels, jump to end of subtree
  9884. (unless org-tags-match-list-sublevels
  9885. (goto-char (1- (org-element-property :end el))))))
  9886. ;; Get the correct position from where to continue
  9887. (when org-map-continue-from
  9888. (setq org-element-cache-map-continue-from org-map-continue-from)
  9889. (goto-char org-map-continue-from))
  9890. ;; Return nil.
  9891. nil)
  9892. :next-re fast-re
  9893. :fail-re fast-re
  9894. :narrow t))
  9895. (while (let (case-fold-search)
  9896. (re-search-forward re nil t))
  9897. (setq org-map-continue-from nil)
  9898. (catch :skip
  9899. ;; Ignore closing parts of inline tasks.
  9900. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9901. (throw :skip t))
  9902. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9903. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9904. (goto-char (setq lspos (match-beginning 0)))
  9905. (setq level (org-reduced-level (org-outline-level))
  9906. category (org-get-category))
  9907. (when (eq action 'agenda)
  9908. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9909. ts-date (car ts-date-pair)
  9910. ts-date-type (cdr ts-date-pair)))
  9911. (setq i llast llast level)
  9912. ;; remove tag lists from same and sublevels
  9913. (while (>= i level)
  9914. (when (setq entry (assoc i tags-alist))
  9915. (setq tags-alist (delete entry tags-alist)))
  9916. (setq i (1- i)))
  9917. ;; add the next tags
  9918. (when tags
  9919. (setq tags (org-split-string tags ":")
  9920. tags-alist
  9921. (cons (cons level tags) tags-alist)))
  9922. ;; compile tags for current headline
  9923. (setq tags-list
  9924. (if org-use-tag-inheritance
  9925. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  9926. tags)
  9927. org-scanner-tags tags-list)
  9928. (when org-use-tag-inheritance
  9929. (setcdr (car tags-alist)
  9930. (mapcar (lambda (x)
  9931. (setq x (copy-sequence x))
  9932. (org-add-prop-inherited x))
  9933. (cdar tags-alist))))
  9934. (when (and tags org-use-tag-inheritance
  9935. (or (not (eq t org-use-tag-inheritance))
  9936. org-tags-exclude-from-inheritance))
  9937. ;; Selective inheritance, remove uninherited ones.
  9938. (setcdr (car tags-alist)
  9939. (org-remove-uninherited-tags (cdar tags-alist))))
  9940. (when (and
  9941. ;; eval matcher only when the todo condition is OK
  9942. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9943. (if (functionp matcher)
  9944. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9945. (funcall matcher todo tags-list level))
  9946. matcher))
  9947. ;; Call the skipper, but return t if it does not
  9948. ;; skip, so that the `and' form continues evaluating.
  9949. (progn
  9950. (unless (eq action 'sparse-tree) (org-agenda-skip))
  9951. t)
  9952. ;; Check if timestamps are deselecting this entry
  9953. (or (not todo-only)
  9954. (and (member todo org-todo-keywords-1)
  9955. (or (not org-agenda-tags-todo-honor-ignore-options)
  9956. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9957. ;; select this headline
  9958. (cond
  9959. ((eq action 'sparse-tree)
  9960. (and org-highlight-sparse-tree-matches
  9961. (org-get-heading) (match-end 0)
  9962. (org-highlight-new-match
  9963. (match-beginning 1) (match-end 1)))
  9964. (org-fold-show-context 'tags-tree))
  9965. ((eq action 'agenda)
  9966. (setq txt (org-agenda-format-item
  9967. ""
  9968. (concat
  9969. (if (eq org-tags-match-list-sublevels 'indented)
  9970. (make-string (1- level) ?.) "")
  9971. (org-get-heading))
  9972. (make-string level ?\s)
  9973. category
  9974. tags-list)
  9975. priority (org-get-priority txt))
  9976. (goto-char lspos)
  9977. (setq marker (org-agenda-new-marker))
  9978. (org-add-props txt props
  9979. 'org-marker marker 'org-hd-marker marker 'org-category category
  9980. 'todo-state todo
  9981. 'ts-date ts-date
  9982. 'priority priority
  9983. 'type (concat "tagsmatch" ts-date-type))
  9984. (push txt rtn))
  9985. ((functionp action)
  9986. (setq org-map-continue-from nil)
  9987. (save-excursion
  9988. (setq rtn1 (funcall action))
  9989. (push rtn1 rtn)))
  9990. (t (user-error "Invalid action")))
  9991. ;; if we are to skip sublevels, jump to end of subtree
  9992. (unless org-tags-match-list-sublevels
  9993. (org-end-of-subtree t)
  9994. (backward-char 1))))
  9995. ;; Get the correct position from where to continue
  9996. (if org-map-continue-from
  9997. (goto-char org-map-continue-from)
  9998. (and (= (point) lspos) (end-of-line 1))))))
  9999. (when (and (eq action 'sparse-tree)
  10000. (not org-sparse-tree-open-archived-trees))
  10001. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  10002. (nreverse rtn)))
  10003. (defun org-remove-uninherited-tags (tags)
  10004. "Remove all tags that are not inherited from the list TAGS."
  10005. (cond
  10006. ((eq org-use-tag-inheritance t)
  10007. (if org-tags-exclude-from-inheritance
  10008. (org-delete-all org-tags-exclude-from-inheritance tags)
  10009. tags))
  10010. ((not org-use-tag-inheritance) nil)
  10011. ((stringp org-use-tag-inheritance)
  10012. (delq nil (mapcar
  10013. (lambda (x)
  10014. (if (and (string-match org-use-tag-inheritance x)
  10015. (not (member x org-tags-exclude-from-inheritance)))
  10016. x nil))
  10017. tags)))
  10018. ((listp org-use-tag-inheritance)
  10019. (delq nil (mapcar
  10020. (lambda (x)
  10021. (if (member x org-use-tag-inheritance) x nil))
  10022. tags)))))
  10023. (defun org-match-sparse-tree (&optional todo-only match)
  10024. "Create a sparse tree according to tags string MATCH.
  10025. MATCH is a string with match syntax. It can contain a selection
  10026. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10027. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10028. those. See the manual for details.
  10029. If optional argument TODO-ONLY is non-nil, only select lines that
  10030. are also TODO tasks."
  10031. (interactive "P")
  10032. (org-agenda-prepare-buffers (list (current-buffer)))
  10033. (let ((org--matcher-tags-todo-only todo-only))
  10034. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10035. org--matcher-tags-todo-only)))
  10036. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10037. (defvar org-cached-props nil)
  10038. (defun org-cached-entry-get (pom property)
  10039. (if (or (eq t org-use-property-inheritance)
  10040. (and (stringp org-use-property-inheritance)
  10041. (let ((case-fold-search t))
  10042. (string-match-p org-use-property-inheritance property)))
  10043. (and (listp org-use-property-inheritance)
  10044. (member-ignore-case property org-use-property-inheritance)))
  10045. ;; Caching is not possible, check it directly.
  10046. (org-entry-get pom property 'inherit)
  10047. ;; Get all properties, so we can do complicated checks easily.
  10048. (cdr (assoc-string property
  10049. (or org-cached-props
  10050. (setq org-cached-props (org-entry-properties pom)))
  10051. t))))
  10052. (defun org-global-tags-completion-table (&optional files)
  10053. "Return the list of all tags in all agenda buffer/files.
  10054. Optional FILES argument is a list of files which can be used
  10055. instead of the agenda files."
  10056. (save-excursion
  10057. (org-uniquify
  10058. (delq nil
  10059. (apply #'append
  10060. (mapcar
  10061. (lambda (file)
  10062. (set-buffer (find-file-noselect file))
  10063. (org--tag-add-to-alist
  10064. (org-get-buffer-tags)
  10065. (mapcar (lambda (x)
  10066. (and (stringp (car-safe x))
  10067. (list (car-safe x))))
  10068. org-current-tag-alist)))
  10069. (if (car-safe files) files
  10070. (org-agenda-files))))))))
  10071. (defun org-make-tags-matcher (match &optional only-local-tags)
  10072. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10073. Returns a cons of the selection string MATCH and a function
  10074. implementing the matcher.
  10075. The matcher is to be called at an Org entry, with point on the
  10076. headline, and returns non-nil if the entry matches the selection
  10077. string MATCH. It must be called with three arguments: the TODO
  10078. keyword at the entry (or nil if none), the list of all tags at
  10079. the entry including inherited ones and the reduced level of the
  10080. headline. Additionally, the category of the entry, if any, must
  10081. be specified as the text property `org-category' on the headline.
  10082. This function sets the variable `org--matcher-tags-todo-only' to
  10083. a non-nil value if the matcher restricts matching to TODO
  10084. entries, otherwise it is not touched.
  10085. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10086. table, only get buffer tags.
  10087. See also `org-scan-tags'."
  10088. (unless match
  10089. ;; Get a new match request, with completion against the global
  10090. ;; tags table and the local tags in current buffer.
  10091. (let ((org-last-tags-completion-table
  10092. (org--tag-add-to-alist
  10093. (org-get-buffer-tags)
  10094. (unless only-local-tags
  10095. (org-global-tags-completion-table)))))
  10096. (setq match
  10097. (completing-read
  10098. "Match: "
  10099. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10100. (let ((match0 match)
  10101. (re (concat
  10102. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10103. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10104. "\\([<>=]\\{1,2\\}\\)"
  10105. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10106. "\\|" org-tag-re "\\)"))
  10107. (start 0)
  10108. tagsmatch todomatch tagsmatcher todomatcher)
  10109. ;; Expand group tags.
  10110. (setq match (org-tags-expand match))
  10111. ;; Check if there is a TODO part of this match, which would be the
  10112. ;; part after a "/". To make sure that this slash is not part of
  10113. ;; a property value to be matched against, we also check that
  10114. ;; there is no / after that slash. First, find the last slash.
  10115. (let ((s 0))
  10116. (while (string-match "/+" match s)
  10117. (setq start (match-beginning 0))
  10118. (setq s (match-end 0))))
  10119. (if (and (string-match "/+" match start)
  10120. (not (string-match-p "\"" match start)))
  10121. ;; Match contains also a TODO-matching request.
  10122. (progn
  10123. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10124. (setq todomatch (substring match (match-end 0)))
  10125. (when (string-prefix-p "!" todomatch)
  10126. (setq org--matcher-tags-todo-only t)
  10127. (setq todomatch (substring todomatch 1)))
  10128. (when (string-match "\\`\\s-*\\'" todomatch)
  10129. (setq todomatch nil)))
  10130. ;; Only matching tags.
  10131. (setq tagsmatch match)
  10132. (setq todomatch nil))
  10133. ;; Make the tags matcher.
  10134. (when (org-string-nw-p tagsmatch)
  10135. (let ((orlist nil)
  10136. (orterms (org-split-string tagsmatch "|"))
  10137. term)
  10138. (while (setq term (pop orterms))
  10139. (while (and (equal (substring term -1) "\\") orterms)
  10140. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10141. (while (string-match re term)
  10142. (let* ((rest (substring term (match-end 0)))
  10143. (minus (and (match-end 1)
  10144. (equal (match-string 1 term) "-")))
  10145. (tag (save-match-data
  10146. (replace-regexp-in-string
  10147. "\\\\-" "-" (match-string 2 term))))
  10148. (regexp (eq (string-to-char tag) ?{))
  10149. (levelp (match-end 4))
  10150. (propp (match-end 5))
  10151. (mm
  10152. (cond
  10153. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10154. (levelp
  10155. `(,(org-op-to-function (match-string 3 term))
  10156. level
  10157. ,(string-to-number (match-string 4 term))))
  10158. (propp
  10159. (let* ((gv (pcase (upcase (match-string 5 term))
  10160. ("CATEGORY"
  10161. '(org-get-category (point)))
  10162. ("TODO" 'todo)
  10163. (p `(org-cached-entry-get nil ,p))))
  10164. (pv (match-string 7 term))
  10165. (regexp (eq (string-to-char pv) ?{))
  10166. (strp (eq (string-to-char pv) ?\"))
  10167. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10168. (po (org-op-to-function (match-string 6 term)
  10169. (if timep 'time strp))))
  10170. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10171. (when timep (setq pv (org-matcher-time pv)))
  10172. (cond ((and regexp (eq po '/=))
  10173. `(not (string-match ,pv (or ,gv ""))))
  10174. (regexp `(string-match ,pv (or ,gv "")))
  10175. (strp `(,po (or ,gv "") ,pv))
  10176. (t
  10177. `(,po
  10178. (string-to-number (or ,gv ""))
  10179. ,(string-to-number pv))))))
  10180. (t `(member ,tag tags-list)))))
  10181. (push (if minus `(not ,mm) mm) tagsmatcher)
  10182. (setq term rest)))
  10183. (push `(and ,@tagsmatcher) orlist)
  10184. (setq tagsmatcher nil))
  10185. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10186. ;; Make the TODO matcher.
  10187. (when (org-string-nw-p todomatch)
  10188. (let ((orlist nil))
  10189. (dolist (term (org-split-string todomatch "|"))
  10190. (while (string-match re term)
  10191. (let* ((minus (and (match-end 1)
  10192. (equal (match-string 1 term) "-")))
  10193. (kwd (match-string 2 term))
  10194. (regexp (eq (string-to-char kwd) ?{))
  10195. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10196. `(equal todo ,kwd))))
  10197. (push (if minus `(not ,mm) mm) todomatcher))
  10198. (setq term (substring term (match-end 0))))
  10199. (push (if (> (length todomatcher) 1)
  10200. (cons 'and todomatcher)
  10201. (car todomatcher))
  10202. orlist)
  10203. (setq todomatcher nil))
  10204. (setq todomatcher (cons 'or orlist))))
  10205. ;; Return the string and function of the matcher. If no
  10206. ;; tags-specific or todo-specific matcher exists, match
  10207. ;; everything.
  10208. (let ((matcher (if (and tagsmatcher todomatcher)
  10209. `(and ,tagsmatcher ,todomatcher)
  10210. (or tagsmatcher todomatcher t))))
  10211. (when org--matcher-tags-todo-only
  10212. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10213. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10214. (defun org--tags-expand-group (group tag-groups expanded)
  10215. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10216. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10217. an accumulator used in recursive calls."
  10218. (dolist (tag group)
  10219. (unless (member tag expanded)
  10220. (let ((group (assoc tag tag-groups)))
  10221. (push tag expanded)
  10222. (when group
  10223. (setq expanded
  10224. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10225. expanded)
  10226. (defun org-tags-expand (match &optional single-as-list)
  10227. "Expand group tags in MATCH.
  10228. This replaces every group tag in MATCH with a regexp tag search.
  10229. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10230. will be replaced like this:
  10231. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10232. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10233. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10234. Replacing by a regexp preserves the structure of the match.
  10235. E.g., this expansion
  10236. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10237. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10238. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10239. A group tag in MATCH can contain regular expressions of its own.
  10240. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10241. will be replaced like this:
  10242. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10243. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10244. assumed to be a single group tag, and the function will return
  10245. the list of tags in this group."
  10246. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10247. (let ((tag-groups
  10248. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10249. (cond
  10250. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10251. (org-group-tags
  10252. (let* ((case-fold-search t)
  10253. (tag-syntax org-mode-syntax-table)
  10254. (group-keys (mapcar #'car tag-groups))
  10255. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10256. (return-match match))
  10257. ;; Mark regexp-expressions in the match-expression so that we
  10258. ;; do not replace them later on.
  10259. (let ((s 0))
  10260. (while (string-match "{.+?}" return-match s)
  10261. (setq s (match-end 0))
  10262. (add-text-properties
  10263. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10264. ;; @ and _ are allowed as word-components in tags.
  10265. (modify-syntax-entry ?@ "w" tag-syntax)
  10266. (modify-syntax-entry ?_ "w" tag-syntax)
  10267. ;; For each tag token found in MATCH, compute a regexp and it
  10268. (with-syntax-table tag-syntax
  10269. (replace-regexp-in-string
  10270. key-regexp
  10271. (lambda (m)
  10272. (if (get-text-property (match-beginning 2) 'regexp m)
  10273. m ;regexp tag: ignore
  10274. (let* ((operator (match-string 1 m))
  10275. (tag-token (let ((tag (match-string 2 m)))
  10276. (list tag)))
  10277. regexp-tags regular-tags)
  10278. ;; Partition tags between regexp and regular tags.
  10279. ;; Remove curly bracket syntax from regexp tags.
  10280. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10281. (save-match-data
  10282. (if (string-match "{\\(.+?\\)}" tag)
  10283. (push (match-string 1 tag) regexp-tags)
  10284. (push tag regular-tags))))
  10285. ;; Replace tag token by the appropriate regexp.
  10286. ;; Regular tags need to be regexp-quoted, whereas
  10287. ;; regexp-tags are inserted as-is.
  10288. (let ((regular (regexp-opt regular-tags))
  10289. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10290. (concat operator
  10291. (cond
  10292. ((null regular-tags) (format "{%s}" regexp))
  10293. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10294. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10295. return-match
  10296. t t))))
  10297. (t match))))
  10298. (defun org-op-to-function (op &optional stringp)
  10299. "Turn an operator into the appropriate function."
  10300. (setq op
  10301. (cond
  10302. ((equal op "<" ) '(< org-string< org-time<))
  10303. ((equal op ">" ) '(> org-string> org-time>))
  10304. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10305. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10306. ((member op '("=" "==")) '(= string= org-time=))
  10307. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10308. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10309. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10310. (defvar org-tags-overlay (make-overlay 1 1))
  10311. (delete-overlay org-tags-overlay)
  10312. (defun org-add-prop-inherited (s)
  10313. (add-text-properties 0 (length s) '(inherited t) s)
  10314. s)
  10315. (defun org-toggle-tag (tag &optional onoff)
  10316. "Toggle the tag TAG for the current line.
  10317. If ONOFF is `on' or `off', don't toggle but set to this state."
  10318. (save-excursion
  10319. (org-back-to-heading t)
  10320. (let ((current
  10321. ;; Reverse the tags list so any new tag is appended to the
  10322. ;; current list of tags.
  10323. (nreverse (org-get-tags nil t)))
  10324. res)
  10325. (pcase onoff
  10326. (`off (setq current (delete tag current)))
  10327. ((or `on (guard (not (member tag current))))
  10328. (setq res t)
  10329. (cl-pushnew tag current :test #'equal))
  10330. (_ (setq current (delete tag current))))
  10331. (org-set-tags (nreverse current))
  10332. res)))
  10333. (defun org--align-tags-here (to-col)
  10334. "Align tags on the current headline to TO-COL.
  10335. Assume point is on a headline. Preserve point when aligning
  10336. tags."
  10337. (when (org-match-line org-tag-line-re)
  10338. (let* ((tags-start (match-beginning 1))
  10339. (blank-start (save-excursion
  10340. (goto-char tags-start)
  10341. (skip-chars-backward " \t")
  10342. (point)))
  10343. (new (max (if (>= to-col 0) to-col
  10344. (- (abs to-col) (string-width (match-string 1))))
  10345. ;; Introduce at least one space after the heading
  10346. ;; or the stars.
  10347. (save-excursion
  10348. (goto-char blank-start)
  10349. (1+ (current-column)))))
  10350. (current
  10351. (save-excursion (goto-char tags-start) (current-column)))
  10352. (origin (point-marker))
  10353. (column (current-column))
  10354. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10355. (when (/= new current)
  10356. (delete-region blank-start tags-start)
  10357. (goto-char blank-start)
  10358. (let ((indent-tabs-mode nil)) (indent-to new))
  10359. ;; Try to move back to original position. If point was in the
  10360. ;; blanks before the tags, ORIGIN marker is of no use because
  10361. ;; it now points to BLANK-START. Use COLUMN instead.
  10362. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10363. (defun org-set-tags-command (&optional arg)
  10364. "Set the tags for the current visible entry.
  10365. When called with `\\[universal-argument]' prefix argument ARG, \
  10366. realign all tags
  10367. in the current buffer.
  10368. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10369. unconditionally do not
  10370. offer the fast tag selection interface.
  10371. If a region is active, set tags in the region according to the
  10372. setting of `org-loop-over-headlines-in-active-region'.
  10373. This function is for interactive use only;
  10374. in Lisp code use `org-set-tags' instead."
  10375. (interactive "P")
  10376. (let ((org-use-fast-tag-selection
  10377. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10378. (cond
  10379. ((equal '(4) arg) (org-align-tags t))
  10380. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10381. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10382. (org-map-entries
  10383. #'org-set-tags-command
  10384. nil
  10385. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10386. 'region-start-level
  10387. 'region)
  10388. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10389. (t
  10390. (save-excursion
  10391. (org-back-to-heading)
  10392. (let* ((all-tags (org-get-tags))
  10393. (table (setq org-last-tags-completion-table
  10394. (org--tag-add-to-alist
  10395. (and org-complete-tags-always-offer-all-agenda-tags
  10396. (org-global-tags-completion-table
  10397. (org-agenda-files)))
  10398. (or org-current-tag-alist (org-get-buffer-tags)))))
  10399. (current-tags
  10400. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10401. all-tags))
  10402. (inherited-tags
  10403. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10404. all-tags))
  10405. (tags
  10406. (replace-regexp-in-string
  10407. ;; Ignore all forbidden characters in tags.
  10408. "[^[:alnum:]_@#%]+" ":"
  10409. (if (or (eq t org-use-fast-tag-selection)
  10410. (and org-use-fast-tag-selection
  10411. (delq nil (mapcar #'cdr table))))
  10412. (org-fast-tag-selection
  10413. current-tags
  10414. inherited-tags
  10415. table
  10416. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10417. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10418. (crm-separator "[ \t]*:[ \t]*"))
  10419. (mapconcat #'identity
  10420. (completing-read-multiple
  10421. "Tags: "
  10422. org-last-tags-completion-table
  10423. nil nil (org-make-tag-string current-tags)
  10424. 'org-tags-history)
  10425. ":"))))))
  10426. (org-set-tags tags)))))
  10427. ;; `save-excursion' may not replace the point at the right
  10428. ;; position.
  10429. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10430. (looking-at-p " "))
  10431. (forward-char))))
  10432. (defun org-align-tags (&optional all)
  10433. "Align tags in current entry.
  10434. When optional argument ALL is non-nil, align all tags in the
  10435. visible part of the buffer."
  10436. (let ((get-indent-column
  10437. (lambda ()
  10438. (let ((offset (if (bound-and-true-p org-indent-mode)
  10439. (* (1- org-indent-indentation-per-level)
  10440. (1- (org-current-level)))
  10441. 0)))
  10442. (+ org-tags-column
  10443. (if (> org-tags-column 0) (- offset) offset))))))
  10444. (if (and (not all) (org-at-heading-p))
  10445. (org--align-tags-here (funcall get-indent-column))
  10446. (save-excursion
  10447. (if all
  10448. (progn
  10449. (goto-char (point-min))
  10450. (while (re-search-forward org-tag-line-re nil t)
  10451. (org--align-tags-here (funcall get-indent-column))))
  10452. (org-back-to-heading t)
  10453. (org--align-tags-here (funcall get-indent-column)))))))
  10454. (defun org-set-tags (tags)
  10455. "Set the tags of the current entry to TAGS, replacing current tags.
  10456. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10457. If TAGS is nil or the empty string, all tags are removed.
  10458. This function assumes point is on a headline."
  10459. (org-with-wide-buffer
  10460. (org-fold-core-ignore-modifications
  10461. (let ((tags (pcase tags
  10462. ((pred listp) tags)
  10463. ((pred stringp) (split-string (org-trim tags) ":" t))
  10464. (_ (error "Invalid tag specification: %S" tags))))
  10465. (old-tags (org-get-tags nil t))
  10466. (tags-change? nil))
  10467. (when (functionp org-tags-sort-function)
  10468. (setq tags (sort tags org-tags-sort-function)))
  10469. (setq tags-change? (not (equal tags old-tags)))
  10470. (when tags-change?
  10471. ;; Delete previous tags and any trailing white space.
  10472. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10473. (line-end-position)))
  10474. (skip-chars-backward " \t")
  10475. (delete-region (point) (line-end-position))
  10476. ;; Deleting white spaces may break an otherwise empty headline.
  10477. ;; Re-introduce one space in this case.
  10478. (unless (org-at-heading-p) (insert " "))
  10479. (when tags
  10480. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10481. ;; When text is being inserted on an invisible region
  10482. ;; boundary, it can be inadvertently sucked into
  10483. ;; invisibility.
  10484. (unless (org-invisible-p (line-beginning-position))
  10485. (org-fold-region (point) (line-end-position) nil 'outline))))
  10486. ;; Align tags, if any.
  10487. (when tags (org-align-tags))
  10488. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10489. (defun org-change-tag-in-region (beg end tag off)
  10490. "Add or remove TAG for each entry in the region.
  10491. This works in the agenda, and also in an Org buffer."
  10492. (interactive
  10493. (list (region-beginning) (region-end)
  10494. (let ((org-last-tags-completion-table
  10495. (if (derived-mode-p 'org-mode)
  10496. (org--tag-add-to-alist
  10497. (org-get-buffer-tags)
  10498. (org-global-tags-completion-table))
  10499. (org-global-tags-completion-table))))
  10500. (completing-read
  10501. "Tag: " org-last-tags-completion-table nil nil nil
  10502. 'org-tags-history))
  10503. (progn
  10504. (message "[s]et or [r]emove? ")
  10505. (equal (read-char-exclusive) ?r))))
  10506. (deactivate-mark)
  10507. (let ((agendap (equal major-mode 'org-agenda-mode))
  10508. l1 l2 m buf pos newhead (cnt 0))
  10509. (goto-char end)
  10510. (setq l2 (1- (org-current-line)))
  10511. (goto-char beg)
  10512. (setq l1 (org-current-line))
  10513. (cl-loop for l from l1 to l2 do
  10514. (org-goto-line l)
  10515. (setq m (get-text-property (point) 'org-hd-marker))
  10516. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10517. (and agendap m))
  10518. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10519. pos (if agendap m (point)))
  10520. (with-current-buffer buf
  10521. (save-excursion
  10522. (save-restriction
  10523. (goto-char pos)
  10524. (setq cnt (1+ cnt))
  10525. (org-toggle-tag tag (if off 'off 'on))
  10526. (setq newhead (org-get-heading)))))
  10527. (and agendap (org-agenda-change-all-lines newhead m))))
  10528. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10529. (defun org-tags-completion-function (string _predicate &optional flag)
  10530. "Complete tag STRING.
  10531. FLAG specifies the type of completion operation to perform. This
  10532. function is passed as a collection function to `completing-read',
  10533. which see."
  10534. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10535. (confirm (lambda (x) (stringp (car x))))
  10536. (prefix ""))
  10537. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10538. (setq prefix (match-string 1 string))
  10539. (setq string (match-string 2 string)))
  10540. (pcase flag
  10541. (`t (all-completions string org-last-tags-completion-table confirm))
  10542. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10543. (`nil
  10544. (pcase (try-completion string org-last-tags-completion-table confirm)
  10545. ((and completion (pred stringp))
  10546. (concat prefix
  10547. completion
  10548. (if (and org-add-colon-after-tag-completion
  10549. (assoc completion org-last-tags-completion-table))
  10550. ":"
  10551. "")))
  10552. (completion completion)))
  10553. (_ nil))))
  10554. (defun org-fast-tag-insert (kwd tags face &optional end)
  10555. "Insert KWD, and the TAGS, the latter with face FACE.
  10556. Also insert END."
  10557. (insert (format "%-12s" (concat kwd ":"))
  10558. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10559. (or end "")))
  10560. (defun org-fast-tag-show-exit (flag)
  10561. (save-excursion
  10562. (org-goto-line 3)
  10563. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10564. (replace-match ""))
  10565. (when flag
  10566. (end-of-line 1)
  10567. (org-move-to-column (- (window-width) 19) t)
  10568. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10569. (defun org-set-current-tags-overlay (current prefix)
  10570. "Add an overlay to CURRENT tag with PREFIX."
  10571. (let ((s (org-make-tag-string current)))
  10572. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10573. (org-overlay-display org-tags-overlay (concat prefix s))))
  10574. (defvar org-last-tag-selection-key nil)
  10575. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10576. "Fast tag selection with single keys.
  10577. CURRENT is the current list of tags in the headline, INHERITED is the
  10578. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10579. possibly with grouping information. TODO-TABLE is a similar table with
  10580. TODO keywords, should these have keys assigned to them.
  10581. If the keys are nil, a-z are automatically assigned.
  10582. Returns the new tags string, or nil to not change the current settings."
  10583. (let* ((fulltable (append table todo-table))
  10584. (maxlen (if (null fulltable) 0
  10585. (apply #'max
  10586. (mapcar (lambda (x)
  10587. (if (stringp (car x)) (string-width (car x))
  10588. 0))
  10589. fulltable))))
  10590. (buf (current-buffer))
  10591. (expert (eq org-fast-tag-selection-single-key 'expert))
  10592. (tab-tags nil)
  10593. (fwidth (+ maxlen 3 1 3))
  10594. (ncol (/ (- (window-width) 4) fwidth))
  10595. (i-face 'org-done)
  10596. (c-face 'org-todo)
  10597. tg cnt e c char c1 c2 ntable tbl rtn
  10598. ov-start ov-end ov-prefix
  10599. (exit-after-next org-fast-tag-selection-single-key)
  10600. (done-keywords org-done-keywords)
  10601. groups ingroup intaggroup)
  10602. (save-excursion
  10603. (beginning-of-line)
  10604. (if (looking-at org-tag-line-re)
  10605. (setq ov-start (match-beginning 1)
  10606. ov-end (match-end 1)
  10607. ov-prefix "")
  10608. (setq ov-start (1- (point-at-eol))
  10609. ov-end (1+ ov-start))
  10610. (skip-chars-forward "^\n\r")
  10611. (setq ov-prefix
  10612. (concat
  10613. (buffer-substring (1- (point)) (point))
  10614. (if (> (current-column) org-tags-column)
  10615. " "
  10616. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10617. (move-overlay org-tags-overlay ov-start ov-end)
  10618. (save-excursion
  10619. (save-window-excursion
  10620. (if expert
  10621. (set-buffer (get-buffer-create " *Org tags*"))
  10622. (delete-other-windows)
  10623. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10624. (org-switch-to-buffer-other-window " *Org tags*"))
  10625. (erase-buffer)
  10626. (setq-local org-done-keywords done-keywords)
  10627. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10628. (org-fast-tag-insert "Current" current c-face "\n\n")
  10629. (org-fast-tag-show-exit exit-after-next)
  10630. (org-set-current-tags-overlay current ov-prefix)
  10631. (setq tbl fulltable char ?a cnt 0)
  10632. (while (setq e (pop tbl))
  10633. (cond
  10634. ((eq (car e) :startgroup)
  10635. (push '() groups) (setq ingroup t)
  10636. (unless (zerop cnt)
  10637. (setq cnt 0)
  10638. (insert "\n"))
  10639. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10640. ((eq (car e) :endgroup)
  10641. (setq ingroup nil cnt 0)
  10642. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10643. ((eq (car e) :startgrouptag)
  10644. (setq intaggroup t)
  10645. (unless (zerop cnt)
  10646. (setq cnt 0)
  10647. (insert "\n"))
  10648. (insert "[ "))
  10649. ((eq (car e) :endgrouptag)
  10650. (setq intaggroup nil cnt 0)
  10651. (insert "]\n"))
  10652. ((equal e '(:newline))
  10653. (unless (zerop cnt)
  10654. (setq cnt 0)
  10655. (insert "\n")
  10656. (setq e (car tbl))
  10657. (while (equal (car tbl) '(:newline))
  10658. (insert "\n")
  10659. (setq tbl (cdr tbl)))))
  10660. ((equal e '(:grouptags)) (insert " : "))
  10661. (t
  10662. (setq tg (copy-sequence (car e)) c2 nil)
  10663. (if (cdr e)
  10664. (setq c (cdr e))
  10665. ;; automatically assign a character.
  10666. (setq c1 (string-to-char
  10667. (downcase (substring
  10668. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10669. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10670. (while (or (rassoc char ntable) (rassoc char table))
  10671. (setq char (1+ char)))
  10672. (setq c2 c1))
  10673. (setq c (or c2 char)))
  10674. (when ingroup (push tg (car groups)))
  10675. (setq tg (org-add-props tg nil 'face
  10676. (cond
  10677. ((not (assoc tg table))
  10678. (org-get-todo-face tg))
  10679. ((member tg current) c-face)
  10680. ((member tg inherited) i-face))))
  10681. (when (equal (caar tbl) :grouptags)
  10682. (org-add-props tg nil 'face 'org-tag-group))
  10683. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10684. (insert "[" c "] " tg (make-string
  10685. (- fwidth 4 (length tg)) ?\ ))
  10686. (push (cons tg c) ntable)
  10687. (when (= (cl-incf cnt) ncol)
  10688. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10689. (insert "\n")
  10690. (when (or ingroup intaggroup) (insert " ")))
  10691. (setq cnt 0)))))
  10692. (setq ntable (nreverse ntable))
  10693. (insert "\n")
  10694. (goto-char (point-min))
  10695. (unless expert (org-fit-window-to-buffer))
  10696. (setq rtn
  10697. (catch 'exit
  10698. (while t
  10699. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10700. (if (not groups) "no " "")
  10701. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10702. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10703. (setq org-last-tag-selection-key c)
  10704. (cond
  10705. ((= c ?\r) (throw 'exit t))
  10706. ((= c ?!)
  10707. (setq groups (not groups))
  10708. (goto-char (point-min))
  10709. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10710. ((= c ?\C-c)
  10711. (if (not expert)
  10712. (org-fast-tag-show-exit
  10713. (setq exit-after-next (not exit-after-next)))
  10714. (setq expert nil)
  10715. (delete-other-windows)
  10716. (set-window-buffer (split-window-vertically) " *Org tags*")
  10717. (org-switch-to-buffer-other-window " *Org tags*")
  10718. (org-fit-window-to-buffer)))
  10719. ((or (= c ?\C-g)
  10720. (and (= c ?q) (not (rassoc c ntable))))
  10721. (delete-overlay org-tags-overlay)
  10722. (setq quit-flag t))
  10723. ((= c ?\ )
  10724. (setq current nil)
  10725. (when exit-after-next (setq exit-after-next 'now)))
  10726. ((= c ?\t)
  10727. (condition-case nil
  10728. (unless tab-tags
  10729. (setq tab-tags
  10730. (delq nil
  10731. (mapcar (lambda (x)
  10732. (let ((item (car-safe x)))
  10733. (and (stringp item)
  10734. (list item))))
  10735. (org--tag-add-to-alist
  10736. (with-current-buffer buf
  10737. (org-get-buffer-tags))
  10738. table))))))
  10739. (setq tg (completing-read "Tag: " tab-tags))
  10740. (when (string-match "\\S-" tg)
  10741. (cl-pushnew (list tg) tab-tags :test #'equal)
  10742. (if (member tg current)
  10743. (setq current (delete tg current))
  10744. (push tg current)))
  10745. (when exit-after-next (setq exit-after-next 'now)))
  10746. ((setq e (rassoc c todo-table) tg (car e))
  10747. (with-current-buffer buf
  10748. (save-excursion (org-todo tg)))
  10749. (when exit-after-next (setq exit-after-next 'now)))
  10750. ((setq e (rassoc c ntable) tg (car e))
  10751. (if (member tg current)
  10752. (setq current (delete tg current))
  10753. (cl-loop for g in groups do
  10754. (when (member tg g)
  10755. (dolist (x g) (setq current (delete x current)))))
  10756. (push tg current))
  10757. (when exit-after-next (setq exit-after-next 'now))))
  10758. ;; Create a sorted list
  10759. (setq current
  10760. (sort current
  10761. (lambda (a b)
  10762. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10763. (when (eq exit-after-next 'now) (throw 'exit t))
  10764. (goto-char (point-min))
  10765. (beginning-of-line 2)
  10766. (delete-region (point) (point-at-eol))
  10767. (org-fast-tag-insert "Current" current c-face)
  10768. (org-set-current-tags-overlay current ov-prefix)
  10769. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10770. (while (re-search-forward tag-re nil t)
  10771. (let ((tag (match-string 1)))
  10772. (add-text-properties
  10773. (match-beginning 1) (match-end 1)
  10774. (list 'face
  10775. (cond
  10776. ((member tag current) c-face)
  10777. ((member tag inherited) i-face)
  10778. (t 'default)))))))
  10779. (goto-char (point-min)))))
  10780. (delete-overlay org-tags-overlay)
  10781. (if rtn
  10782. (mapconcat 'identity current ":")
  10783. nil)))))
  10784. (defun org-make-tag-string (tags)
  10785. "Return string associated to TAGS.
  10786. TAGS is a list of strings."
  10787. (if (null tags) ""
  10788. (format ":%s:" (mapconcat #'identity tags ":"))))
  10789. (defun org--get-local-tags ()
  10790. "Return list of tags for the current headline.
  10791. Assume point is at the beginning of the headline."
  10792. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10793. (cached-tags (org-element-property :tags cached)))
  10794. (if cached
  10795. ;; If we do not explicitly copy the result, reference would
  10796. ;; be returned and cache element might be modified directly.
  10797. (mapcar #'copy-sequence cached-tags)
  10798. ;; Parse tags manually.
  10799. (and (looking-at org-tag-line-re)
  10800. (split-string (match-string-no-properties 2) ":" t)))))
  10801. (defun org-get-tags (&optional pos-or-element local)
  10802. "Get the list of tags specified in the current headline.
  10803. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10804. POS.
  10805. According to `org-use-tag-inheritance', tags may be inherited
  10806. from parent headlines, and from the whole document, through
  10807. `org-file-tags'. In this case, the returned list of tags
  10808. contains tags in this order: file tags, tags inherited from
  10809. parent headlines, local tags. If a tag appears multiple times,
  10810. only the most local tag is returned.
  10811. However, when optional argument LOCAL is non-nil, only return
  10812. tags specified at the headline.
  10813. Inherited tags have the `inherited' text property."
  10814. (save-match-data
  10815. (if (and org-trust-scanner-tags
  10816. (or (not pos-or-element) (eq pos-or-element (point)))
  10817. (not local))
  10818. org-scanner-tags
  10819. (org-with-point-at (unless (org-element-type pos-or-element)
  10820. (or pos-or-element (point)))
  10821. (unless (or (org-element-type pos-or-element)
  10822. (org-before-first-heading-p))
  10823. (org-back-to-heading t))
  10824. (let ((ltags (if (org-element-type pos-or-element)
  10825. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10826. (org--get-local-tags)))
  10827. itags)
  10828. (if (or local (not org-use-tag-inheritance)) ltags
  10829. (let ((cached (and (org-element--cache-active-p)
  10830. (if (org-element-type pos-or-element)
  10831. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10832. (org-element-at-point nil 'cached)))))
  10833. (if cached
  10834. (while (setq cached (org-element-property :parent cached))
  10835. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10836. ;; If we do explicitly copy the result, reference would
  10837. ;; be returned and cache element might be modified directly.
  10838. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10839. itags)))
  10840. (while (org-up-heading-safe)
  10841. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10842. (org--get-local-tags))
  10843. itags)))))
  10844. (setq itags (append org-file-tags itags))
  10845. (nreverse
  10846. (delete-dups
  10847. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10848. (defun org-get-buffer-tags ()
  10849. "Get a table of all tags used in the buffer, for completion."
  10850. (if (org-element--cache-active-p)
  10851. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10852. ;; search.
  10853. (let ((hashed (make-hash-table :test #'equal)))
  10854. (org-element-cache-map
  10855. (lambda (el)
  10856. (dolist (tag (org-element-property :tags el))
  10857. (puthash (list tag) t hashed))))
  10858. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10859. (hash-table-keys hashed))
  10860. (org-with-point-at 1
  10861. (let (tags)
  10862. (while (re-search-forward org-tag-line-re nil t)
  10863. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10864. tags)))
  10865. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10866. ;;;; The mapping API
  10867. (defvar org-agenda-skip-comment-trees)
  10868. (defvar org-agenda-skip-function)
  10869. (defun org-map-entries (func &optional match scope &rest skip)
  10870. "Call FUNC at each headline selected by MATCH in SCOPE.
  10871. FUNC is a function or a Lisp form. The function will be called without
  10872. arguments, with the cursor positioned at the beginning of the headline.
  10873. The return values of all calls to the function will be collected and
  10874. returned as a list.
  10875. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10876. does not need to preserve point. After evaluation, the cursor will be
  10877. moved to the end of the line (presumably of the headline of the
  10878. processed entry) and search continues from there. Under some
  10879. circumstances, this may not produce the wanted results. For example,
  10880. if you have removed (e.g. archived) the current (sub)tree it could
  10881. mean that the next entry will be skipped entirely. In such cases, you
  10882. can specify the position from where search should continue by making
  10883. FUNC set the variable `org-map-continue-from' to the desired buffer
  10884. position.
  10885. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10886. Only headlines that are matched by this query will be considered during
  10887. the iteration. When MATCH is nil or t, all headlines will be
  10888. visited by the iteration.
  10889. SCOPE determines the scope of this command. It can be any of:
  10890. nil The current buffer, respecting the restriction if any
  10891. tree The subtree started with the entry at point
  10892. region The entries within the active region, if any
  10893. region-start-level
  10894. The entries within the active region, but only those at
  10895. the same level than the first one.
  10896. file The current buffer, without restriction
  10897. file-with-archives
  10898. The current buffer, and any archives associated with it
  10899. agenda All agenda files
  10900. agenda-with-archives
  10901. All agenda files with any archive files associated with them
  10902. \(file1 file2 ...)
  10903. If this is a list, all files in the list will be scanned
  10904. The remaining args are treated as settings for the skipping facilities of
  10905. the scanner. The following items can be given here:
  10906. archive skip trees with the archive tag
  10907. comment skip trees with the COMMENT keyword
  10908. function or Emacs Lisp form:
  10909. will be used as value for `org-agenda-skip-function', so
  10910. whenever the function returns a position, FUNC will not be
  10911. called for that entry and search will continue from the
  10912. position returned
  10913. If your function needs to retrieve the tags including inherited tags
  10914. at the *current* entry, you can use the value of the variable
  10915. `org-scanner-tags' which will be much faster than getting the value
  10916. with `org-get-tags'. If your function gets properties with
  10917. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10918. to t around the call to `org-entry-properties' to get the same speedup.
  10919. Note that if your function moves around to retrieve tags and properties at
  10920. a *different* entry, you cannot use these techniques."
  10921. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10922. (not (org-region-active-p)))
  10923. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10924. (org-agenda-skip-archived-trees (memq 'archive skip))
  10925. (org-agenda-skip-comment-trees (memq 'comment skip))
  10926. (org-agenda-skip-function
  10927. (car (org-delete-all '(comment archive) skip)))
  10928. (org-tags-match-list-sublevels t)
  10929. (start-level (eq scope 'region-start-level))
  10930. matcher res
  10931. org-todo-keywords-for-agenda
  10932. org-done-keywords-for-agenda
  10933. org-todo-keyword-alist-for-agenda
  10934. org-tag-alist-for-agenda
  10935. org--matcher-tags-todo-only)
  10936. (cond
  10937. ((eq match t) (setq matcher t))
  10938. ((eq match nil) (setq matcher t))
  10939. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10940. (save-excursion
  10941. (save-restriction
  10942. (cond ((eq scope 'tree)
  10943. (org-back-to-heading t)
  10944. (org-narrow-to-subtree)
  10945. (setq scope nil))
  10946. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  10947. (org-region-active-p))
  10948. ;; If needed, set start-level to a string like "2"
  10949. (when start-level
  10950. (save-excursion
  10951. (goto-char (region-beginning))
  10952. (unless (org-at-heading-p) (outline-next-heading))
  10953. (setq start-level (org-current-level))))
  10954. (narrow-to-region (region-beginning)
  10955. (save-excursion
  10956. (goto-char (region-end))
  10957. (unless (and (bolp) (org-at-heading-p))
  10958. (outline-next-heading))
  10959. (point)))
  10960. (setq scope nil)))
  10961. (if (not scope)
  10962. (progn
  10963. (org-agenda-prepare-buffers
  10964. (and buffer-file-name (list buffer-file-name)))
  10965. (setq res
  10966. (org-scan-tags
  10967. func matcher org--matcher-tags-todo-only start-level)))
  10968. ;; Get the right scope
  10969. (cond
  10970. ((and scope (listp scope) (symbolp (car scope)))
  10971. (setq scope (eval scope t)))
  10972. ((eq scope 'agenda)
  10973. (setq scope (org-agenda-files t)))
  10974. ((eq scope 'agenda-with-archives)
  10975. (setq scope (org-agenda-files t))
  10976. (setq scope (org-add-archive-files scope)))
  10977. ((eq scope 'file)
  10978. (setq scope (and buffer-file-name (list buffer-file-name))))
  10979. ((eq scope 'file-with-archives)
  10980. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  10981. (org-agenda-prepare-buffers scope)
  10982. (dolist (file scope)
  10983. (with-current-buffer (org-find-base-buffer-visiting file)
  10984. (org-with-wide-buffer
  10985. (goto-char (point-min))
  10986. (setq res
  10987. (append
  10988. res
  10989. (org-scan-tags
  10990. func matcher org--matcher-tags-todo-only)))))))))
  10991. res)))
  10992. ;;; Properties API
  10993. (defconst org-special-properties
  10994. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  10995. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  10996. "The special properties valid in Org mode.
  10997. These are properties that are not defined in the property drawer,
  10998. but in some other way.")
  10999. (defconst org-default-properties
  11000. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11001. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11002. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11003. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11004. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11005. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11006. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11007. "Some properties that are used by Org mode for various purposes.
  11008. Being in this list makes sure that they are offered for completion.")
  11009. (defun org--valid-property-p (property)
  11010. "Non-nil when string PROPERTY is a valid property name."
  11011. (not
  11012. (or (equal property "")
  11013. (string-match-p "\\s-" property))))
  11014. (defun org--update-property-plist (key val props)
  11015. "Associate KEY to VAL in alist PROPS.
  11016. Modifications are made by side-effect. Return new alist."
  11017. (let* ((appending (string= (substring key -1) "+"))
  11018. (key (if appending (substring key 0 -1) key))
  11019. (old (assoc-string key props t)))
  11020. (if (not old) (cons (cons key val) props)
  11021. (setcdr old (if appending (concat (cdr old) " " val) val))
  11022. props)))
  11023. (defun org-get-property-block (&optional beg force)
  11024. "Return the (beg . end) range of the body of the property drawer.
  11025. BEG is the beginning of the current subtree or the beginning of
  11026. the document if before the first headline. If it is not given,
  11027. it will be found. If the drawer does not exist, create it if
  11028. FORCE is non-nil, or return nil."
  11029. (org-with-wide-buffer
  11030. (let ((beg (cond (beg (goto-char beg))
  11031. ((or (not (featurep 'org-inlinetask))
  11032. (org-inlinetask-in-task-p))
  11033. (org-back-to-heading-or-point-min t) (point))
  11034. (t (org-with-limited-levels
  11035. (org-back-to-heading-or-point-min t))
  11036. (point)))))
  11037. ;; Move point to its position according to its positional rules.
  11038. (cond ((org-before-first-heading-p)
  11039. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11040. (t (forward-line)
  11041. (when (looking-at-p org-planning-line-re) (forward-line))))
  11042. (cond ((looking-at org-property-drawer-re)
  11043. (forward-line)
  11044. (cons (point) (progn (goto-char (match-end 0))
  11045. (line-beginning-position))))
  11046. (force
  11047. (goto-char beg)
  11048. (org-insert-property-drawer)
  11049. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11050. (line-beginning-position))))
  11051. (cons pos pos)))))))
  11052. (defun org-at-property-drawer-p ()
  11053. "Non-nil when point is at the first line of a property drawer."
  11054. (org-with-wide-buffer
  11055. (beginning-of-line)
  11056. (and (looking-at org-property-drawer-re)
  11057. (or (bobp)
  11058. (progn
  11059. (forward-line -1)
  11060. (cond ((org-at-heading-p))
  11061. ((looking-at org-planning-line-re)
  11062. (forward-line -1)
  11063. (org-at-heading-p))
  11064. ((looking-at org-comment-regexp)
  11065. (forward-line -1)
  11066. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11067. (forward-line -1))
  11068. (looking-at org-comment-regexp))
  11069. (t nil)))))))
  11070. (defun org-at-property-p ()
  11071. "Non-nil when point is inside a property drawer.
  11072. See `org-property-re' for match data, if applicable."
  11073. (save-excursion
  11074. (beginning-of-line)
  11075. (and (looking-at org-property-re)
  11076. (let ((property-drawer (save-match-data (org-get-property-block))))
  11077. (and property-drawer
  11078. (>= (point) (car property-drawer))
  11079. (< (point) (cdr property-drawer)))))))
  11080. (defun org-property-action ()
  11081. "Do an action on properties."
  11082. (interactive)
  11083. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11084. (let ((c (read-char-exclusive)))
  11085. (cl-case c
  11086. (?s (call-interactively #'org-set-property))
  11087. (?d (call-interactively #'org-delete-property))
  11088. (?D (call-interactively #'org-delete-property-globally))
  11089. (?c (call-interactively #'org-compute-property-at-point))
  11090. (otherwise (user-error "No such property action %c" c)))))
  11091. (defun org-inc-effort ()
  11092. "Increment the value of the effort property in the current entry."
  11093. (interactive)
  11094. (org-set-effort t))
  11095. (defvar org-clock-effort) ; Defined in org-clock.el.
  11096. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11097. (defun org-set-effort (&optional increment value)
  11098. "Set the effort property of the current entry.
  11099. If INCREMENT is non-nil, set the property to the next allowed
  11100. value. Otherwise, if optional argument VALUE is provided, use
  11101. it. Eventually, prompt for the new value if none of the previous
  11102. variables is set."
  11103. (interactive "P")
  11104. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11105. (current (org-entry-get nil org-effort-property))
  11106. (value
  11107. (cond
  11108. (increment
  11109. (unless allowed (user-error "Allowed effort values are not set"))
  11110. (or (cl-caadr (member (list current) allowed))
  11111. (user-error "Unknown value %S among allowed values" current)))
  11112. (value
  11113. (if (stringp value) value
  11114. (error "Invalid effort value: %S" value)))
  11115. (t
  11116. (let ((must-match
  11117. (and allowed
  11118. (not (get-text-property 0 'org-unrestricted
  11119. (caar allowed))))))
  11120. (completing-read "Effort: " allowed nil must-match))))))
  11121. ;; Test whether the value can be interpreted as a duration before
  11122. ;; inserting it in the buffer:
  11123. (org-duration-to-minutes value)
  11124. ;; Maybe update the effort value:
  11125. (unless (equal current value)
  11126. (org-entry-put nil org-effort-property value))
  11127. (unless (org-element--cache-active-p)
  11128. (org-refresh-property '((effort . identity)
  11129. (effort-minutes . org-duration-to-minutes))
  11130. value))
  11131. (when (equal (org-get-heading t t t t)
  11132. (bound-and-true-p org-clock-current-task))
  11133. (setq org-clock-effort value)
  11134. (org-clock-update-mode-line))
  11135. (message "%s is now %s" org-effort-property value)))
  11136. (defun org-entry-properties (&optional pom which)
  11137. "Get all properties of the current entry.
  11138. When POM is a buffer position, get all properties from the entry
  11139. there instead.
  11140. This includes the TODO keyword, the tags, time strings for
  11141. deadline, scheduled, and clocking, and any additional properties
  11142. defined in the entry.
  11143. If WHICH is nil or `all', get all properties. If WHICH is
  11144. `special' or `standard', only get that subclass. If WHICH is
  11145. a string, only get that property.
  11146. Return value is an alist. Keys are properties, as upcased
  11147. strings."
  11148. (org-with-point-at pom
  11149. (when (and (derived-mode-p 'org-mode)
  11150. (org-back-to-heading-or-point-min t))
  11151. (catch 'exit
  11152. (let* ((beg (point))
  11153. (specific (and (stringp which) (upcase which)))
  11154. (which (cond ((not specific) which)
  11155. ((member specific org-special-properties) 'special)
  11156. (t 'standard)))
  11157. props)
  11158. ;; Get the special properties, like TODO and TAGS.
  11159. (when (memq which '(nil all special))
  11160. (when (or (not specific) (string= specific "CLOCKSUM"))
  11161. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11162. (when clocksum
  11163. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11164. props)))
  11165. (when specific (throw 'exit props)))
  11166. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11167. (let ((clocksumt (get-text-property (point)
  11168. :org-clock-minutes-today)))
  11169. (when clocksumt
  11170. (push (cons "CLOCKSUM_T"
  11171. (org-duration-from-minutes clocksumt))
  11172. props)))
  11173. (when specific (throw 'exit props)))
  11174. (when (or (not specific) (string= specific "ITEM"))
  11175. (let ((case-fold-search nil))
  11176. (when (looking-at org-complex-heading-regexp)
  11177. (push (cons "ITEM"
  11178. (let ((title (match-string-no-properties 4)))
  11179. (if (org-string-nw-p title)
  11180. (org-remove-tabs title)
  11181. "")))
  11182. props)))
  11183. (when specific (throw 'exit props)))
  11184. (when (or (not specific) (string= specific "TODO"))
  11185. (let ((case-fold-search nil))
  11186. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11187. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11188. (when specific (throw 'exit props)))
  11189. (when (or (not specific) (string= specific "PRIORITY"))
  11190. (push (cons "PRIORITY"
  11191. (if (looking-at org-priority-regexp)
  11192. (match-string-no-properties 2)
  11193. (char-to-string org-priority-default)))
  11194. props)
  11195. (when specific (throw 'exit props)))
  11196. (when (or (not specific) (string= specific "FILE"))
  11197. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11198. props)
  11199. (when specific (throw 'exit props)))
  11200. (when (or (not specific) (string= specific "TAGS"))
  11201. (let ((tags (org-get-tags nil t)))
  11202. (when tags
  11203. (push (cons "TAGS" (org-make-tag-string tags))
  11204. props)))
  11205. (when specific (throw 'exit props)))
  11206. (when (or (not specific) (string= specific "ALLTAGS"))
  11207. (let ((tags (org-get-tags)))
  11208. (when tags
  11209. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11210. props)))
  11211. (when specific (throw 'exit props)))
  11212. (when (or (not specific) (string= specific "BLOCKED"))
  11213. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11214. (when specific (throw 'exit props)))
  11215. (when (or (not specific)
  11216. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11217. (forward-line)
  11218. (when (looking-at-p org-planning-line-re)
  11219. (end-of-line)
  11220. (let ((bol (line-beginning-position))
  11221. ;; Backward compatibility: time keywords used to
  11222. ;; be configurable (before 8.3). Make sure we
  11223. ;; get the correct keyword.
  11224. (key-assoc `(("CLOSED" . ,org-closed-string)
  11225. ("DEADLINE" . ,org-deadline-string)
  11226. ("SCHEDULED" . ,org-scheduled-string))))
  11227. (dolist (pair (if specific (list (assoc specific key-assoc))
  11228. key-assoc))
  11229. (save-excursion
  11230. (when (search-backward (cdr pair) bol t)
  11231. (goto-char (match-end 0))
  11232. (skip-chars-forward " \t")
  11233. (and (looking-at org-ts-regexp-both)
  11234. (push (cons (car pair)
  11235. (match-string-no-properties 0))
  11236. props)))))))
  11237. (when specific (throw 'exit props)))
  11238. (when (or (not specific)
  11239. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11240. (let ((find-ts
  11241. (lambda (end ts)
  11242. ;; Fix next time-stamp before END. TS is the
  11243. ;; list of time-stamps found so far.
  11244. (let ((ts ts)
  11245. (regexp (cond
  11246. ((string= specific "TIMESTAMP")
  11247. org-ts-regexp)
  11248. ((string= specific "TIMESTAMP_IA")
  11249. org-ts-regexp-inactive)
  11250. ((assoc "TIMESTAMP_IA" ts)
  11251. org-ts-regexp)
  11252. ((assoc "TIMESTAMP" ts)
  11253. org-ts-regexp-inactive)
  11254. (t org-ts-regexp-both))))
  11255. (catch 'next
  11256. (while (re-search-forward regexp end t)
  11257. (backward-char)
  11258. (let ((object (org-element-context)))
  11259. ;; Accept to match timestamps in node
  11260. ;; properties, too.
  11261. (when (memq (org-element-type object)
  11262. '(node-property timestamp))
  11263. (let ((type
  11264. (org-element-property :type object)))
  11265. (cond
  11266. ((and (memq type '(active active-range))
  11267. (not (equal specific "TIMESTAMP_IA")))
  11268. (unless (assoc "TIMESTAMP" ts)
  11269. (push (cons "TIMESTAMP"
  11270. (org-element-property
  11271. :raw-value object))
  11272. ts)
  11273. (when specific (throw 'exit ts))))
  11274. ((and (memq type '(inactive inactive-range))
  11275. (not (string= specific "TIMESTAMP")))
  11276. (unless (assoc "TIMESTAMP_IA" ts)
  11277. (push (cons "TIMESTAMP_IA"
  11278. (org-element-property
  11279. :raw-value object))
  11280. ts)
  11281. (when specific (throw 'exit ts))))))
  11282. ;; Both timestamp types are found,
  11283. ;; move to next part.
  11284. (when (= (length ts) 2) (throw 'next ts)))))
  11285. ts)))))
  11286. (goto-char beg)
  11287. ;; First look for timestamps within headline.
  11288. (let ((ts (funcall find-ts (line-end-position) nil)))
  11289. (if (= (length ts) 2) (setq props (nconc ts props))
  11290. ;; Then find timestamps in the section, skipping
  11291. ;; planning line.
  11292. (let ((end (save-excursion (outline-next-heading))))
  11293. (forward-line)
  11294. (when (looking-at-p org-planning-line-re) (forward-line))
  11295. (setq props (nconc (funcall find-ts end ts) props))))))))
  11296. ;; Get the standard properties, like :PROP:.
  11297. (when (memq which '(nil all standard))
  11298. ;; If we are looking after a specific property, delegate
  11299. ;; to `org-entry-get', which is faster. However, make an
  11300. ;; exception for "CATEGORY", since it can be also set
  11301. ;; through keywords (i.e. #+CATEGORY).
  11302. (if (and specific (not (equal specific "CATEGORY")))
  11303. (let ((value (org-entry-get beg specific nil t)))
  11304. (throw 'exit (and value (list (cons specific value)))))
  11305. (let ((range (org-get-property-block beg)))
  11306. (when range
  11307. (let ((end (cdr range)) seen-base)
  11308. (goto-char (car range))
  11309. ;; Unlike to `org--update-property-plist', we
  11310. ;; handle the case where base values is found
  11311. ;; after its extension. We also forbid standard
  11312. ;; properties to be named as special properties.
  11313. (while (re-search-forward org-property-re end t)
  11314. (let* ((key (upcase (match-string-no-properties 2)))
  11315. (extendp (string-match-p "\\+\\'" key))
  11316. (key-base (if extendp (substring key 0 -1) key))
  11317. (value (match-string-no-properties 3)))
  11318. (cond
  11319. ((member-ignore-case key-base org-special-properties))
  11320. (extendp
  11321. (setq props
  11322. (org--update-property-plist key value props)))
  11323. ((member key seen-base))
  11324. (t (push key seen-base)
  11325. (let ((p (assoc-string key props t)))
  11326. (if p (setcdr p (concat value " " (cdr p)))
  11327. (push (cons key value) props))))))))))))
  11328. (unless (assoc "CATEGORY" props)
  11329. (push (cons "CATEGORY" (org-get-category beg)) props)
  11330. (when (string= specific "CATEGORY") (throw 'exit props)))
  11331. ;; Return value.
  11332. props)))))
  11333. (defun org--property-local-values (property literal-nil &optional element)
  11334. "Return value for PROPERTY in current entry or ELEMENT.
  11335. Value is a list whose car is the base value for PROPERTY and cdr
  11336. a list of accumulated values. Return nil if neither is found in
  11337. the entry. Also return nil when PROPERTY is set to \"nil\",
  11338. unless LITERAL-NIL is non-nil."
  11339. (let ((element (or element
  11340. (and (org-element--cache-active-p)
  11341. (org-element-at-point nil 'cached)))))
  11342. (if element
  11343. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11344. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11345. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11346. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11347. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11348. (value (cons base-value extra-value)))
  11349. (and (not (equal value '(nil))) value))
  11350. (let ((range (org-get-property-block)))
  11351. (when range
  11352. (goto-char (car range))
  11353. (let* ((case-fold-search t)
  11354. (end (cdr range))
  11355. (value
  11356. ;; Base value.
  11357. (save-excursion
  11358. (let ((v (and (re-search-forward
  11359. (org-re-property property nil t) end t)
  11360. (match-string-no-properties 3))))
  11361. (list (if literal-nil v (org-not-nil v)))))))
  11362. ;; Find additional values.
  11363. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11364. (while (re-search-forward property+ end t)
  11365. (push (match-string-no-properties 3) value)))
  11366. ;; Return final values.
  11367. (and (not (equal value '(nil))) (nreverse value))))))))
  11368. (defun org--property-global-or-keyword-value (property literal-nil)
  11369. "Return value for PROPERTY as defined by global properties or by keyword.
  11370. Return value is a string. Return nil if property is not set
  11371. globally or by keyword. Also return nil when PROPERTY is set to
  11372. \"nil\", unless LITERAL-NIL is non-nil."
  11373. (let ((global
  11374. (cdr (or (assoc-string property org-keyword-properties t)
  11375. (assoc-string property org-global-properties t)
  11376. (assoc-string property org-global-properties-fixed t)))))
  11377. (if literal-nil global (org-not-nil global))))
  11378. (defun org-entry-get (pom property &optional inherit literal-nil)
  11379. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11380. If INHERIT is non-nil and the entry does not have the property,
  11381. then also check higher levels of the hierarchy. If INHERIT is
  11382. the symbol `selective', use inheritance only if the setting in
  11383. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11384. If the property is present but empty, the return value is the
  11385. empty string. If the property is not present at all, nil is
  11386. returned. In any other case, return the value as a string.
  11387. Search is case-insensitive.
  11388. If LITERAL-NIL is set, return the string value \"nil\" as
  11389. a string, do not interpret it as the list atom nil. This is used
  11390. for inheritance when a \"nil\" value can supersede a non-nil
  11391. value higher up the hierarchy."
  11392. (org-with-point-at pom
  11393. (cond
  11394. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11395. ;; We need a special property. Use `org-entry-properties' to
  11396. ;; retrieve it, but specify the wanted property.
  11397. (cdr (assoc-string property (org-entry-properties nil property))))
  11398. ((and inherit
  11399. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11400. (org-entry-get-with-inheritance property literal-nil))
  11401. (t
  11402. (let* ((local (org--property-local-values property literal-nil))
  11403. (value (and local (mapconcat #'identity
  11404. (delq nil local)
  11405. (org--property-get-separator property)))))
  11406. (if literal-nil value (org-not-nil value)))))))
  11407. (defun org-property-or-variable-value (var &optional inherit)
  11408. "Check if there is a property fixing the value of VAR.
  11409. If yes, return this value. If not, return the current value of the variable."
  11410. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11411. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11412. (read prop)
  11413. (symbol-value var))))
  11414. (defun org-entry-delete (pom property)
  11415. "Delete PROPERTY from entry at point-or-marker POM.
  11416. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11417. non-nil when a property was removed."
  11418. (org-with-point-at pom
  11419. (pcase (org-get-property-block)
  11420. (`(,begin . ,origin)
  11421. (let* ((end (copy-marker origin))
  11422. (re (org-re-property
  11423. (concat (regexp-quote property) "\\+?") t t)))
  11424. (goto-char begin)
  11425. (while (re-search-forward re end t)
  11426. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11427. ;; If drawer is empty, remove it altogether.
  11428. (when (= begin end)
  11429. (delete-region (line-beginning-position 0)
  11430. (line-beginning-position 2)))
  11431. ;; Return non-nil if some property was removed.
  11432. (prog1 (/= end origin) (set-marker end nil))))
  11433. (_ nil))))
  11434. ;; Multi-values properties are properties that contain multiple values
  11435. ;; These values are assumed to be single words, separated by whitespace.
  11436. (defun org-entry-add-to-multivalued-property (pom property value)
  11437. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11438. (let* ((old (org-entry-get pom property))
  11439. (values (and old (split-string old))))
  11440. (setq value (org-entry-protect-space value))
  11441. (unless (member value values)
  11442. (setq values (append values (list value)))
  11443. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11444. (defun org-entry-remove-from-multivalued-property (pom property value)
  11445. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11446. (let* ((old (org-entry-get pom property))
  11447. (values (and old (split-string old))))
  11448. (setq value (org-entry-protect-space value))
  11449. (when (member value values)
  11450. (setq values (delete value values))
  11451. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11452. (defun org-entry-member-in-multivalued-property (pom property value)
  11453. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11454. (let* ((old (org-entry-get pom property))
  11455. (values (and old (split-string old))))
  11456. (setq value (org-entry-protect-space value))
  11457. (member value values)))
  11458. (defun org-entry-get-multivalued-property (pom property)
  11459. "Return a list of values in a multivalued property."
  11460. (let* ((value (org-entry-get pom property))
  11461. (values (and value (split-string value))))
  11462. (mapcar #'org-entry-restore-space values)))
  11463. (defun org-entry-put-multivalued-property (pom property &rest values)
  11464. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11465. VALUES should be a list of strings. Spaces will be protected."
  11466. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11467. (let* ((value (org-entry-get pom property))
  11468. (values (and value (split-string value))))
  11469. (mapcar #'org-entry-restore-space values)))
  11470. (defun org-entry-protect-space (s)
  11471. "Protect spaces and newline in string S."
  11472. (while (string-match " " s)
  11473. (setq s (replace-match "%20" t t s)))
  11474. (while (string-match "\n" s)
  11475. (setq s (replace-match "%0A" t t s)))
  11476. s)
  11477. (defun org-entry-restore-space (s)
  11478. "Restore spaces and newline in string S."
  11479. (while (string-match "%20" s)
  11480. (setq s (replace-match " " t t s)))
  11481. (while (string-match "%0A" s)
  11482. (setq s (replace-match "\n" t t s)))
  11483. s)
  11484. (defvar org-entry-property-inherited-from (make-marker)
  11485. "Marker pointing to the entry from where a property was inherited.
  11486. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11487. location of the entry where the inheritance search matched. If there was
  11488. no match, the marker will point nowhere.
  11489. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11490. is set.")
  11491. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11492. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11493. The search will stop at the first ancestor which has the property defined.
  11494. If the value found is \"nil\", return nil to show that the property
  11495. should be considered as undefined (this is the meaning of nil here).
  11496. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11497. (move-marker org-entry-property-inherited-from nil)
  11498. (org-with-wide-buffer
  11499. (let (value at-bob-no-heading)
  11500. (catch 'exit
  11501. (let ((element (or element
  11502. (and (org-element--cache-active-p)
  11503. (org-element-at-point nil 'cached))))
  11504. (separator (org--property-get-separator property)))
  11505. (if element
  11506. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11507. (while t
  11508. (let* ((v (org--property-local-values property literal-nil element))
  11509. (v (if (listp v) v (list v))))
  11510. (when v
  11511. (setq value
  11512. (concat (mapconcat #'identity (delq nil v) separator)
  11513. (and value separator)
  11514. value)))
  11515. (cond
  11516. ((car v)
  11517. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11518. (throw 'exit nil))
  11519. ((org-element-property :parent element)
  11520. (setq element (org-element-property :parent element)))
  11521. (t
  11522. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11523. (cond ((not global))
  11524. (value (setq value (concat global separator value)))
  11525. (t (setq value global))))
  11526. (throw 'exit nil))))))
  11527. (while t
  11528. (let ((v (org--property-local-values property literal-nil)))
  11529. (when v
  11530. (setq value
  11531. (concat (mapconcat #'identity (delq nil v) separator)
  11532. (and value separator)
  11533. value)))
  11534. (cond
  11535. ((car v)
  11536. (org-back-to-heading-or-point-min t)
  11537. (move-marker org-entry-property-inherited-from (point))
  11538. (throw 'exit nil))
  11539. ((or (org-up-heading-safe)
  11540. (and (not (bobp))
  11541. (goto-char (point-min))
  11542. nil)
  11543. ;; `org-up-heading-safe' returned nil. We are at low
  11544. ;; level heading or bob. If there is headline
  11545. ;; there, do not try to fetch its properties.
  11546. (and (bobp)
  11547. (not at-bob-no-heading)
  11548. (not (org-at-heading-p))
  11549. (setq at-bob-no-heading t))))
  11550. (t
  11551. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11552. (cond ((not global))
  11553. (value (setq value (concat global separator value)))
  11554. (t (setq value global))))
  11555. (throw 'exit nil))))))))
  11556. (if literal-nil value (org-not-nil value)))))
  11557. (defvar org-property-changed-functions nil
  11558. "Hook called when the value of a property has changed.
  11559. Each hook function should accept two arguments, the name of the property
  11560. and the new value.")
  11561. (defun org-entry-put (pom property value)
  11562. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11563. If the value is nil, it is converted to the empty string. If it
  11564. is not a string, an error is raised. Also raise an error on
  11565. invalid property names.
  11566. PROPERTY can be any regular property (see
  11567. `org-special-properties'). It can also be \"TODO\",
  11568. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11569. For the last two properties, VALUE may have any of the special
  11570. values \"earlier\" and \"later\". The function then increases or
  11571. decreases scheduled or deadline date by one day."
  11572. (cond ((null value) (setq value ""))
  11573. ((not (stringp value)) (error "Properties values should be strings"))
  11574. ((not (org--valid-property-p property))
  11575. (user-error "Invalid property name: \"%s\"" property)))
  11576. (org-no-read-only
  11577. (org-with-point-at pom
  11578. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11579. (org-back-to-heading-or-point-min t)
  11580. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11581. (let ((beg (point)))
  11582. (cond
  11583. ((equal property "TODO")
  11584. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11585. ((not (member value org-todo-keywords-1))
  11586. (user-error "\"%s\" is not a valid TODO state" value)))
  11587. (org-todo value)
  11588. (org-align-tags))
  11589. ((equal property "PRIORITY")
  11590. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11591. (org-align-tags))
  11592. ((equal property "SCHEDULED")
  11593. (forward-line)
  11594. (if (and (looking-at-p org-planning-line-re)
  11595. (re-search-forward
  11596. org-scheduled-time-regexp (line-end-position) t))
  11597. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11598. ((string= value "later") (org-timestamp-change 1 'day))
  11599. ((string= value "") (org-schedule '(4)))
  11600. (t (org-schedule nil value)))
  11601. (if (member value '("earlier" "later" ""))
  11602. (call-interactively #'org-schedule)
  11603. (org-schedule nil value))))
  11604. ((equal property "DEADLINE")
  11605. (forward-line)
  11606. (if (and (looking-at-p org-planning-line-re)
  11607. (re-search-forward
  11608. org-deadline-time-regexp (line-end-position) t))
  11609. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11610. ((string= value "later") (org-timestamp-change 1 'day))
  11611. ((string= value "") (org-deadline '(4)))
  11612. (t (org-deadline nil value)))
  11613. (if (member value '("earlier" "later" ""))
  11614. (call-interactively #'org-deadline)
  11615. (org-deadline nil value))))
  11616. ((member property org-special-properties)
  11617. (error "The %s property cannot be set with `org-entry-put'" property))
  11618. (t
  11619. (org-fold-core-ignore-modifications
  11620. (let* ((range (org-get-property-block beg 'force))
  11621. (end (cdr range))
  11622. (case-fold-search t))
  11623. (goto-char (car range))
  11624. (if (re-search-forward (org-re-property property nil t) end t)
  11625. (progn (delete-region (match-beginning 0) (match-end 0))
  11626. (goto-char (match-beginning 0)))
  11627. (goto-char end)
  11628. (insert-and-inherit "\n")
  11629. (backward-char))
  11630. (insert-and-inherit ":" property ":")
  11631. (when value (insert-and-inherit " " value))
  11632. (org-indent-line))))))
  11633. (run-hook-with-args 'org-property-changed-functions property value))))
  11634. (defun org-buffer-property-keys (&optional specials defaults columns)
  11635. "Get all property keys in the current buffer.
  11636. When SPECIALS is non-nil, also list the special properties that
  11637. reflect things like tags and TODO state.
  11638. When DEFAULTS is non-nil, also include properties that has
  11639. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11640. DESCRIPTION, LOCATION, and LOGGING and others.
  11641. When COLUMNS in non-nil, also include property names given in
  11642. COLUMN formats in the current buffer."
  11643. (let ((case-fold-search t)
  11644. (props (append
  11645. (and specials org-special-properties)
  11646. (and defaults (cons org-effort-property org-default-properties))
  11647. ;; Get property names from #+PROPERTY keywords as well
  11648. (mapcar (lambda (s)
  11649. (nth 0 (split-string s)))
  11650. (cdar (org-collect-keywords '("PROPERTY")))))))
  11651. (org-with-wide-buffer
  11652. (goto-char (point-min))
  11653. (while (re-search-forward org-property-start-re nil t)
  11654. (catch :skip
  11655. (let ((range (org-get-property-block)))
  11656. (unless range (throw :skip nil))
  11657. (goto-char (car range))
  11658. (let ((begin (car range))
  11659. (end (cdr range)))
  11660. ;; Make sure that found property block is not located
  11661. ;; before current point, as it would generate an infloop.
  11662. ;; It can happen, for example, in the following
  11663. ;; situation:
  11664. ;;
  11665. ;; * Headline
  11666. ;; :PROPERTIES:
  11667. ;; ...
  11668. ;; :END:
  11669. ;; *************** Inlinetask
  11670. ;; #+BEGIN_EXAMPLE
  11671. ;; :PROPERTIES:
  11672. ;; #+END_EXAMPLE
  11673. ;;
  11674. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11675. (while (< (point) end)
  11676. (let ((p (progn (looking-at org-property-re)
  11677. (match-string-no-properties 2))))
  11678. ;; Only add true property name, not extension symbol.
  11679. (push (if (not (string-match-p "\\+\\'" p)) p
  11680. (substring p 0 -1))
  11681. props))
  11682. (forward-line))))
  11683. (outline-next-heading)))
  11684. (when columns
  11685. (goto-char (point-min))
  11686. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11687. (let ((element (org-element-at-point)))
  11688. (when (memq (org-element-type element) '(keyword node-property))
  11689. (let ((value (org-element-property :value element))
  11690. (start 0))
  11691. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11692. \\(?:{[^}]+}\\)?"
  11693. value start)
  11694. (setq start (match-end 0))
  11695. (let ((p (match-string-no-properties 1 value)))
  11696. (unless (member-ignore-case p org-special-properties)
  11697. (push p props))))))))))
  11698. (sort (delete-dups
  11699. (append props
  11700. ;; for each xxx_ALL property, make sure the bare
  11701. ;; xxx property is also included
  11702. (delq nil (mapcar (lambda (p)
  11703. (and (string-match-p "._ALL\\'" p)
  11704. (substring p 0 -4)))
  11705. props))))
  11706. (lambda (a b) (string< (upcase a) (upcase b))))))
  11707. (defun org-property-values (key)
  11708. "List all non-nil values of property KEY in current buffer."
  11709. (org-with-wide-buffer
  11710. (goto-char (point-min))
  11711. (let ((case-fold-search t)
  11712. (re (org-re-property key))
  11713. values)
  11714. (while (re-search-forward re nil t)
  11715. (push (org-entry-get (point) key) values))
  11716. (delete-dups values))))
  11717. (defun org-insert-property-drawer ()
  11718. "Insert a property drawer into the current entry.
  11719. Do nothing if the drawer already exists. The newly created
  11720. drawer is immediately hidden."
  11721. (org-with-wide-buffer
  11722. ;; Set point to the position where the drawer should be inserted.
  11723. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11724. (org-back-to-heading-or-point-min t)
  11725. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11726. (if (org-before-first-heading-p)
  11727. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11728. (forward-line)
  11729. (when (looking-at-p org-planning-line-re) (forward-line)))
  11730. (unless (looking-at-p org-property-drawer-re)
  11731. ;; Make sure we start editing a line from current entry, not from
  11732. ;; next one. It prevents extending text properties or overlays
  11733. ;; belonging to the latter.
  11734. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11735. (let ((begin (if (bobp) (point) (1+ (point))))
  11736. (inhibit-read-only t))
  11737. (unless (bobp) (insert "\n"))
  11738. (insert ":PROPERTIES:\n:END:")
  11739. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11740. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11741. (org-indent-region begin (point))))))
  11742. (defun org-insert-drawer (&optional arg drawer)
  11743. "Insert a drawer at point.
  11744. When optional argument ARG is non-nil, insert a property drawer.
  11745. Optional argument DRAWER, when non-nil, is a string representing
  11746. drawer's name. Otherwise, the user is prompted for a name.
  11747. If a region is active, insert the drawer around that region
  11748. instead.
  11749. Point is left between drawer's boundaries."
  11750. (interactive "P")
  11751. (let* ((drawer (if arg "PROPERTIES"
  11752. (or drawer (read-from-minibuffer "Drawer: ")))))
  11753. (cond
  11754. ;; With C-u, fall back on `org-insert-property-drawer'
  11755. (arg (org-insert-property-drawer))
  11756. ;; Check validity of suggested drawer's name.
  11757. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11758. (user-error "Invalid drawer name"))
  11759. ;; With an active region, insert a drawer at point.
  11760. ((not (org-region-active-p))
  11761. (progn
  11762. (unless (bolp) (insert "\n"))
  11763. (insert (format ":%s:\n\n:END:\n" drawer))
  11764. (forward-line -2)))
  11765. ;; Otherwise, insert the drawer at point
  11766. (t
  11767. (let ((rbeg (region-beginning))
  11768. (rend (copy-marker (region-end))))
  11769. (unwind-protect
  11770. (progn
  11771. (goto-char rbeg)
  11772. (beginning-of-line)
  11773. (when (save-excursion
  11774. (re-search-forward org-outline-regexp-bol rend t))
  11775. (user-error "Drawers cannot contain headlines"))
  11776. ;; Position point at the beginning of the first
  11777. ;; non-blank line in region. Insert drawer's opening
  11778. ;; there, then indent it.
  11779. (org-skip-whitespace)
  11780. (beginning-of-line)
  11781. (insert ":" drawer ":\n")
  11782. (forward-line -1)
  11783. (indent-for-tab-command)
  11784. ;; Move point to the beginning of the first blank line
  11785. ;; after the last non-blank line in region. Insert
  11786. ;; drawer's closing, then indent it.
  11787. (goto-char rend)
  11788. (skip-chars-backward " \r\t\n")
  11789. (insert "\n:END:")
  11790. (deactivate-mark t)
  11791. (indent-for-tab-command)
  11792. (unless (eolp) (insert "\n")))
  11793. ;; Clear marker, whatever the outcome of insertion is.
  11794. (set-marker rend nil)))))))
  11795. (defvar org-property-set-functions-alist nil
  11796. "Property set function alist.
  11797. Each entry should have the following format:
  11798. (PROPERTY . READ-FUNCTION)
  11799. The read function will be called with the same argument as
  11800. `org-completing-read'.")
  11801. (defun org-set-property-function (property)
  11802. "Get the function that should be used to set PROPERTY.
  11803. This is computed according to `org-property-set-functions-alist'."
  11804. (or (cdr (assoc property org-property-set-functions-alist))
  11805. 'org-completing-read))
  11806. (defun org-read-property-value (property &optional pom default)
  11807. "Read value for PROPERTY, as a string.
  11808. When optional argument POM is non-nil, completion uses additional
  11809. information, i.e., allowed or existing values at point or marker
  11810. POM.
  11811. Optional argument DEFAULT provides a default value for PROPERTY."
  11812. (let* ((completion-ignore-case t)
  11813. (allowed
  11814. (or (org-property-get-allowed-values nil property 'table)
  11815. (and pom (org-property-get-allowed-values pom property 'table))))
  11816. (current (org-entry-get nil property))
  11817. (prompt (format "%s value%s: "
  11818. property
  11819. (if (org-string-nw-p current)
  11820. (format " [%s]" current)
  11821. "")))
  11822. (set-function (org-set-property-function property)))
  11823. (org-trim
  11824. (if allowed
  11825. (funcall set-function
  11826. prompt allowed nil
  11827. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11828. default nil default)
  11829. (let ((all (mapcar #'list
  11830. (append (org-property-values property)
  11831. (and pom
  11832. (org-with-point-at pom
  11833. (org-property-values property)))))))
  11834. (funcall set-function prompt all nil nil "" nil current))))))
  11835. (defvar org-last-set-property nil)
  11836. (defvar org-last-set-property-value nil)
  11837. (defun org-read-property-name ()
  11838. "Read a property name."
  11839. (let ((completion-ignore-case t)
  11840. (default-prop (or (and (org-at-property-p)
  11841. (match-string-no-properties 2))
  11842. org-last-set-property)))
  11843. (org-completing-read
  11844. (concat "Property"
  11845. (if default-prop (concat " [" default-prop "]") "")
  11846. ": ")
  11847. (mapcar #'list (org-buffer-property-keys nil t t))
  11848. nil nil nil nil default-prop)))
  11849. (defun org-set-property-and-value (use-last)
  11850. "Allow to set [PROPERTY]: [value] direction from prompt.
  11851. When use-default, don't even ask, just use the last
  11852. \"[PROPERTY]: [value]\" string from the history."
  11853. (interactive "P")
  11854. (let* ((completion-ignore-case t)
  11855. (pv (or (and use-last org-last-set-property-value)
  11856. (org-completing-read
  11857. "Enter a \"[Property]: [value]\" pair: "
  11858. nil nil nil nil nil
  11859. org-last-set-property-value)))
  11860. prop val)
  11861. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11862. (setq prop (match-string 1 pv)
  11863. val (match-string 2 pv))
  11864. (org-set-property prop val))))
  11865. (defun org-set-property (property value)
  11866. "In the current entry, set PROPERTY to VALUE.
  11867. When called interactively, this will prompt for a property name, offering
  11868. completion on existing and default properties. And then it will prompt
  11869. for a value, offering completion either on allowed values (via an inherited
  11870. xxx_ALL property) or on existing values in other instances of this property
  11871. in the current file.
  11872. Throw an error when trying to set a property with an invalid name."
  11873. (interactive (list nil nil))
  11874. (let ((property (or property (org-read-property-name))))
  11875. ;; `org-entry-put' also makes the following check, but this one
  11876. ;; avoids polluting `org-last-set-property' and
  11877. ;; `org-last-set-property-value' needlessly.
  11878. (unless (org--valid-property-p property)
  11879. (user-error "Invalid property name: \"%s\"" property))
  11880. (let ((value (or value (org-read-property-value property)))
  11881. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11882. (setq org-last-set-property property)
  11883. (setq org-last-set-property-value (concat property ": " value))
  11884. ;; Possibly postprocess the inserted value:
  11885. (when fn (setq value (funcall fn value)))
  11886. (unless (equal (org-entry-get nil property) value)
  11887. (org-entry-put nil property value)))))
  11888. (defun org-find-property (property &optional value)
  11889. "Find first entry in buffer that sets PROPERTY.
  11890. When optional argument VALUE is non-nil, only consider an entry
  11891. if it contains PROPERTY set to this value. If PROPERTY should be
  11892. explicitly set to nil, use string \"nil\" for VALUE.
  11893. Return position where the entry begins, or nil if there is no
  11894. such entry. If narrowing is in effect, only search the visible
  11895. part of the buffer."
  11896. (save-excursion
  11897. (goto-char (point-min))
  11898. (let ((case-fold-search t)
  11899. (re (org-re-property property nil (not value) value)))
  11900. (catch 'exit
  11901. (while (re-search-forward re nil t)
  11902. (when (if value (org-at-property-p)
  11903. (org-entry-get (point) property nil t))
  11904. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  11905. (point)))))))))
  11906. (defun org-delete-property (property)
  11907. "In the current entry, delete PROPERTY."
  11908. (interactive
  11909. (let* ((completion-ignore-case t)
  11910. (cat (org-entry-get (point) "CATEGORY"))
  11911. (props0 (org-entry-properties nil 'standard))
  11912. (props (if cat props0
  11913. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11914. (prop (if (< 1 (length props))
  11915. (completing-read "Property: " props nil t)
  11916. (caar props))))
  11917. (list prop)))
  11918. (if (not property)
  11919. (message "No property to delete in this entry")
  11920. (org-entry-delete nil property)
  11921. (message "Property \"%s\" deleted" property)))
  11922. (defun org-delete-property-globally (property)
  11923. "Remove PROPERTY globally, from all entries.
  11924. This function ignores narrowing, if any."
  11925. (interactive
  11926. (let* ((completion-ignore-case t)
  11927. (prop (completing-read
  11928. "Globally remove property: "
  11929. (mapcar #'list (org-buffer-property-keys)))))
  11930. (list prop)))
  11931. (org-with-wide-buffer
  11932. (goto-char (point-min))
  11933. (let ((count 0)
  11934. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11935. (while (re-search-forward re nil t)
  11936. (when (org-entry-delete (point) property) (cl-incf count)))
  11937. (message "Property \"%s\" removed from %d entries" property count))))
  11938. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11939. (defun org-compute-property-at-point ()
  11940. "Compute the property at point.
  11941. This looks for an enclosing column format, extracts the operator and
  11942. then applies it to the property in the column format's scope."
  11943. (interactive)
  11944. (unless (org-at-property-p)
  11945. (user-error "Not at a property"))
  11946. (let ((prop (match-string-no-properties 2)))
  11947. (org-columns-get-format-and-top-level)
  11948. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11949. (user-error "No operator defined for property %s" prop))
  11950. (org-columns-compute prop)))
  11951. (defvar org-property-allowed-value-functions nil
  11952. "Hook for functions supplying allowed values for a specific property.
  11953. The functions must take a single argument, the name of the property, and
  11954. return a flat list of allowed values. If \":ETC\" is one of
  11955. the values, this means that these values are intended as defaults for
  11956. completion, but that other values should be allowed too.
  11957. The functions must return nil if they are not responsible for this
  11958. property.")
  11959. (defun org-property-get-allowed-values (pom property &optional table)
  11960. "Get allowed values for the property PROPERTY.
  11961. When TABLE is non-nil, return an alist that can directly be used for
  11962. completion."
  11963. (let (vals)
  11964. (cond
  11965. ((equal property "TODO")
  11966. (setq vals (org-with-point-at pom
  11967. (append org-todo-keywords-1 '("")))))
  11968. ((equal property "PRIORITY")
  11969. (let ((n org-priority-lowest))
  11970. (while (>= n org-priority-highest)
  11971. (push (char-to-string n) vals)
  11972. (setq n (1- n)))))
  11973. ((equal property "CATEGORY"))
  11974. ((member property org-special-properties))
  11975. ((setq vals (run-hook-with-args-until-success
  11976. 'org-property-allowed-value-functions property)))
  11977. (t
  11978. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11979. (when (and vals (string-match "\\S-" vals))
  11980. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11981. (setq vals (mapcar (lambda (x)
  11982. (cond ((stringp x) x)
  11983. ((numberp x) (number-to-string x))
  11984. ((symbolp x) (symbol-name x))
  11985. (t "???")))
  11986. vals)))))
  11987. (when (member ":ETC" vals)
  11988. (setq vals (remove ":ETC" vals))
  11989. (org-add-props (car vals) '(org-unrestricted t)))
  11990. (if table (mapcar 'list vals) vals)))
  11991. (defun org-property-previous-allowed-value (&optional _previous)
  11992. "Switch to the next allowed value for this property."
  11993. (interactive)
  11994. (org-property-next-allowed-value t))
  11995. (defun org-property-next-allowed-value (&optional previous)
  11996. "Switch to the next allowed value for this property."
  11997. (interactive)
  11998. (unless (org-at-property-p)
  11999. (user-error "Not at a property"))
  12000. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12001. (key (match-string 2))
  12002. (value (match-string 3))
  12003. (allowed (or (org-property-get-allowed-values (point) key)
  12004. (and (member value '("[ ]" "[-]" "[X]"))
  12005. '("[ ]" "[X]"))))
  12006. (heading (save-match-data (nth 4 (org-heading-components))))
  12007. nval)
  12008. (unless allowed
  12009. (user-error "Allowed values for this property have not been defined"))
  12010. (when previous (setq allowed (reverse allowed)))
  12011. (when (member value allowed)
  12012. (setq nval (car (cdr (member value allowed)))))
  12013. (setq nval (or nval (car allowed)))
  12014. (when (equal nval value)
  12015. (user-error "Only one allowed value for this property"))
  12016. (org-at-property-p)
  12017. (replace-match (concat " :" key ": " nval) t t)
  12018. (org-indent-line)
  12019. (beginning-of-line 1)
  12020. (skip-chars-forward " \t")
  12021. (when (equal prop org-effort-property)
  12022. (unless (org-element--cache-active-p)
  12023. (org-refresh-property
  12024. '((effort . identity)
  12025. (effort-minutes . org-duration-to-minutes))
  12026. nval))
  12027. (when (string= org-clock-current-task heading)
  12028. (setq org-clock-effort nval)
  12029. (org-clock-update-mode-line)))
  12030. (run-hook-with-args 'org-property-changed-functions key nval)))
  12031. (defun org-find-olp (path &optional this-buffer)
  12032. "Return a marker pointing to the entry at outline path OLP.
  12033. If anything goes wrong, throw an error, and if you need to do
  12034. something based on this error, you can catch it with
  12035. `condition-case'.
  12036. If THIS-BUFFER is set, the outline path does not contain a file,
  12037. only headings."
  12038. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12039. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12040. (level 1)
  12041. (lmin 1)
  12042. (lmax 1)
  12043. end found flevel)
  12044. (unless buffer (error "File not found :%s" file))
  12045. (with-current-buffer buffer
  12046. (unless (derived-mode-p 'org-mode)
  12047. (error "Buffer %s needs to be in Org mode" buffer))
  12048. (org-with-wide-buffer
  12049. (goto-char (point-min))
  12050. (dolist (heading path)
  12051. (let ((re (format org-complex-heading-regexp-format
  12052. (regexp-quote heading)))
  12053. (cnt 0))
  12054. (while (re-search-forward re end t)
  12055. (setq level (- (match-end 1) (match-beginning 1)))
  12056. (when (and (>= level lmin) (<= level lmax))
  12057. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12058. (when (= cnt 0)
  12059. (error "Heading not found on level %d: %s" lmax heading))
  12060. (when (> cnt 1)
  12061. (error "Heading not unique on level %d: %s" lmax heading))
  12062. (goto-char found)
  12063. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12064. (setq end (save-excursion (org-end-of-subtree t t)))))
  12065. (when (org-at-heading-p)
  12066. (point-marker))))))
  12067. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12068. "Find node HEADING in BUFFER.
  12069. Return a marker to the heading if it was found, or nil if not.
  12070. If POS-ONLY is set, return just the position instead of a marker.
  12071. The heading text must match exact, but it may have a TODO keyword,
  12072. a priority cookie and tags in the standard locations."
  12073. (with-current-buffer (or buffer (current-buffer))
  12074. (org-with-wide-buffer
  12075. (goto-char (point-min))
  12076. (let (case-fold-search)
  12077. (when (re-search-forward
  12078. (format org-complex-heading-regexp-format
  12079. (regexp-quote heading)) nil t)
  12080. (if pos-only
  12081. (match-beginning 0)
  12082. (move-marker (make-marker) (match-beginning 0))))))))
  12083. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12084. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12085. When the target headline is found, return a marker to this location."
  12086. (let ((files (directory-files (or dir default-directory)
  12087. t "\\`[^.#].*\\.org\\'"))
  12088. visiting m buffer)
  12089. (catch 'found
  12090. (dolist (file files)
  12091. (message "trying %s" file)
  12092. (setq visiting (org-find-base-buffer-visiting file))
  12093. (setq buffer (or visiting (find-file-noselect file)))
  12094. (setq m (org-find-exact-headline-in-buffer
  12095. heading buffer))
  12096. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12097. (and m (throw 'found m))))))
  12098. (defun org-find-entry-with-id (ident)
  12099. "Locate the entry that contains the ID property with exact value IDENT.
  12100. IDENT can be a string, a symbol or a number, this function will search for
  12101. the string representation of it.
  12102. Return the position where this entry starts, or nil if there is no such entry."
  12103. (interactive "sID: ")
  12104. (let ((id (cond
  12105. ((stringp ident) ident)
  12106. ((symbolp ident) (symbol-name ident))
  12107. ((numberp ident) (number-to-string ident))
  12108. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12109. (org-with-wide-buffer (org-find-property "ID" id))))
  12110. ;;;; Timestamps
  12111. (defvar org-last-changed-timestamp nil)
  12112. (defvar org-last-inserted-timestamp nil
  12113. "The last time stamp inserted with `org-insert-time-stamp'.")
  12114. (defun org-time-stamp (arg &optional inactive)
  12115. "Prompt for a date/time and insert a time stamp.
  12116. If the user specifies a time like HH:MM or if this command is
  12117. called with at least one prefix argument, the time stamp contains
  12118. the date and the time. Otherwise, only the date is included.
  12119. All parts of a date not specified by the user are filled in from
  12120. the timestamp at point, if any, or the current date/time
  12121. otherwise.
  12122. If there is already a timestamp at the cursor, it is replaced.
  12123. With two universal prefix arguments, insert an active timestamp
  12124. with the current time without prompting the user.
  12125. When called from Lisp, the timestamp is inactive if INACTIVE is
  12126. non-nil."
  12127. (interactive "P")
  12128. (let* ((ts (cond
  12129. ((org-at-date-range-p t)
  12130. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12131. ((org-at-timestamp-p 'lax) (match-string 0))))
  12132. ;; Default time is either the timestamp at point or today.
  12133. ;; When entering a range, only the range start is considered.
  12134. (default-time (and ts (org-time-string-to-time ts)))
  12135. (default-input (and ts (org-get-compact-tod ts)))
  12136. (repeater (and ts
  12137. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12138. (match-string 0 ts)))
  12139. org-time-was-given
  12140. org-end-time-was-given
  12141. (time
  12142. (if (equal arg '(16)) (current-time)
  12143. ;; Preserve `this-command' and `last-command'.
  12144. (let ((this-command this-command)
  12145. (last-command last-command))
  12146. (org-read-date
  12147. arg 'totime nil nil default-time default-input
  12148. inactive)))))
  12149. (cond
  12150. ((and ts
  12151. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12152. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12153. (insert "--")
  12154. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12155. (ts
  12156. ;; Make sure we're on a timestamp. When in the middle of a date
  12157. ;; range, move arbitrarily to range end.
  12158. (unless (org-at-timestamp-p 'lax)
  12159. (skip-chars-forward "-")
  12160. (org-at-timestamp-p 'lax))
  12161. (replace-match "")
  12162. (setq org-last-changed-timestamp
  12163. (org-insert-time-stamp
  12164. time (or org-time-was-given arg)
  12165. inactive nil nil (list org-end-time-was-given)))
  12166. (when repeater
  12167. (backward-char)
  12168. (insert " " repeater)
  12169. (setq org-last-changed-timestamp
  12170. (concat (substring org-last-inserted-timestamp 0 -1)
  12171. " " repeater ">")))
  12172. (message "Timestamp updated"))
  12173. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12174. (t (org-insert-time-stamp
  12175. time (or org-time-was-given arg) inactive nil nil
  12176. (list org-end-time-was-given))))))
  12177. ;; FIXME: can we use this for something else, like computing time differences?
  12178. (defun org-get-compact-tod (s)
  12179. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12180. (let* ((t1 (match-string 1 s))
  12181. (h1 (string-to-number (match-string 2 s)))
  12182. (m1 (string-to-number (match-string 3 s)))
  12183. (t2 (and (match-end 4) (match-string 5 s)))
  12184. (h2 (and t2 (string-to-number (match-string 6 s))))
  12185. (m2 (and t2 (string-to-number (match-string 7 s))))
  12186. dh dm)
  12187. (if (not t2)
  12188. t1
  12189. (setq dh (- h2 h1) dm (- m2 m1))
  12190. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12191. (concat t1 "+" (number-to-string dh)
  12192. (and (/= 0 dm) (format ":%02d" dm)))))))
  12193. (defun org-time-stamp-inactive (&optional arg)
  12194. "Insert an inactive time stamp.
  12195. An inactive time stamp is enclosed in square brackets instead of
  12196. angle brackets. It is inactive in the sense that it does not
  12197. trigger agenda entries. So these are more for recording a
  12198. certain time/date.
  12199. If the user specifies a time like HH:MM or if this command is called with
  12200. at least one prefix argument, the time stamp contains the date and the time.
  12201. Otherwise, only the date is included.
  12202. When called with two universal prefix arguments, insert an inactive time stamp
  12203. with the current time without prompting the user."
  12204. (interactive "P")
  12205. (org-time-stamp arg 'inactive))
  12206. (defvar org-date-ovl (make-overlay 1 1))
  12207. (overlay-put org-date-ovl 'face 'org-date-selected)
  12208. (delete-overlay org-date-ovl)
  12209. (defvar org-ans1) ; dynamically scoped parameter
  12210. (defvar org-ans2) ; dynamically scoped parameter
  12211. (defvar org-plain-time-of-day-regexp) ; defined below
  12212. (defvar org-overriding-default-time nil) ; dynamically scoped
  12213. (defvar org-read-date-overlay nil)
  12214. (defvar org-read-date-history nil)
  12215. (defvar org-read-date-final-answer nil)
  12216. (defvar org-read-date-analyze-futurep nil)
  12217. (defvar org-read-date-analyze-forced-year nil)
  12218. (defvar org-read-date-inactive)
  12219. (defvar org-def)
  12220. (defvar org-defdecode)
  12221. (defvar org-with-time)
  12222. (defvar calendar-setup) ; Dynamically scoped.
  12223. (defun org-read-date (&optional with-time to-time from-string prompt
  12224. default-time default-input inactive)
  12225. "Read a date, possibly a time, and make things smooth for the user.
  12226. The prompt will suggest to enter an ISO date, but you can also enter anything
  12227. which will at least partially be understood by `parse-time-string'.
  12228. Unrecognized parts of the date will default to the current day, month, year,
  12229. hour and minute. If this command is called to replace a timestamp at point,
  12230. or to enter the second timestamp of a range, the default time is taken
  12231. from the existing stamp. Furthermore, the command prefers the future,
  12232. so if you are giving a date where the year is not given, and the day-month
  12233. combination is already past in the current year, it will assume you
  12234. mean next year. For details, see the manual. A few examples:
  12235. 3-2-5 --> 2003-02-05
  12236. feb 15 --> currentyear-02-15
  12237. 2/15 --> currentyear-02-15
  12238. sep 12 9 --> 2009-09-12
  12239. 12:45 --> today 12:45
  12240. 22 sept 0:34 --> currentyear-09-22 0:34
  12241. 12 --> currentyear-currentmonth-12
  12242. Fri --> nearest Friday after today
  12243. -Tue --> last Tuesday
  12244. etc.
  12245. Furthermore you can specify a relative date by giving, as the *first* thing
  12246. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12247. change in days weeks, months, years.
  12248. With a single plus or minus, the date is relative to today. With a double
  12249. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12250. +4d --> four days from today
  12251. +4 --> same as above
  12252. +2w --> two weeks from today
  12253. ++5 --> five days from default date
  12254. The function understands only English month and weekday abbreviations.
  12255. While prompting, a calendar is popped up - you can also select the
  12256. date with the mouse (button 1). The calendar shows a period of three
  12257. months. To scroll it to other months, use the keys `>' and `<'.
  12258. There are many other calendar navigation commands available, see
  12259. Info node `(org) The date/time prompt' for a full list.
  12260. If you don't like the calendar, turn it off with
  12261. (setq org-read-date-popup-calendar nil)
  12262. With optional argument TO-TIME, the date will immediately be converted
  12263. to an internal time.
  12264. With an optional argument WITH-TIME, the prompt will suggest to
  12265. also insert a time. Note that when WITH-TIME is not set, you can
  12266. still enter a time, and this function will inform the calling routine
  12267. about this change. The calling routine may then choose to change the
  12268. format used to insert the time stamp into the buffer to include the time.
  12269. With optional argument FROM-STRING, read from this string instead from
  12270. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12271. the time/date that is used for everything that is not specified by the
  12272. user."
  12273. (require 'parse-time)
  12274. (let* ((org-with-time with-time)
  12275. (org-time-stamp-rounding-minutes
  12276. (if (equal org-with-time '(16))
  12277. '(0 0)
  12278. org-time-stamp-rounding-minutes))
  12279. (ct (org-current-time))
  12280. (org-def (or org-overriding-default-time default-time ct))
  12281. (org-defdecode (decode-time org-def))
  12282. (cur-frame (selected-frame))
  12283. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12284. (calendar-setup
  12285. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12286. (calendar-move-hook nil)
  12287. (calendar-view-diary-initially-flag nil)
  12288. (calendar-view-holidays-initially-flag nil)
  12289. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12290. ;; Rationalize `org-def' and `org-defdecode', if required.
  12291. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12292. (setf (nth 2 org-defdecode) -1)
  12293. (setf (nth 1 org-defdecode) 59)
  12294. (setq org-def (org-encode-time org-defdecode))
  12295. (setq org-defdecode (decode-time org-def)))
  12296. (let* ((timestr (format-time-string
  12297. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12298. org-def))
  12299. (prompt (concat (if prompt (concat prompt " ") "")
  12300. (format "Date+time [%s]: " timestr))))
  12301. (cond
  12302. (from-string (setq ans from-string))
  12303. (org-read-date-popup-calendar
  12304. (save-excursion
  12305. (save-window-excursion
  12306. (calendar)
  12307. (when (eq calendar-setup 'calendar-only)
  12308. (setq cal-frame
  12309. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12310. (select-frame cal-frame))
  12311. (org-eval-in-calendar '(setq cursor-type nil) t)
  12312. (unwind-protect
  12313. (progn
  12314. (calendar-forward-day (- (time-to-days org-def)
  12315. (calendar-absolute-from-gregorian
  12316. (calendar-current-date))))
  12317. (org-eval-in-calendar nil t)
  12318. (let* ((old-map (current-local-map))
  12319. (map (copy-keymap calendar-mode-map))
  12320. (minibuffer-local-map
  12321. (copy-keymap org-read-date-minibuffer-local-map)))
  12322. (org-defkey map (kbd "RET") 'org-calendar-select)
  12323. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12324. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12325. (unwind-protect
  12326. (progn
  12327. (use-local-map map)
  12328. (setq org-read-date-inactive inactive)
  12329. (add-hook 'post-command-hook 'org-read-date-display)
  12330. (setq org-ans0
  12331. (read-string prompt
  12332. default-input
  12333. 'org-read-date-history
  12334. nil))
  12335. ;; org-ans0: from prompt
  12336. ;; org-ans1: from mouse click
  12337. ;; org-ans2: from calendar motion
  12338. (setq ans
  12339. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12340. (remove-hook 'post-command-hook 'org-read-date-display)
  12341. (use-local-map old-map)
  12342. (when org-read-date-overlay
  12343. (delete-overlay org-read-date-overlay)
  12344. (setq org-read-date-overlay nil)))))
  12345. (bury-buffer "*Calendar*")
  12346. (when cal-frame
  12347. (delete-frame cal-frame)
  12348. (select-frame-set-input-focus cur-frame))))))
  12349. (t ; Naked prompt only
  12350. (unwind-protect
  12351. (setq ans (read-string prompt default-input
  12352. 'org-read-date-history timestr))
  12353. (when org-read-date-overlay
  12354. (delete-overlay org-read-date-overlay)
  12355. (setq org-read-date-overlay nil))))))
  12356. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12357. (when org-read-date-analyze-forced-year
  12358. (message "Year was forced into %s"
  12359. (if org-read-date-force-compatible-dates
  12360. "compatible range (1970-2037)"
  12361. "range representable on this machine"))
  12362. (ding))
  12363. (setq final (org-encode-time final))
  12364. (setq org-read-date-final-answer ans)
  12365. (if to-time
  12366. final
  12367. ;; This round-trip gets rid of 34th of August and stuff like that....
  12368. (setq final (decode-time final))
  12369. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12370. (format "%04d-%02d-%02d %02d:%02d"
  12371. (nth 5 final) (nth 4 final) (nth 3 final)
  12372. (nth 2 final) (nth 1 final))
  12373. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12374. (defun org-read-date-display ()
  12375. "Display the current date prompt interpretation in the minibuffer."
  12376. (when org-read-date-display-live
  12377. (when org-read-date-overlay
  12378. (delete-overlay org-read-date-overlay))
  12379. (when (minibufferp (current-buffer))
  12380. (save-excursion
  12381. (end-of-line 1)
  12382. (while (not (equal (buffer-substring
  12383. (max (point-min) (- (point) 4)) (point))
  12384. " "))
  12385. (insert " ")))
  12386. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12387. " " (or org-ans1 org-ans2)))
  12388. (org-end-time-was-given nil)
  12389. (f (org-read-date-analyze ans org-def org-defdecode))
  12390. (fmts (if org-display-custom-times
  12391. org-time-stamp-custom-formats
  12392. org-time-stamp-formats))
  12393. (fmt (if (or org-with-time
  12394. (and (boundp 'org-time-was-given) org-time-was-given))
  12395. (cdr fmts)
  12396. (car fmts)))
  12397. (txt (format-time-string fmt (org-encode-time f)))
  12398. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12399. (txt (concat "=> " txt)))
  12400. (when (and org-end-time-was-given
  12401. (string-match org-plain-time-of-day-regexp txt))
  12402. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12403. org-end-time-was-given
  12404. (substring txt (match-end 0)))))
  12405. (when org-read-date-analyze-futurep
  12406. (setq txt (concat txt " (=>F)")))
  12407. (setq org-read-date-overlay
  12408. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12409. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12410. (defun org-read-date-analyze (ans def defdecode)
  12411. "Analyze the combined answer of the date prompt."
  12412. ;; FIXME: cleanup and comment
  12413. (let ((org-def def)
  12414. (org-defdecode defdecode)
  12415. (nowdecode (decode-time))
  12416. delta deltan deltaw deltadef year month day
  12417. hour minute second wday pm h2 m2 tl wday1
  12418. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12419. (setq org-read-date-analyze-futurep nil
  12420. org-read-date-analyze-forced-year nil)
  12421. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12422. (setq ans "+0"))
  12423. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12424. (setq ans (replace-match "" t t ans)
  12425. deltan (car delta)
  12426. deltaw (nth 1 delta)
  12427. deltadef (nth 2 delta)))
  12428. ;; Check if there is an iso week date in there. If yes, store the
  12429. ;; info and postpone interpreting it until the rest of the parsing
  12430. ;; is done.
  12431. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12432. (setq iso-year (when (match-end 1)
  12433. (org-small-year-to-year
  12434. (string-to-number (match-string 1 ans))))
  12435. iso-weekday (when (match-end 3)
  12436. (string-to-number (match-string 3 ans)))
  12437. iso-week (string-to-number (match-string 2 ans)))
  12438. (setq ans (replace-match "" t t ans)))
  12439. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12440. (when (string-match
  12441. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12442. (setq year (if (match-end 2)
  12443. (string-to-number (match-string 2 ans))
  12444. (progn (setq kill-year t)
  12445. (string-to-number (format-time-string "%Y"))))
  12446. month (string-to-number (match-string 3 ans))
  12447. day (string-to-number (match-string 4 ans)))
  12448. (setq year (org-small-year-to-year year))
  12449. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12450. t nil ans)))
  12451. ;; Help matching dotted european dates
  12452. (when (string-match
  12453. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12454. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12455. (setq kill-year t)
  12456. (string-to-number (format-time-string "%Y")))
  12457. day (string-to-number (match-string 1 ans))
  12458. month (string-to-number (match-string 2 ans))
  12459. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12460. t nil ans)))
  12461. ;; Help matching american dates, like 5/30 or 5/30/7
  12462. (when (string-match
  12463. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12464. (setq year (if (match-end 4)
  12465. (string-to-number (match-string 4 ans))
  12466. (progn (setq kill-year t)
  12467. (string-to-number (format-time-string "%Y"))))
  12468. month (string-to-number (match-string 1 ans))
  12469. day (string-to-number (match-string 2 ans)))
  12470. (setq year (org-small-year-to-year year))
  12471. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12472. t nil ans)))
  12473. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12474. ;; If there is a time with am/pm, and *no* time without it, we convert
  12475. ;; so that matching will be successful.
  12476. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12477. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12478. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12479. (setq hour (string-to-number (match-string 1 ans))
  12480. minute (if (match-end 3)
  12481. (string-to-number (match-string 3 ans))
  12482. 0)
  12483. pm (equal ?p
  12484. (string-to-char (downcase (match-string 4 ans)))))
  12485. (if (and (= hour 12) (not pm))
  12486. (setq hour 0)
  12487. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12488. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12489. t t ans))))
  12490. ;; Help matching HHhMM times, similarly as for am/pm times.
  12491. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12492. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12493. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12494. (setq hour (if (match-end 1)
  12495. (string-to-number (match-string 1 ans))
  12496. 0)
  12497. minute (if (match-end 2)
  12498. (string-to-number (match-string 2 ans))
  12499. 0))
  12500. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12501. t t ans))))
  12502. ;; Check if a time range is given as a duration
  12503. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12504. (setq hour (string-to-number (match-string 1 ans))
  12505. h2 (+ hour (string-to-number (match-string 3 ans)))
  12506. minute (string-to-number (match-string 2 ans))
  12507. m2 (+ minute (if (match-end 5) (string-to-number
  12508. (match-string 5 ans))0)))
  12509. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12510. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12511. t t ans)))
  12512. ;; Check if there is a time range
  12513. (when (boundp 'org-end-time-was-given)
  12514. (setq org-time-was-given nil)
  12515. (when (and (string-match org-plain-time-of-day-regexp ans)
  12516. (match-end 8))
  12517. (setq org-end-time-was-given (match-string 8 ans))
  12518. (setq ans (concat (substring ans 0 (match-beginning 7))
  12519. (substring ans (match-end 7))))))
  12520. (setq tl (parse-time-string ans)
  12521. day (or (nth 3 tl) (nth 3 org-defdecode))
  12522. month
  12523. (cond ((nth 4 tl))
  12524. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12525. ;; Day was specified. Make sure DAY+MONTH
  12526. ;; combination happens in the future.
  12527. ((nth 3 tl)
  12528. (setq futurep t)
  12529. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12530. (nth 4 nowdecode)))
  12531. (t (nth 4 org-defdecode)))
  12532. year
  12533. (cond ((and (not kill-year) (nth 5 tl)))
  12534. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12535. ;; Month was guessed in the future and is at least
  12536. ;; equal to NOWDECODE's. Fix year accordingly.
  12537. (futurep
  12538. (if (or (> month (nth 4 nowdecode))
  12539. (>= day (nth 3 nowdecode)))
  12540. (nth 5 nowdecode)
  12541. (1+ (nth 5 nowdecode))))
  12542. ;; Month was specified. Make sure MONTH+YEAR
  12543. ;; combination happens in the future.
  12544. ((nth 4 tl)
  12545. (setq futurep t)
  12546. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12547. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12548. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12549. (t (nth 5 nowdecode))))
  12550. (t (nth 5 org-defdecode)))
  12551. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12552. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12553. second (or (nth 0 tl) 0)
  12554. wday (nth 6 tl))
  12555. (when (and (eq org-read-date-prefer-future 'time)
  12556. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12557. (equal day (nth 3 nowdecode))
  12558. (equal month (nth 4 nowdecode))
  12559. (equal year (nth 5 nowdecode))
  12560. (nth 2 tl)
  12561. (or (< (nth 2 tl) (nth 2 nowdecode))
  12562. (and (= (nth 2 tl) (nth 2 nowdecode))
  12563. (nth 1 tl)
  12564. (< (nth 1 tl) (nth 1 nowdecode)))))
  12565. (setq day (1+ day)
  12566. futurep t))
  12567. ;; Special date definitions below
  12568. (cond
  12569. (iso-week
  12570. ;; There was an iso week
  12571. (require 'cal-iso)
  12572. (setq futurep nil)
  12573. (setq year (or iso-year year)
  12574. day (or iso-weekday wday 1)
  12575. wday nil ; to make sure that the trigger below does not match
  12576. iso-date (calendar-gregorian-from-absolute
  12577. (calendar-iso-to-absolute
  12578. (list iso-week day year))))
  12579. ; FIXME: Should we also push ISO weeks into the future?
  12580. ; (when (and org-read-date-prefer-future
  12581. ; (not iso-year)
  12582. ; (< (calendar-absolute-from-gregorian iso-date)
  12583. ; (time-to-days nil)))
  12584. ; (setq year (1+ year)
  12585. ; iso-date (calendar-gregorian-from-absolute
  12586. ; (calendar-iso-to-absolute
  12587. ; (list iso-week day year)))))
  12588. (setq month (car iso-date)
  12589. year (nth 2 iso-date)
  12590. day (nth 1 iso-date)))
  12591. (deltan
  12592. (setq futurep nil)
  12593. (unless deltadef
  12594. (let ((now (decode-time)))
  12595. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12596. (cond ((member deltaw '("h" ""))
  12597. (when (boundp 'org-time-was-given)
  12598. (setq org-time-was-given t))
  12599. (setq hour (+ hour deltan)))
  12600. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12601. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12602. ((equal deltaw "m") (setq month (+ month deltan)))
  12603. ((equal deltaw "y") (setq year (+ year deltan)))))
  12604. ((and wday (not (nth 3 tl)))
  12605. ;; Weekday was given, but no day, so pick that day in the week
  12606. ;; on or after the derived date.
  12607. (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  12608. (unless (equal wday wday1)
  12609. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12610. (when (and (boundp 'org-time-was-given)
  12611. (nth 2 tl))
  12612. (setq org-time-was-given t))
  12613. (when (< year 100) (setq year (+ 2000 year)))
  12614. ;; Check of the date is representable
  12615. (if org-read-date-force-compatible-dates
  12616. (progn
  12617. (when (< year 1970)
  12618. (setq year 1970 org-read-date-analyze-forced-year t))
  12619. (when (> year 2037)
  12620. (setq year 2037 org-read-date-analyze-forced-year t)))
  12621. (condition-case nil
  12622. (ignore (org-encode-time second minute hour day month year))
  12623. (error
  12624. (setq year (nth 5 org-defdecode))
  12625. (setq org-read-date-analyze-forced-year t))))
  12626. (setq org-read-date-analyze-futurep futurep)
  12627. (list second minute hour day month year nil -1 nil)))
  12628. (defvar parse-time-weekdays)
  12629. (defun org-read-date-get-relative (s today default)
  12630. "Check string S for special relative date string.
  12631. TODAY and DEFAULT are internal times, for today and for a default.
  12632. Return shift list (N what def-flag)
  12633. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12634. N is the number of WHATs to shift.
  12635. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12636. the DEFAULT date rather than TODAY."
  12637. (require 'parse-time)
  12638. (when (and
  12639. (string-match
  12640. (concat
  12641. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12642. "\\([0-9]+\\)?"
  12643. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12644. "\\([ \t]\\|$\\)") s)
  12645. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12646. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12647. (string-to-char (substring (match-string 1 s) -1))
  12648. ?+))
  12649. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12650. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12651. (what (if (match-end 3) (match-string 3 s) "d"))
  12652. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12653. (date (if rel default today))
  12654. (wday (nth 6 (decode-time date)))
  12655. delta)
  12656. (if wday1
  12657. (progn
  12658. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12659. (when (= delta 0) (setq delta 7))
  12660. (when (= dir ?-)
  12661. (setq delta (- delta 7))
  12662. (when (= delta 0) (setq delta -7)))
  12663. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12664. (list delta "d" rel))
  12665. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12666. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12667. "Turn a user-specified date into the internal representation.
  12668. The internal representation needed by the calendar is (month day year).
  12669. This is a wrapper to handle the brain-dead convention in calendar that
  12670. user function argument order change dependent on argument order."
  12671. (pcase calendar-date-style
  12672. (`american (list arg1 arg2 arg3))
  12673. (`european (list arg2 arg1 arg3))
  12674. (`iso (list arg2 arg3 arg1))))
  12675. (defun org-eval-in-calendar (form &optional keepdate)
  12676. "Eval FORM in the calendar window and return to current window.
  12677. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12678. (let ((sf (selected-frame))
  12679. (sw (selected-window)))
  12680. (select-window (get-buffer-window "*Calendar*" t))
  12681. (eval form t)
  12682. (when (and (not keepdate) (calendar-cursor-to-date))
  12683. (let* ((date (calendar-cursor-to-date))
  12684. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12685. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12686. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12687. (select-window sw)
  12688. (select-frame-set-input-focus sf)))
  12689. (defun org-calendar-select ()
  12690. "Return to `org-read-date' with the date currently selected.
  12691. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12692. (interactive)
  12693. (when (calendar-cursor-to-date)
  12694. (let* ((date (calendar-cursor-to-date))
  12695. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12696. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12697. (when (active-minibuffer-window) (exit-minibuffer))))
  12698. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12699. "Insert a date stamp for the date given by the internal TIME.
  12700. See `format-time-string' for the format of TIME.
  12701. WITH-HM means use the stamp format that includes the time of the day.
  12702. INACTIVE means use square brackets instead of angular ones, so that the
  12703. stamp will not contribute to the agenda.
  12704. PRE and POST are optional strings to be inserted before and after the
  12705. stamp.
  12706. The command returns the inserted time stamp."
  12707. (org-fold-core-ignore-modifications
  12708. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12709. stamp)
  12710. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12711. (insert-before-markers-and-inherit (or pre ""))
  12712. (when (listp extra)
  12713. (setq extra (car extra))
  12714. (if (and (stringp extra)
  12715. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12716. (setq extra (format "-%02d:%02d"
  12717. (string-to-number (match-string 1 extra))
  12718. (string-to-number (match-string 2 extra))))
  12719. (setq extra nil)))
  12720. (when extra
  12721. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12722. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12723. (insert-before-markers-and-inherit (or post ""))
  12724. (setq org-last-inserted-timestamp stamp))))
  12725. (defun org-toggle-time-stamp-overlays ()
  12726. "Toggle the use of custom time stamp formats."
  12727. (interactive)
  12728. (setq org-display-custom-times (not org-display-custom-times))
  12729. (unless org-display-custom-times
  12730. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12731. (while (setq p (next-single-property-change p 'display))
  12732. (when (and (get-text-property p 'display)
  12733. (eq (get-text-property p 'face) 'org-date))
  12734. (remove-text-properties
  12735. p (setq p (next-single-property-change p 'display))
  12736. '(display t))))
  12737. (set-buffer-modified-p bmp)))
  12738. (org-restart-font-lock)
  12739. (setq org-table-may-need-update t)
  12740. (if org-display-custom-times
  12741. (message "Time stamps are overlaid with custom format")
  12742. (message "Time stamp overlays removed")))
  12743. (defun org-display-custom-time (beg end)
  12744. "Overlay modified time stamp format over timestamp between BEG and END."
  12745. (let* ((ts (buffer-substring beg end))
  12746. t1 with-hm tf time str (off 0))
  12747. (save-match-data
  12748. (setq t1 (org-parse-time-string ts t))
  12749. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12750. (setq off (- (match-end 0) (match-beginning 0)))))
  12751. (setq end (- end off))
  12752. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12753. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12754. time (org-fix-decoded-time t1)
  12755. str (org-add-props
  12756. (format-time-string
  12757. (substring tf 1 -1) (org-encode-time time))
  12758. nil 'mouse-face 'highlight))
  12759. (put-text-property beg end 'display str)))
  12760. (defun org-fix-decoded-time (time)
  12761. "Set 0 instead of nil for the first 6 elements of time.
  12762. Don't touch the rest."
  12763. (let ((n 0))
  12764. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12765. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12766. "Difference between TIMESTAMP-STRING and now in days.
  12767. If SECONDS is non-nil, return the difference in seconds."
  12768. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12769. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12770. (funcall fdiff nil))))
  12771. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12772. "Is the time in TIMESTAMP-STRING close to the current date?"
  12773. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12774. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12775. (not (org-entry-is-done-p))))
  12776. (defun org-get-wdays (ts &optional delay zero-delay)
  12777. "Get the deadline lead time appropriate for timestring TS.
  12778. When DELAY is non-nil, get the delay time for scheduled items
  12779. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12780. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12781. don't try to find the delay cookie in the scheduled timestamp."
  12782. (let ((tv (if delay org-scheduled-delay-days
  12783. org-deadline-warning-days)))
  12784. (cond
  12785. ((or (and delay (< tv 0))
  12786. (and delay zero-delay (<= tv 0))
  12787. (and (not delay) (<= tv 0)))
  12788. ;; Enforce this value no matter what
  12789. (- tv))
  12790. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12791. ;; lead time is specified.
  12792. (floor (* (string-to-number (match-string 1 ts))
  12793. (cdr (assoc (match-string 2 ts)
  12794. '(("d" . 1) ("w" . 7)
  12795. ("m" . 30.4) ("y" . 365.25)
  12796. ("h" . 0.041667)))))))
  12797. ;; go for the default.
  12798. (t tv))))
  12799. (defun org-calendar-select-mouse (ev)
  12800. "Return to `org-read-date' with the date currently selected.
  12801. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12802. (interactive "e")
  12803. (mouse-set-point ev)
  12804. (when (calendar-cursor-to-date)
  12805. (let* ((date (calendar-cursor-to-date))
  12806. (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12807. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12808. (when (active-minibuffer-window) (exit-minibuffer))))
  12809. (defun org-check-deadlines (ndays)
  12810. "Check if there are any deadlines due or past due.
  12811. A deadline is considered due if it happens within `org-deadline-warning-days'
  12812. days from today's date. If the deadline appears in an entry marked DONE,
  12813. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12814. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12815. are shown."
  12816. (interactive "P")
  12817. (let* ((org-warn-days
  12818. (cond
  12819. ((equal ndays '(4)) 100000)
  12820. (ndays (prefix-numeric-value ndays))
  12821. (t (abs org-deadline-warning-days))))
  12822. (case-fold-search nil)
  12823. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12824. (callback
  12825. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12826. (message "%d deadlines past-due or due within %d days"
  12827. (org-occur regexp nil callback)
  12828. org-warn-days)))
  12829. (defsubst org-re-timestamp (type)
  12830. "Return a regexp for timestamp TYPE.
  12831. Allowed values for TYPE are:
  12832. all: all timestamps
  12833. active: only active timestamps (<...>)
  12834. inactive: only inactive timestamps ([...])
  12835. scheduled: only scheduled timestamps
  12836. deadline: only deadline timestamps
  12837. closed: only closed time-stamps
  12838. When TYPE is nil, fall back on returning a regexp that matches
  12839. both scheduled and deadline timestamps."
  12840. (cl-case type
  12841. (all org-ts-regexp-both)
  12842. (active org-ts-regexp)
  12843. (inactive org-ts-regexp-inactive)
  12844. (scheduled org-scheduled-time-regexp)
  12845. (deadline org-deadline-time-regexp)
  12846. (closed org-closed-time-regexp)
  12847. (otherwise
  12848. (concat "\\<"
  12849. (regexp-opt (list org-deadline-string org-scheduled-string))
  12850. " *<\\([^>]+\\)>"))))
  12851. (defun org-check-before-date (d)
  12852. "Check if there are deadlines or scheduled entries before date D."
  12853. (interactive (list (org-read-date)))
  12854. (let* ((case-fold-search nil)
  12855. (regexp (org-re-timestamp org-ts-type))
  12856. (ts-type org-ts-type)
  12857. (callback
  12858. (lambda ()
  12859. (let ((match (match-string 1)))
  12860. (and (if (memq ts-type '(active inactive all))
  12861. (eq (org-element-type (save-excursion
  12862. (backward-char)
  12863. (org-element-context)))
  12864. 'timestamp)
  12865. (org-at-planning-p))
  12866. (time-less-p
  12867. (org-time-string-to-time match)
  12868. (org-time-string-to-time d)))))))
  12869. (message "%d entries before %s"
  12870. (org-occur regexp nil callback)
  12871. d)))
  12872. (defun org-check-after-date (d)
  12873. "Check if there are deadlines or scheduled entries after date D."
  12874. (interactive (list (org-read-date)))
  12875. (let* ((case-fold-search nil)
  12876. (regexp (org-re-timestamp org-ts-type))
  12877. (ts-type org-ts-type)
  12878. (callback
  12879. (lambda ()
  12880. (let ((match (match-string 1)))
  12881. (and (if (memq ts-type '(active inactive all))
  12882. (eq (org-element-type (save-excursion
  12883. (backward-char)
  12884. (org-element-context)))
  12885. 'timestamp)
  12886. (org-at-planning-p))
  12887. (not (time-less-p
  12888. (org-time-string-to-time match)
  12889. (org-time-string-to-time d))))))))
  12890. (message "%d entries after %s"
  12891. (org-occur regexp nil callback)
  12892. d)))
  12893. (defun org-check-dates-range (start-date end-date)
  12894. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12895. (interactive (list (org-read-date nil nil nil "Range starts")
  12896. (org-read-date nil nil nil "Range end")))
  12897. (let ((case-fold-search nil)
  12898. (regexp (org-re-timestamp org-ts-type))
  12899. (callback
  12900. (let ((type org-ts-type))
  12901. (lambda ()
  12902. (let ((match (match-string 1)))
  12903. (and
  12904. (if (memq type '(active inactive all))
  12905. (eq (org-element-type (save-excursion
  12906. (backward-char)
  12907. (org-element-context)))
  12908. 'timestamp)
  12909. (org-at-planning-p))
  12910. (not (time-less-p
  12911. (org-time-string-to-time match)
  12912. (org-time-string-to-time start-date)))
  12913. (time-less-p
  12914. (org-time-string-to-time match)
  12915. (org-time-string-to-time end-date))))))))
  12916. (message "%d entries between %s and %s"
  12917. (org-occur regexp nil callback) start-date end-date)))
  12918. (defun org-evaluate-time-range (&optional to-buffer)
  12919. "Evaluate a time range by computing the difference between start and end.
  12920. Normally the result is just printed in the echo area, but with prefix arg
  12921. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12922. If the time range is actually in a table, the result is inserted into the
  12923. next column.
  12924. For time difference computation, a year is assumed to be exactly 365
  12925. days in order to avoid rounding problems."
  12926. (interactive "P")
  12927. (or
  12928. (org-clock-update-time-maybe)
  12929. (save-excursion
  12930. (unless (org-at-date-range-p t)
  12931. (goto-char (point-at-bol))
  12932. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12933. (unless (org-at-date-range-p t)
  12934. (user-error "Not at a time-stamp range, and none found in current line")))
  12935. (let* ((ts1 (match-string 1))
  12936. (ts2 (match-string 2))
  12937. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12938. (match-end (match-end 0))
  12939. (time1 (org-time-string-to-time ts1))
  12940. (time2 (org-time-string-to-time ts2))
  12941. (diff (abs (float-time (time-subtract time2 time1))))
  12942. (negative (time-less-p time2 time1))
  12943. ;; (ys (floor (* 365 24 60 60)))
  12944. (ds (* 24 60 60))
  12945. (hs (* 60 60))
  12946. (fy "%dy %dd %02d:%02d")
  12947. (fy1 "%dy %dd")
  12948. (fd "%dd %02d:%02d")
  12949. (fd1 "%dd")
  12950. (fh "%02d:%02d")
  12951. y d h m align)
  12952. (if havetime
  12953. (setq ; y (floor diff ys) diff (mod diff ys)
  12954. y 0
  12955. d (floor diff ds) diff (mod diff ds)
  12956. h (floor diff hs) diff (mod diff hs)
  12957. m (floor diff 60))
  12958. (setq ; y (floor diff ys) diff (mod diff ys)
  12959. y 0
  12960. d (round diff ds)
  12961. h 0 m 0))
  12962. (if (not to-buffer)
  12963. (message "%s" (org-make-tdiff-string y d h m))
  12964. (if (org-at-table-p)
  12965. (progn
  12966. (goto-char match-end)
  12967. (setq align t)
  12968. (and (looking-at " *|") (goto-char (match-end 0))))
  12969. (goto-char match-end))
  12970. (when (looking-at
  12971. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12972. (replace-match ""))
  12973. (when negative (insert " -"))
  12974. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12975. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12976. (insert " " (format fh h m))))
  12977. (when align (org-table-align))
  12978. (message "Time difference inserted")))))
  12979. (defun org-make-tdiff-string (y d h m)
  12980. (let ((fmt "")
  12981. (l nil))
  12982. (when (> y 0)
  12983. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12984. (push y l))
  12985. (when (> d 0)
  12986. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12987. (push d l))
  12988. (when (> h 0)
  12989. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12990. (push h l))
  12991. (when (> m 0)
  12992. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12993. (push m l))
  12994. (apply 'format fmt (nreverse l))))
  12995. (defun org-time-string-to-time (s)
  12996. "Convert timestamp string S into internal time."
  12997. (org-encode-time (org-parse-time-string s)))
  12998. (defun org-time-string-to-seconds (s)
  12999. "Convert a timestamp string S into a number of seconds."
  13000. (float-time (org-time-string-to-time s)))
  13001. (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13002. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13003. "Convert time stamp S to an absolute day number.
  13004. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13005. stamp, get the closest date to DAYNR. If PREFER is
  13006. `past' (respectively `future') return a date past (respectively
  13007. after) or equal to DAYNR.
  13008. POS is the location of time stamp S, as a buffer position in
  13009. BUFFER.
  13010. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13011. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13012. signaled."
  13013. (cond
  13014. ((string-match "\\`%%\\((.*)\\)" s)
  13015. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13016. ;; only able to match individual dates. If it fails, raise an
  13017. ;; error.
  13018. (if (and daynr
  13019. (org-diary-sexp-entry
  13020. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13021. daynr
  13022. (signal 'org-diary-sexp-no-match (list s))))
  13023. (daynr (org-closest-date s daynr prefer))
  13024. (t (time-to-days
  13025. (condition-case errdata
  13026. (org-time-string-to-time s)
  13027. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13028. s
  13029. (if (not (and buffer pos)) ""
  13030. (format-message " at %d in buffer `%s'" pos buffer))
  13031. (cdr errdata))))))))
  13032. (defun org-days-to-iso-week (days)
  13033. "Return the ISO week number."
  13034. (require 'cal-iso)
  13035. (car (calendar-iso-from-absolute days)))
  13036. (defun org-small-year-to-year (year)
  13037. "Convert 2-digit years into 4-digit years.
  13038. YEAR is expanded into one of the 30 next years, if possible, or
  13039. into a past one. Any year larger than 99 is returned unchanged."
  13040. (if (>= year 100) year
  13041. (let* ((current (string-to-number (format-time-string "%Y")))
  13042. (century (/ current 100))
  13043. (offset (- year (% current 100))))
  13044. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13045. ((> offset -70) (+ (* century 100) year))
  13046. (t (+ (* (1+ century) 100) year))))))
  13047. (defun org-time-from-absolute (d)
  13048. "Return the time corresponding to date D.
  13049. D may be an absolute day number, or a calendar-type list (month day year)."
  13050. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13051. (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13052. (defvar org-agenda-current-date)
  13053. (defun org-calendar-holiday ()
  13054. "List of holidays, for Diary display in Org mode."
  13055. (require 'holidays)
  13056. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13057. (and hl (mapconcat #'identity hl "; "))))
  13058. (defun org-diary-sexp-entry (sexp entry d)
  13059. "Process a SEXP diary ENTRY for date D."
  13060. (require 'diary-lib)
  13061. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13062. ;; dynamically.
  13063. (let* ((sexp `(let ((entry ,entry)
  13064. (date ',d))
  13065. ,(car (read-from-string sexp))))
  13066. ;; FIXME: Do not use (eval ... t) in the following sexp as
  13067. ;; diary vars are still using dynamic scope.
  13068. (result (if calendar-debug-sexp (eval sexp)
  13069. (condition-case nil
  13070. (eval sexp)
  13071. (error
  13072. (beep)
  13073. (message "Bad sexp at line %d in %s: %s"
  13074. (org-current-line)
  13075. (buffer-file-name) sexp)
  13076. (sleep-for 2))))))
  13077. (cond ((stringp result) (split-string result "; "))
  13078. ((and (consp result)
  13079. (not (consp (cdr result)))
  13080. (stringp (cdr result))) (cdr result))
  13081. ((and (consp result)
  13082. (stringp (car result))) result)
  13083. (result entry))))
  13084. (defun org-diary-to-ical-string (frombuf)
  13085. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13086. This uses the icalendar.el library."
  13087. (let* ((tmpdir temporary-file-directory)
  13088. (tmpfile (make-temp-name
  13089. (expand-file-name "orgics" tmpdir)))
  13090. buf rtn b e)
  13091. (with-current-buffer frombuf
  13092. (icalendar-export-region (point-min) (point-max) tmpfile)
  13093. (setq buf (find-buffer-visiting tmpfile))
  13094. (set-buffer buf)
  13095. (goto-char (point-min))
  13096. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13097. (setq b (match-beginning 0)))
  13098. (goto-char (point-max))
  13099. (when (re-search-backward "^END:VEVENT" nil t)
  13100. (setq e (match-end 0)))
  13101. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13102. (kill-buffer buf)
  13103. (delete-file tmpfile)
  13104. rtn))
  13105. (defun org-closest-date (start current prefer)
  13106. "Return closest date to CURRENT starting from START.
  13107. CURRENT and START are both time stamps.
  13108. When PREFER is `past', return a date that is either CURRENT or
  13109. past. When PREFER is `future', return a date that is either
  13110. CURRENT or future.
  13111. Only time stamps with a repeater are modified. Any other time
  13112. stamp stay unchanged. In any case, return value is an absolute
  13113. day number."
  13114. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13115. ;; No repeater. Do not shift time stamp.
  13116. (time-to-days (org-time-string-to-time start))
  13117. (let ((value (string-to-number (match-string 1 start)))
  13118. (type (match-string 2 start)))
  13119. (if (= 0 value)
  13120. ;; Repeater with a 0-value is considered as void.
  13121. (time-to-days (org-time-string-to-time start))
  13122. (let* ((base (org-date-to-gregorian start))
  13123. (target (org-date-to-gregorian current))
  13124. (sday (calendar-absolute-from-gregorian base))
  13125. (cday (calendar-absolute-from-gregorian target))
  13126. n1 n2)
  13127. ;; If START is already past CURRENT, just return START.
  13128. (if (<= cday sday) sday
  13129. ;; Compute closest date before (N1) and closest date past
  13130. ;; (N2) CURRENT.
  13131. (pcase type
  13132. ("h"
  13133. (let ((missing-hours
  13134. (mod (+ (- (* 24 (- cday sday))
  13135. (nth 2 (org-parse-time-string start)))
  13136. org-extend-today-until)
  13137. value)))
  13138. (setf n1 (if (= missing-hours 0) cday
  13139. (- cday (1+ (/ missing-hours 24)))))
  13140. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13141. ((or "d" "w")
  13142. (let ((value (if (equal type "w") (* 7 value) value)))
  13143. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13144. (setf n2 (+ n1 value))))
  13145. ("m"
  13146. (let* ((add-months
  13147. (lambda (d n)
  13148. ;; Add N months to gregorian date D, i.e.,
  13149. ;; a list (MONTH DAY YEAR). Return a valid
  13150. ;; gregorian date.
  13151. (let ((m (+ (nth 0 d) n)))
  13152. (list (mod m 12)
  13153. (nth 1 d)
  13154. (+ (/ m 12) (nth 2 d))))))
  13155. (months ; Complete months to TARGET.
  13156. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13157. (- (nth 0 target) (nth 0 base))
  13158. ;; If START's day is greater than
  13159. ;; TARGET's, remove incomplete month.
  13160. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13161. value)
  13162. value))
  13163. (before (funcall add-months base months)))
  13164. (setf n1 (calendar-absolute-from-gregorian before))
  13165. (setf n2
  13166. (calendar-absolute-from-gregorian
  13167. (funcall add-months before value)))))
  13168. (_
  13169. (let* ((d (nth 1 base))
  13170. (m (nth 0 base))
  13171. (y (nth 2 base))
  13172. (years ; Complete years to TARGET.
  13173. (* (/ (- (nth 2 target)
  13174. y
  13175. ;; If START's month and day are
  13176. ;; greater than TARGET's, remove
  13177. ;; incomplete year.
  13178. (if (or (> (nth 0 target) m)
  13179. (and (= (nth 0 target) m)
  13180. (> (nth 1 target) d)))
  13181. 0
  13182. 1))
  13183. value)
  13184. value))
  13185. (before (list m d (+ y years))))
  13186. (setf n1 (calendar-absolute-from-gregorian before))
  13187. (setf n2 (calendar-absolute-from-gregorian
  13188. (list m d (+ (nth 2 before) value)))))))
  13189. ;; Handle PREFER parameter, if any.
  13190. (cond
  13191. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13192. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13193. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13194. (defun org-date-to-gregorian (d)
  13195. "Turn any specification of date D into a Gregorian date for the calendar."
  13196. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13197. ((and (listp d) (= (length d) 3)) d)
  13198. ((stringp d)
  13199. (let ((d (org-parse-time-string d)))
  13200. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13201. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13202. (defun org-timestamp-up (&optional arg)
  13203. "Increase the date item at the cursor by one.
  13204. If the cursor is on the year, change the year. If it is on the month,
  13205. the day or the time, change that. If the cursor is on the enclosing
  13206. bracket, change the timestamp type.
  13207. With prefix ARG, change by that many units."
  13208. (interactive "p")
  13209. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13210. (defun org-timestamp-down (&optional arg)
  13211. "Decrease the date item at the cursor by one.
  13212. If the cursor is on the year, change the year. If it is on the month,
  13213. the day or the time, change that. If the cursor is on the enclosing
  13214. bracket, change the timestamp type.
  13215. With prefix ARG, change by that many units."
  13216. (interactive "p")
  13217. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13218. (defun org-timestamp-up-day (&optional arg)
  13219. "Increase the date in the time stamp by one day.
  13220. With prefix ARG, change that many days."
  13221. (interactive "p")
  13222. (if (and (not (org-at-timestamp-p 'lax))
  13223. (org-at-heading-p))
  13224. (org-todo 'up)
  13225. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13226. (defun org-timestamp-down-day (&optional arg)
  13227. "Decrease the date in the time stamp by one day.
  13228. With prefix ARG, change that many days."
  13229. (interactive "p")
  13230. (if (and (not (org-at-timestamp-p 'lax))
  13231. (org-at-heading-p))
  13232. (org-todo 'down)
  13233. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13234. (defun org-at-timestamp-p (&optional extended)
  13235. "Non-nil if point is inside a timestamp.
  13236. By default, the function only consider syntactically valid active
  13237. timestamps. However, the caller may have a broader definition
  13238. for timestamps. As a consequence, optional argument EXTENDED can
  13239. be set to the following values
  13240. `inactive'
  13241. Include also syntactically valid inactive timestamps.
  13242. `agenda'
  13243. Include timestamps allowed in Agenda, i.e., those in
  13244. properties drawers, planning lines and clock lines.
  13245. `lax'
  13246. Ignore context. The function matches any part of the
  13247. document looking like a timestamp. This includes comments,
  13248. example blocks...
  13249. For backward-compatibility with Org 9.0, every other non-nil
  13250. value is equivalent to `inactive'.
  13251. When at a timestamp, return the position of the point as a symbol
  13252. among `bracket', `after', `year', `month', `hour', `minute',
  13253. `day' or a number of character from the last know part of the
  13254. time stamp. If diary sexp timestamps, any point inside the timestamp
  13255. is considered `day' (i.e. only `bracket', `day', and `after' return
  13256. values are possible).
  13257. When matching, the match groups are the following:
  13258. group 1: year, if any
  13259. group 2: month, if any
  13260. group 3: day number, if any
  13261. group 4: day name, if any
  13262. group 5: hours, if any
  13263. group 6: minutes, if any"
  13264. (let* ((regexp
  13265. (if extended
  13266. (if (eq extended 'agenda)
  13267. (rx-to-string
  13268. `(or (regexp ,org-ts-regexp3)
  13269. (regexp ,org-element--timestamp-regexp)))
  13270. org-ts-regexp3)
  13271. org-ts-regexp2))
  13272. (pos (point))
  13273. (match?
  13274. (let ((boundaries (org-in-regexp regexp)))
  13275. (save-match-data
  13276. (cond ((null boundaries) nil)
  13277. ((eq extended 'lax) t)
  13278. (t
  13279. (or (and (eq extended 'agenda)
  13280. (or (org-at-planning-p)
  13281. (org-at-property-p)
  13282. (and (bound-and-true-p
  13283. org-agenda-include-inactive-timestamps)
  13284. (org-at-clock-log-p))))
  13285. (eq 'timestamp
  13286. (save-excursion
  13287. (when (= pos (cdr boundaries)) (forward-char -1))
  13288. (org-element-type (org-element-context)))))))))))
  13289. (cond
  13290. ((not match?) nil)
  13291. ((= pos (match-beginning 0)) 'bracket)
  13292. ;; Distinguish location right before the closing bracket from
  13293. ;; right after it.
  13294. ((= pos (1- (match-end 0))) 'bracket)
  13295. ((= pos (match-end 0)) 'after)
  13296. ((org-pos-in-match-range pos 2) 'year)
  13297. ((org-pos-in-match-range pos 3) 'month)
  13298. ((org-pos-in-match-range pos 7) 'hour)
  13299. ((org-pos-in-match-range pos 8) 'minute)
  13300. ((or (org-pos-in-match-range pos 4)
  13301. (org-pos-in-match-range pos 5)) 'day)
  13302. ((and (or (match-end 8) (match-end 5))
  13303. (> pos (or (match-end 8) (match-end 5)))
  13304. (< pos (match-end 0)))
  13305. (- pos (or (match-end 8) (match-end 5))))
  13306. (t 'day))))
  13307. (defun org-toggle-timestamp-type ()
  13308. "Toggle the type (<active> or [inactive]) of a time stamp."
  13309. (interactive)
  13310. (when (org-at-timestamp-p 'lax)
  13311. (let ((beg (match-beginning 0)) (end (match-end 0))
  13312. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13313. (save-excursion
  13314. (goto-char beg)
  13315. (while (re-search-forward "[][<>]" end t)
  13316. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13317. t t)))
  13318. (message "Timestamp is now %sactive"
  13319. (if (equal (char-after beg) ?<) "" "in")))))
  13320. (defun org-at-clock-log-p ()
  13321. "Non-nil if point is on a clock log line."
  13322. (and (org-match-line org-clock-line-re)
  13323. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13324. (defvar org-clock-history) ; defined in org-clock.el
  13325. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13326. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13327. "Change the date in the time stamp at point.
  13328. The date is changed by N times WHAT. WHAT can be `day', `month',
  13329. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13330. position in the timestamp determines what is changed.
  13331. When optional argument UPDOWN is non-nil, minutes are rounded
  13332. according to `org-time-stamp-rounding-minutes'.
  13333. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13334. \"--2d\"."
  13335. (let ((origin (point))
  13336. (timestamp? (org-at-timestamp-p 'lax))
  13337. origin-cat
  13338. with-hm inactive
  13339. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13340. extra rem
  13341. ts time time0 fixnext clrgx)
  13342. (unless timestamp? (user-error "Not at a timestamp"))
  13343. (if (and (not what) (eq timestamp? 'bracket))
  13344. (org-toggle-timestamp-type)
  13345. ;; Point isn't on brackets. Remember the part of the time-stamp
  13346. ;; the point was in. Indeed, size of time-stamps may change,
  13347. ;; but point must be kept in the same category nonetheless.
  13348. (setq origin-cat timestamp?)
  13349. (when (and (not what) (not (eq timestamp? 'day))
  13350. org-display-custom-times
  13351. (get-text-property (point) 'display)
  13352. (not (get-text-property (1- (point)) 'display)))
  13353. (setq timestamp? 'day))
  13354. (setq timestamp? (or what timestamp?)
  13355. inactive (= (char-after (match-beginning 0)) ?\[)
  13356. ts (match-string 0))
  13357. (replace-match "")
  13358. (when (string-match
  13359. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13360. ts)
  13361. (setq extra (match-string 1 ts))
  13362. (when suppress-tmp-delay
  13363. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13364. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13365. (setq with-hm t))
  13366. (setq time0 (org-parse-time-string ts))
  13367. (when (and updown
  13368. (eq timestamp? 'minute)
  13369. (not current-prefix-arg))
  13370. ;; This looks like s-up and s-down. Change by one rounding step.
  13371. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13372. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13373. (setcar (cdr time0) (+ (nth 1 time0)
  13374. (if (> n 0) (- rem) (- dm rem))))))
  13375. (setq time
  13376. (org-encode-time
  13377. (apply #'list
  13378. (or (car time0) 0)
  13379. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13380. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13381. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13382. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13383. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13384. (nthcdr 6 time0))))
  13385. (when (and (memq timestamp? '(hour minute))
  13386. extra
  13387. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13388. (setq extra (org-modify-ts-extra
  13389. extra
  13390. (if (eq timestamp? 'hour) 2 5)
  13391. n dm)))
  13392. (when (integerp timestamp?)
  13393. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13394. (when (eq what 'calendar)
  13395. (let ((cal-date (org-get-date-from-calendar)))
  13396. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13397. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13398. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13399. (setcar time0 (or (car time0) 0))
  13400. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13401. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13402. (setq time (org-encode-time time0))))
  13403. ;; Insert the new time-stamp, and ensure point stays in the same
  13404. ;; category as before (i.e. not after the last position in that
  13405. ;; category).
  13406. (let ((pos (point)))
  13407. ;; Stay before inserted string. `save-excursion' is of no use.
  13408. (setq org-last-changed-timestamp
  13409. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13410. (goto-char pos))
  13411. (save-match-data
  13412. (looking-at org-ts-regexp3)
  13413. (goto-char
  13414. (pcase origin-cat
  13415. ;; `day' category ends before `hour' if any, or at the end
  13416. ;; of the day name.
  13417. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13418. (`hour (min (match-end 7) origin))
  13419. (`minute (min (1- (match-end 8)) origin))
  13420. ((pred integerp) (min (1- (match-end 0)) origin))
  13421. ;; Point was right after the time-stamp. However, the
  13422. ;; time-stamp length might have changed, so refer to
  13423. ;; (match-end 0) instead.
  13424. (`after (match-end 0))
  13425. ;; `year' and `month' have both fixed size: point couldn't
  13426. ;; have moved into another part.
  13427. (_ origin))))
  13428. ;; Update clock if on a CLOCK line.
  13429. (org-clock-update-time-maybe)
  13430. ;; Maybe adjust the closest clock in `org-clock-history'
  13431. (when org-clock-adjust-closest
  13432. (if (not (and (org-at-clock-log-p)
  13433. (< 1 (length (delq nil (mapcar 'marker-position
  13434. org-clock-history))))))
  13435. (message "No clock to adjust")
  13436. (cond ((save-excursion ; fix previous clock?
  13437. (re-search-backward org-ts-regexp0 nil t)
  13438. (looking-back (concat org-clock-string " \\[")
  13439. (line-beginning-position)))
  13440. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13441. ((save-excursion ; fix next clock?
  13442. (re-search-backward org-ts-regexp0 nil t)
  13443. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13444. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13445. (save-window-excursion
  13446. ;; Find closest clock to point, adjust the previous/next one in history
  13447. (let* ((p (save-excursion (org-back-to-heading t)))
  13448. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13449. (clfixnth
  13450. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13451. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13452. (if (not clfixpos)
  13453. (message "No clock to adjust")
  13454. (save-excursion
  13455. (org-goto-marker-or-bmk clfixpos)
  13456. (org-fold-show-subtree)
  13457. (when (re-search-forward clrgx nil t)
  13458. (goto-char (match-beginning 1))
  13459. (let (org-clock-adjust-closest)
  13460. (org-timestamp-change n timestamp? updown))
  13461. (message "Clock adjusted in %s for heading: %s"
  13462. (file-name-nondirectory (buffer-file-name))
  13463. (org-get-heading t t)))))))))
  13464. ;; Try to recenter the calendar window, if any.
  13465. (when (and org-calendar-follow-timestamp-change
  13466. (get-buffer-window "*Calendar*" t)
  13467. (memq timestamp? '(day month year)))
  13468. (org-recenter-calendar (time-to-days time))))))
  13469. (defun org-modify-ts-extra (s pos n dm)
  13470. "Change the different parts of the lead-time and repeat fields in timestamp."
  13471. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13472. ng h m new rem)
  13473. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13474. (cond
  13475. ((or (org-pos-in-match-range pos 2)
  13476. (org-pos-in-match-range pos 3))
  13477. (setq m (string-to-number (match-string 3 s))
  13478. h (string-to-number (match-string 2 s)))
  13479. (if (org-pos-in-match-range pos 2)
  13480. (setq h (+ h n))
  13481. (setq n (* dm (with-no-warnings (cl-signum n))))
  13482. (unless (= 0 (setq rem (% m dm)))
  13483. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13484. (setq m (+ m n)))
  13485. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13486. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13487. (setq h (mod h 24))
  13488. (setq ng 1 new (format "-%02d:%02d" h m)))
  13489. ((org-pos-in-match-range pos 6)
  13490. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13491. ((org-pos-in-match-range pos 5)
  13492. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13493. ((org-pos-in-match-range pos 9)
  13494. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13495. ((org-pos-in-match-range pos 8)
  13496. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13497. (when ng
  13498. (setq s (concat
  13499. (substring s 0 (match-beginning ng))
  13500. new
  13501. (substring s (match-end ng))))))
  13502. s))
  13503. (defun org-recenter-calendar (d)
  13504. "If the calendar is visible, recenter it to date D."
  13505. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13506. (when cwin
  13507. (let ((calendar-move-hook nil))
  13508. (with-selected-window cwin
  13509. (calendar-goto-date
  13510. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13511. (defun org-goto-calendar (&optional arg)
  13512. "Go to the Emacs calendar at the current date.
  13513. If there is a time stamp in the current line, go to that date.
  13514. A prefix ARG can be used to force the current date."
  13515. (interactive "P")
  13516. (let ((calendar-move-hook nil)
  13517. (calendar-view-holidays-initially-flag nil)
  13518. (calendar-view-diary-initially-flag nil)
  13519. diff)
  13520. (when (or (org-at-timestamp-p 'lax)
  13521. (org-match-line (concat ".*" org-ts-regexp)))
  13522. (let ((d1 (time-to-days nil))
  13523. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13524. (setq diff (- d2 d1))))
  13525. (calendar)
  13526. (calendar-goto-today)
  13527. (when (and diff (not arg)) (calendar-forward-day diff))))
  13528. (defun org-get-date-from-calendar ()
  13529. "Return a list (month day year) of date at point in calendar."
  13530. (with-current-buffer "*Calendar*"
  13531. (save-match-data
  13532. (calendar-cursor-to-date))))
  13533. (defun org-date-from-calendar ()
  13534. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13535. If there is already a time stamp at the cursor position, update it."
  13536. (interactive)
  13537. (if (org-at-timestamp-p 'lax)
  13538. (org-timestamp-change 0 'calendar)
  13539. (let ((cal-date (org-get-date-from-calendar)))
  13540. (org-insert-time-stamp
  13541. (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13542. (defcustom org-image-actual-width t
  13543. "When non-nil, use the actual width of images when inlining them.
  13544. When set to a number, use imagemagick (when available) to set the
  13545. image's width to this value.
  13546. When set to a number in a list, try to get the width from any
  13547. #+ATTR.* keyword if it matches a width specification like
  13548. #+ATTR_HTML: :width 300px
  13549. and fall back on that number if none is found.
  13550. When set to nil, try to get the width from an #+ATTR.* keyword
  13551. and fall back on the original width if none is found.
  13552. When set to any other non-nil value, always use the image width.
  13553. This requires Emacs >= 24.1, built with imagemagick support."
  13554. :group 'org-appearance
  13555. :version "24.4"
  13556. :package-version '(Org . "8.0")
  13557. :type '(choice
  13558. (const :tag "Use the image width" t)
  13559. (integer :tag "Use a number of pixels")
  13560. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13561. (const :tag "Use #+ATTR* or don't resize" nil)))
  13562. (defcustom org-agenda-inhibit-startup nil
  13563. "Inhibit startup when preparing agenda buffers.
  13564. When this variable is t, the initialization of the Org agenda
  13565. buffers is inhibited: e.g. the visibility state is not set, the
  13566. tables are not re-aligned, etc."
  13567. :type 'boolean
  13568. :version "24.3"
  13569. :group 'org-agenda)
  13570. (defcustom org-agenda-ignore-properties nil
  13571. "Avoid updating text properties when building the agenda.
  13572. Properties are used to prepare buffers for effort estimates,
  13573. appointments, statistics and subtree-local categories.
  13574. If you don't use these in the agenda, you can add them to this
  13575. list and agenda building will be a bit faster.
  13576. The value is a list, with zero or more of the symbols `effort', `appt',
  13577. `stats' or `category'."
  13578. :type '(set :greedy t
  13579. (const effort)
  13580. (const appt)
  13581. (const stats)
  13582. (const category))
  13583. :version "26.1"
  13584. :package-version '(Org . "8.3")
  13585. :group 'org-agenda)
  13586. ;;;; Files
  13587. (defun org-save-all-org-buffers ()
  13588. "Save all Org buffers without user confirmation."
  13589. (interactive)
  13590. (message "Saving all Org buffers...")
  13591. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13592. (when (featurep 'org-id) (org-id-locations-save))
  13593. (message "Saving all Org buffers... done"))
  13594. (defun org-revert-all-org-buffers ()
  13595. "Revert all Org buffers.
  13596. Prompt for confirmation when there are unsaved changes.
  13597. Be sure you know what you are doing before letting this function
  13598. overwrite your changes.
  13599. This function is useful in a setup where one tracks Org files
  13600. with a version control system, to revert on one machine after pulling
  13601. changes from another. I believe the procedure must be like this:
  13602. 1. \\[org-save-all-org-buffers]
  13603. 2. Pull changes from the other machine, resolve conflicts
  13604. 3. \\[org-revert-all-org-buffers]"
  13605. (interactive)
  13606. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13607. (user-error "Abort"))
  13608. (save-excursion
  13609. (save-window-excursion
  13610. (dolist (b (buffer-list))
  13611. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13612. (with-current-buffer b buffer-file-name))
  13613. (pop-to-buffer-same-window b)
  13614. (revert-buffer t 'no-confirm)))
  13615. (when (and (featurep 'org-id) org-id-track-globally)
  13616. (org-id-locations-load)))))
  13617. ;;;; Agenda files
  13618. ;;;###autoload
  13619. (defun org-switchb (&optional arg)
  13620. "Switch between Org buffers.
  13621. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13622. With `\\[universal-argument] \\[universal-argument]' \
  13623. prefix, restrict available buffers to agenda files."
  13624. (interactive "P")
  13625. (let ((blist (org-buffer-list
  13626. (cond ((equal arg '(4)) 'files)
  13627. ((equal arg '(16)) 'agenda)))))
  13628. (pop-to-buffer-same-window
  13629. (completing-read "Org buffer: "
  13630. (mapcar #'list (mapcar #'buffer-name blist))
  13631. nil t))))
  13632. (defun org-agenda-files (&optional unrestricted archives)
  13633. "Get the list of agenda files.
  13634. Optional UNRESTRICTED means return the full list even if a restriction
  13635. is currently in place.
  13636. When ARCHIVES is t, include all archive files that are really being
  13637. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13638. `org-agenda-archives-mode' is t."
  13639. (let ((files
  13640. (cond
  13641. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13642. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13643. ((listp org-agenda-files) org-agenda-files)
  13644. (t (error "Invalid value of `org-agenda-files'")))))
  13645. (setq files (apply 'append
  13646. (mapcar (lambda (f)
  13647. (if (file-directory-p f)
  13648. (directory-files
  13649. f t org-agenda-file-regexp)
  13650. (list (expand-file-name f org-directory))))
  13651. files)))
  13652. (when org-agenda-skip-unavailable-files
  13653. (setq files (delq nil
  13654. (mapcar (lambda (file)
  13655. (and (file-readable-p file) file))
  13656. files))))
  13657. (when (or (eq archives t)
  13658. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13659. (setq files (org-add-archive-files files)))
  13660. files))
  13661. (defun org-agenda-file-p (&optional file)
  13662. "Return non-nil, if FILE is an agenda file.
  13663. If FILE is omitted, use the file associated with the current
  13664. buffer."
  13665. (let ((fname (or file (buffer-file-name))))
  13666. (and fname
  13667. (member (file-truename fname)
  13668. (mapcar #'file-truename (org-agenda-files t))))))
  13669. (defun org-edit-agenda-file-list ()
  13670. "Edit the list of agenda files.
  13671. Depending on setup, this either uses customize to edit the variable
  13672. `org-agenda-files', or it visits the file that is holding the list. In the
  13673. latter case, the buffer is set up in a way that saving it automatically kills
  13674. the buffer and restores the previous window configuration."
  13675. (interactive)
  13676. (if (stringp org-agenda-files)
  13677. (let ((cw (current-window-configuration)))
  13678. (find-file org-agenda-files)
  13679. (setq-local org-window-configuration cw)
  13680. (add-hook 'after-save-hook
  13681. (lambda ()
  13682. (set-window-configuration
  13683. (prog1 org-window-configuration
  13684. (kill-buffer (current-buffer))))
  13685. (org-install-agenda-files-menu)
  13686. (message "New agenda file list installed"))
  13687. nil 'local)
  13688. (message "%s" (substitute-command-keys
  13689. "Edit list and finish with \\[save-buffer]")))
  13690. (customize-variable 'org-agenda-files)))
  13691. (defun org-store-new-agenda-file-list (list)
  13692. "Set new value for the agenda file list and save it correctly."
  13693. (if (stringp org-agenda-files)
  13694. (let ((fe (org-read-agenda-file-list t)) b u)
  13695. (while (setq b (find-buffer-visiting org-agenda-files))
  13696. (kill-buffer b))
  13697. (with-temp-file org-agenda-files
  13698. (insert
  13699. (mapconcat
  13700. (lambda (f) ;; Keep un-expanded entries.
  13701. (if (setq u (assoc f fe))
  13702. (cdr u)
  13703. f))
  13704. list "\n")
  13705. "\n")))
  13706. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13707. (org-insert-mode-line-in-empty-file nil))
  13708. (setq org-agenda-files list)
  13709. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13710. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13711. "Read the list of agenda files from a file.
  13712. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13713. filenames, used by `org-store-new-agenda-file-list' to write back
  13714. un-expanded file names."
  13715. (when (file-directory-p org-agenda-files)
  13716. (error "`org-agenda-files' cannot be a single directory"))
  13717. (when (stringp org-agenda-files)
  13718. (with-temp-buffer
  13719. (insert-file-contents org-agenda-files)
  13720. (mapcar
  13721. (lambda (f)
  13722. (let ((e (expand-file-name (substitute-in-file-name f)
  13723. org-directory)))
  13724. (if pair-with-expansion
  13725. (cons e f)
  13726. e)))
  13727. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13728. ;;;###autoload
  13729. (defun org-cycle-agenda-files ()
  13730. "Cycle through the files in `org-agenda-files'.
  13731. If the current buffer visits an agenda file, find the next one in the list.
  13732. If the current buffer does not, find the first agenda file."
  13733. (interactive)
  13734. (let* ((fs (or (org-agenda-files t)
  13735. (user-error "No agenda files")))
  13736. (files (copy-sequence fs))
  13737. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13738. file)
  13739. (when tcf
  13740. (while (and (setq file (pop files))
  13741. (not (equal (file-truename file) tcf)))))
  13742. (find-file (car (or files fs)))
  13743. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13744. (defun org-agenda-file-to-front (&optional to-end)
  13745. "Move/add the current file to the top of the agenda file list.
  13746. If the file is not present in the list, it is added to the front. If it is
  13747. present, it is moved there. With optional argument TO-END, add/move to the
  13748. end of the list."
  13749. (interactive "P")
  13750. (let ((org-agenda-skip-unavailable-files nil)
  13751. (file-alist (mapcar (lambda (x)
  13752. (cons (file-truename x) x))
  13753. (org-agenda-files t)))
  13754. (ctf (file-truename
  13755. (or buffer-file-name
  13756. (user-error "Please save the current buffer to a file"))))
  13757. x had)
  13758. (setq x (assoc ctf file-alist) had x)
  13759. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13760. (if to-end
  13761. (setq file-alist (append (delq x file-alist) (list x)))
  13762. (setq file-alist (cons x (delq x file-alist))))
  13763. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13764. (org-install-agenda-files-menu)
  13765. (message "File %s to %s of agenda file list"
  13766. (if had "moved" "added") (if to-end "end" "front"))))
  13767. (defun org-remove-file (&optional file)
  13768. "Remove current file from the list of files in variable `org-agenda-files'.
  13769. These are the files which are being checked for agenda entries.
  13770. Optional argument FILE means use this file instead of the current."
  13771. (interactive)
  13772. (let* ((org-agenda-skip-unavailable-files nil)
  13773. (file (or file buffer-file-name
  13774. (user-error "Current buffer does not visit a file")))
  13775. (true-file (file-truename file))
  13776. (afile (abbreviate-file-name file))
  13777. (files (delq nil (mapcar
  13778. (lambda (x)
  13779. (unless (equal true-file
  13780. (file-truename x))
  13781. x))
  13782. (org-agenda-files t)))))
  13783. (if (not (= (length files) (length (org-agenda-files t))))
  13784. (progn
  13785. (org-store-new-agenda-file-list files)
  13786. (org-install-agenda-files-menu)
  13787. (message "Removed from Org Agenda list: %s" afile))
  13788. (message "File was not in list: %s (not removed)" afile))))
  13789. (defun org-file-menu-entry (file)
  13790. (vector file (list 'find-file file) t))
  13791. (defun org-check-agenda-file (file)
  13792. "Make sure FILE exists. If not, ask user what to do."
  13793. (unless (file-exists-p file)
  13794. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13795. (abbreviate-file-name file))
  13796. (let ((r (downcase (read-char-exclusive))))
  13797. (cond
  13798. ((equal r ?r)
  13799. (org-remove-file file)
  13800. (throw 'nextfile t))
  13801. (t (user-error "Abort"))))))
  13802. (defun org-get-agenda-file-buffer (file)
  13803. "Get an agenda buffer visiting FILE.
  13804. If the buffer needs to be created, add it to the list of buffers
  13805. which might be released later."
  13806. (let ((buf (org-find-base-buffer-visiting file)))
  13807. (if buf
  13808. buf ; just return it
  13809. ;; Make a new buffer and remember it
  13810. (setq buf (find-file-noselect file))
  13811. (when buf (push buf org-agenda-new-buffers))
  13812. buf)))
  13813. (defun org-release-buffers (blist)
  13814. "Release all buffers in list, asking the user for confirmation when needed.
  13815. When a buffer is unmodified, it is just killed. When modified, it is saved
  13816. \(if the user agrees) and then killed."
  13817. (let (file)
  13818. (dolist (buf blist)
  13819. (setq file (buffer-file-name buf))
  13820. (when (and (buffer-modified-p buf)
  13821. file
  13822. (y-or-n-p (format "Save file %s? " file)))
  13823. (with-current-buffer buf (save-buffer)))
  13824. (kill-buffer buf))))
  13825. (defun org-agenda-prepare-buffers (files)
  13826. "Create buffers for all agenda files, protect archived trees and comments."
  13827. (interactive)
  13828. (let ((inhibit-read-only t)
  13829. (org-inhibit-startup org-agenda-inhibit-startup))
  13830. (setq org-tag-alist-for-agenda nil
  13831. org-tag-groups-alist-for-agenda nil)
  13832. (dolist (file files)
  13833. (catch 'nextfile
  13834. (with-current-buffer
  13835. (if (bufferp file)
  13836. file
  13837. (org-check-agenda-file file)
  13838. (org-get-agenda-file-buffer file))
  13839. (org-with-wide-buffer
  13840. (org-set-regexps-and-options 'tags-only)
  13841. (or (memq 'category org-agenda-ignore-properties)
  13842. (org-refresh-category-properties))
  13843. (or (memq 'stats org-agenda-ignore-properties)
  13844. (org-refresh-stats-properties))
  13845. (or (memq 'effort org-agenda-ignore-properties)
  13846. (unless org-element-use-cache
  13847. (org-refresh-effort-properties)))
  13848. (or (memq 'appt org-agenda-ignore-properties)
  13849. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13850. (setq org-todo-keywords-for-agenda
  13851. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13852. (setq org-done-keywords-for-agenda
  13853. (append org-done-keywords-for-agenda org-done-keywords))
  13854. (setq org-todo-keyword-alist-for-agenda
  13855. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13856. (setq org-tag-alist-for-agenda
  13857. (org--tag-add-to-alist
  13858. org-tag-alist-for-agenda
  13859. org-current-tag-alist))
  13860. ;; Merge current file's tag groups into global
  13861. ;; `org-tag-groups-alist-for-agenda'.
  13862. (when org-group-tags
  13863. (dolist (alist org-tag-groups-alist)
  13864. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13865. (if old
  13866. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13867. (push alist org-tag-groups-alist-for-agenda)))))))))
  13868. (setq org-todo-keywords-for-agenda
  13869. (org-uniquify org-todo-keywords-for-agenda))
  13870. (setq org-todo-keyword-alist-for-agenda
  13871. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13872. ;;;; CDLaTeX minor mode
  13873. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13874. "Keymap for the minor `org-cdlatex-mode'.")
  13875. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13876. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13877. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13878. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13879. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13880. (defvar org-cdlatex-texmathp-advice-is-done nil
  13881. "Flag remembering if we have applied the advice to texmathp already.")
  13882. (define-minor-mode org-cdlatex-mode
  13883. "Toggle the minor `org-cdlatex-mode'.
  13884. This mode supports entering LaTeX environment and math in LaTeX fragments
  13885. in Org mode.
  13886. \\{org-cdlatex-mode-map}"
  13887. :lighter " OCDL"
  13888. (when org-cdlatex-mode
  13889. (require 'cdlatex)
  13890. (run-hooks 'cdlatex-mode-hook)
  13891. (cdlatex-compute-tables))
  13892. (unless org-cdlatex-texmathp-advice-is-done
  13893. (setq org-cdlatex-texmathp-advice-is-done t)
  13894. (advice-add 'texmathp :around #'org--math-always-on)))
  13895. (defun org--math-always-on (orig-fun &rest args)
  13896. "Always return t in Org buffers.
  13897. This is because we want to insert math symbols without dollars even outside
  13898. the LaTeX math segments. If Org mode thinks that point is actually inside
  13899. an embedded LaTeX fragment, let `texmathp' do its job.
  13900. `\\[org-cdlatex-mode-map]'"
  13901. (interactive)
  13902. (cond
  13903. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  13904. ((eq this-command 'cdlatex-math-symbol)
  13905. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  13906. t)
  13907. (t
  13908. (let ((p (org-inside-LaTeX-fragment-p)))
  13909. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  13910. (if (member (car p)
  13911. (plist-get org-format-latex-options :matchers))
  13912. (progn
  13913. (setq texmathp-why '("Org mode embedded math" . 0))
  13914. t)
  13915. (apply orig-fun args)))))))
  13916. (defun turn-on-org-cdlatex ()
  13917. "Unconditionally turn on `org-cdlatex-mode'."
  13918. (org-cdlatex-mode 1))
  13919. (defun org-try-cdlatex-tab ()
  13920. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13921. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13922. - inside a LaTeX fragment, or
  13923. - after the first word in a line, where an abbreviation expansion could
  13924. insert a LaTeX environment."
  13925. (when org-cdlatex-mode
  13926. (cond
  13927. ;; Before any word on the line: No expansion possible.
  13928. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13929. ;; Just after first word on the line: Expand it. Make sure it
  13930. ;; cannot happen on headlines, though.
  13931. ((save-excursion
  13932. (skip-chars-backward "a-zA-Z0-9*")
  13933. (skip-chars-backward " \t")
  13934. (and (bolp) (not (org-at-heading-p))))
  13935. (cdlatex-tab) t)
  13936. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13937. (defun org-cdlatex-underscore-caret (&optional _arg)
  13938. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13939. Revert to the normal definition outside of these fragments."
  13940. (interactive "P")
  13941. (if (org-inside-LaTeX-fragment-p)
  13942. (call-interactively 'cdlatex-sub-superscript)
  13943. (let (org-cdlatex-mode)
  13944. (call-interactively (key-binding (vector last-input-event))))))
  13945. (defun org-cdlatex-math-modify (&optional _arg)
  13946. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13947. Revert to the normal definition outside of these fragments."
  13948. (interactive "P")
  13949. (if (org-inside-LaTeX-fragment-p)
  13950. (call-interactively 'cdlatex-math-modify)
  13951. (let (org-cdlatex-mode)
  13952. (call-interactively (key-binding (vector last-input-event))))))
  13953. (defun org-cdlatex-environment-indent (&optional environment item)
  13954. "Execute `cdlatex-environment' and indent the inserted environment.
  13955. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13956. The inserted environment is indented to current indentation
  13957. unless point is at the beginning of the line, in which the
  13958. environment remains unintended."
  13959. (interactive)
  13960. ;; cdlatex-environment always return nil. Therefore, capture output
  13961. ;; first and determine if an environment was selected.
  13962. (let* ((beg (point-marker))
  13963. (end (copy-marker (point) t))
  13964. (inserted (progn
  13965. (ignore-errors (cdlatex-environment environment item))
  13966. (< beg end)))
  13967. ;; Figure out how many lines to move forward after the
  13968. ;; environment has been inserted.
  13969. (lines (when inserted
  13970. (save-excursion
  13971. (- (cl-loop while (< beg (point))
  13972. with x = 0
  13973. do (forward-line -1)
  13974. (cl-incf x)
  13975. finally return x)
  13976. (if (progn (goto-char beg)
  13977. (and (progn (skip-chars-forward " \t") (eolp))
  13978. (progn (skip-chars-backward " \t") (bolp))))
  13979. 1 0)))))
  13980. (env (org-trim (delete-and-extract-region beg end))))
  13981. (when inserted
  13982. ;; Get indentation of next line unless at column 0.
  13983. (let ((ind (if (bolp) 0
  13984. (save-excursion
  13985. (org-return t)
  13986. (prog1 (current-indentation)
  13987. (when (progn (skip-chars-forward " \t") (eolp))
  13988. (delete-region beg (point)))))))
  13989. (bol (progn (skip-chars-backward " \t") (bolp))))
  13990. ;; Insert a newline before environment unless at column zero
  13991. ;; to "escape" the current line. Insert a newline if
  13992. ;; something is one the same line as \end{ENVIRONMENT}.
  13993. (insert
  13994. (concat (unless bol "\n") env
  13995. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  13996. (unless (zerop ind)
  13997. (save-excursion
  13998. (goto-char beg)
  13999. (while (< (point) end)
  14000. (unless (eolp) (indent-line-to ind))
  14001. (forward-line))))
  14002. (goto-char beg)
  14003. (forward-line lines)
  14004. (indent-line-to ind)))
  14005. (set-marker beg nil)
  14006. (set-marker end nil)))
  14007. ;;;; LaTeX fragments
  14008. (defun org-inside-LaTeX-fragment-p ()
  14009. "Test if point is inside a LaTeX fragment.
  14010. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14011. sequence appearing also before point.
  14012. Even though the matchers for math are configurable, this function assumes
  14013. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14014. delimiters are skipped when they have been removed by customization.
  14015. The return value is nil, or a cons cell with the delimiter and the
  14016. position of this delimiter.
  14017. This function does a reasonably good job, but can locally be fooled by
  14018. for example currency specifications. For example it will assume being in
  14019. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14020. fragments that are properly closed, but during editing, we have to live
  14021. with the uncertainty caused by missing closing delimiters. This function
  14022. looks only before point, not after."
  14023. (catch 'exit
  14024. (let ((pos (point))
  14025. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14026. (lim (progn
  14027. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14028. 'move)
  14029. (point)))
  14030. dd-on str (start 0) m re)
  14031. (goto-char pos)
  14032. (when dodollar
  14033. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14034. re (nth 1 (assoc "$" org-latex-regexps)))
  14035. (while (string-match re str start)
  14036. (cond
  14037. ((= (match-end 0) (length str))
  14038. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14039. ((= (match-end 0) (- (length str) 5))
  14040. (throw 'exit nil))
  14041. (t (setq start (match-end 0))))))
  14042. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14043. (goto-char pos)
  14044. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14045. (and (match-beginning 2) (throw 'exit nil))
  14046. ;; count $$
  14047. (while (re-search-backward "\\$\\$" lim t)
  14048. (setq dd-on (not dd-on)))
  14049. (goto-char pos)
  14050. (when dd-on (cons "$$" m))))))
  14051. (defun org-inside-latex-macro-p ()
  14052. "Is point inside a LaTeX macro or its arguments?"
  14053. (save-match-data
  14054. (org-in-regexp
  14055. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14056. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14057. "Build an overlay between BEG and END using IMAGE file.
  14058. Argument IMAGETYPE is the extension of the displayed image,
  14059. as a string. It defaults to \"png\"."
  14060. (let ((ov (make-overlay beg end))
  14061. (imagetype (or (intern imagetype) 'png)))
  14062. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14063. (overlay-put ov 'evaporate t)
  14064. (overlay-put ov
  14065. 'modification-hooks
  14066. (list (lambda (o _flag _beg _end &optional _l)
  14067. (delete-overlay o))))
  14068. (overlay-put ov
  14069. 'display
  14070. (list 'image :type imagetype :file image :ascent 'center))))
  14071. (defun org-clear-latex-preview (&optional beg end)
  14072. "Remove all overlays with LaTeX fragment images in current buffer.
  14073. When optional arguments BEG and END are non-nil, remove all
  14074. overlays between them instead. Return a non-nil value when some
  14075. overlays were removed, nil otherwise."
  14076. (let ((overlays
  14077. (cl-remove-if-not
  14078. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14079. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14080. (mapc #'delete-overlay overlays)
  14081. overlays))
  14082. (defun org--latex-preview-region (beg end)
  14083. "Preview LaTeX fragments between BEG and END.
  14084. BEG and END are buffer positions."
  14085. (let ((file (buffer-file-name (buffer-base-buffer))))
  14086. (save-excursion
  14087. (org-format-latex
  14088. (concat org-preview-latex-image-directory "org-ltximg")
  14089. beg end
  14090. ;; Emacs cannot overlay images from remote hosts. Create it in
  14091. ;; `temporary-file-directory' instead.
  14092. (if (or (not file) (file-remote-p file))
  14093. temporary-file-directory
  14094. default-directory)
  14095. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14096. (defun org-latex-preview (&optional arg)
  14097. "Toggle preview of the LaTeX fragment at point.
  14098. If the cursor is on a LaTeX fragment, create the image and
  14099. overlay it over the source code, if there is none. Remove it
  14100. otherwise. If there is no fragment at point, display images for
  14101. all fragments in the current section. With an active region,
  14102. display images for all fragments in the region.
  14103. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14104. for all fragments
  14105. in the current section.
  14106. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14107. argument ARG, display image for all
  14108. fragments in the buffer.
  14109. With a `\\[universal-argument] \\[universal-argument] \
  14110. \\[universal-argument]' prefix argument ARG, clear image for all
  14111. fragments in the buffer."
  14112. (interactive "P")
  14113. (cond
  14114. ((not (display-graphic-p)) nil)
  14115. ;; Clear whole buffer.
  14116. ((equal arg '(64))
  14117. (org-clear-latex-preview (point-min) (point-max))
  14118. (message "LaTeX previews removed from buffer"))
  14119. ;; Preview whole buffer.
  14120. ((equal arg '(16))
  14121. (message "Creating LaTeX previews in buffer...")
  14122. (org--latex-preview-region (point-min) (point-max))
  14123. (message "Creating LaTeX previews in buffer... done."))
  14124. ;; Clear current section.
  14125. ((equal arg '(4))
  14126. (org-clear-latex-preview
  14127. (if (use-region-p)
  14128. (region-beginning)
  14129. (if (org-before-first-heading-p) (point-min)
  14130. (save-excursion
  14131. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14132. (if (use-region-p)
  14133. (region-end)
  14134. (org-with-limited-levels (org-entry-end-position)))))
  14135. ((use-region-p)
  14136. (message "Creating LaTeX previews in region...")
  14137. (org--latex-preview-region (region-beginning) (region-end))
  14138. (message "Creating LaTeX previews in region... done."))
  14139. ;; Toggle preview on LaTeX code at point.
  14140. ((let ((datum (org-element-context)))
  14141. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14142. (let ((beg (org-element-property :begin datum))
  14143. (end (org-element-property :end datum)))
  14144. (if (org-clear-latex-preview beg end)
  14145. (message "LaTeX preview removed")
  14146. (message "Creating LaTeX preview...")
  14147. (org--latex-preview-region beg end)
  14148. (message "Creating LaTeX preview... done."))
  14149. t))))
  14150. ;; Preview current section.
  14151. (t
  14152. (let ((beg (if (org-before-first-heading-p) (point-min)
  14153. (save-excursion
  14154. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14155. (end (org-with-limited-levels (org-entry-end-position))))
  14156. (message "Creating LaTeX previews in section...")
  14157. (org--latex-preview-region beg end)
  14158. (message "Creating LaTeX previews in section... done.")))))
  14159. (defun org-format-latex
  14160. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14161. "Replace LaTeX fragments with links to an image.
  14162. The function takes care of creating the replacement image.
  14163. Only consider fragments between BEG and END when those are
  14164. provided.
  14165. When optional argument OVERLAYS is non-nil, display the image on
  14166. top of the fragment instead of replacing it.
  14167. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14168. Some of the options can be changed using the variable
  14169. `org-format-latex-options', which see."
  14170. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14171. (unless (eq processing-type 'verbatim)
  14172. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14173. (cnt 0)
  14174. checkdir-flag)
  14175. (goto-char (or beg (point-min)))
  14176. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14177. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14178. (overlay-recenter (or end (point-max))))
  14179. (while (re-search-forward math-regexp end t)
  14180. (unless (and overlays
  14181. (eq (get-char-property (point) 'org-overlay-type)
  14182. 'org-latex-overlay))
  14183. (let* ((context (org-element-context))
  14184. (type (org-element-type context)))
  14185. (when (memq type '(latex-environment latex-fragment))
  14186. (let ((block-type (eq type 'latex-environment))
  14187. (value (org-element-property :value context))
  14188. (beg (org-element-property :begin context))
  14189. (end (save-excursion
  14190. (goto-char (org-element-property :end context))
  14191. (skip-chars-backward " \r\t\n")
  14192. (point))))
  14193. (cond
  14194. ((eq processing-type 'mathjax)
  14195. ;; Prepare for MathJax processing.
  14196. (if (not (string-match "\\`\\$\\$?" value))
  14197. (goto-char end)
  14198. (delete-region beg end)
  14199. (if (string= (match-string 0 value) "$$")
  14200. (insert "\\[" (substring value 2 -2) "\\]")
  14201. (insert "\\(" (substring value 1 -1) "\\)"))))
  14202. ((eq processing-type 'html)
  14203. (goto-char beg)
  14204. (delete-region beg end)
  14205. (insert (org-format-latex-as-html value)))
  14206. ((assq processing-type org-preview-latex-process-alist)
  14207. ;; Process to an image.
  14208. (cl-incf cnt)
  14209. (goto-char beg)
  14210. (let* ((processing-info
  14211. (cdr (assq processing-type org-preview-latex-process-alist)))
  14212. (face (face-at-point))
  14213. ;; Get the colors from the face at point.
  14214. (fg
  14215. (let ((color (plist-get org-format-latex-options
  14216. :foreground)))
  14217. (if forbuffer
  14218. (cond
  14219. ((eq color 'auto)
  14220. (face-attribute face :foreground nil 'default))
  14221. ((eq color 'default)
  14222. (face-attribute 'default :foreground nil))
  14223. (t color))
  14224. color)))
  14225. (bg
  14226. (let ((color (plist-get org-format-latex-options
  14227. :background)))
  14228. (if forbuffer
  14229. (cond
  14230. ((eq color 'auto)
  14231. (face-attribute face :background nil 'default))
  14232. ((eq color 'default)
  14233. (face-attribute 'default :background nil))
  14234. (t color))
  14235. color)))
  14236. (hash (sha1 (prin1-to-string
  14237. (list org-format-latex-header
  14238. org-latex-default-packages-alist
  14239. org-latex-packages-alist
  14240. org-format-latex-options
  14241. forbuffer value fg bg))))
  14242. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14243. (absprefix (expand-file-name prefix dir))
  14244. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14245. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14246. (sep (and block-type "\n\n"))
  14247. (link (concat sep "[[file:" linkfile "]]" sep))
  14248. (options
  14249. (org-combine-plists
  14250. org-format-latex-options
  14251. `(:foreground ,fg :background ,bg))))
  14252. (when msg (message msg cnt))
  14253. (unless checkdir-flag ; Ensure the directory exists.
  14254. (setq checkdir-flag t)
  14255. (let ((todir (file-name-directory absprefix)))
  14256. (unless (file-directory-p todir)
  14257. (make-directory todir t))))
  14258. (unless (file-exists-p movefile)
  14259. (org-create-formula-image
  14260. value movefile options forbuffer processing-type))
  14261. (if overlays
  14262. (progn
  14263. (dolist (o (overlays-in beg end))
  14264. (when (eq (overlay-get o 'org-overlay-type)
  14265. 'org-latex-overlay)
  14266. (delete-overlay o)))
  14267. (org--make-preview-overlay beg end movefile imagetype)
  14268. (goto-char end))
  14269. (delete-region beg end)
  14270. (insert
  14271. (org-add-props link
  14272. (list 'org-latex-src
  14273. (replace-regexp-in-string "\"" "" value)
  14274. 'org-latex-src-embed-type
  14275. (if block-type 'paragraph 'character)))))))
  14276. ((eq processing-type 'mathml)
  14277. ;; Process to MathML.
  14278. (unless (org-format-latex-mathml-available-p)
  14279. (user-error "LaTeX to MathML converter not configured"))
  14280. (cl-incf cnt)
  14281. (when msg (message msg cnt))
  14282. (goto-char beg)
  14283. (delete-region beg end)
  14284. (insert (org-format-latex-as-mathml
  14285. value block-type prefix dir)))
  14286. (t
  14287. (error "Unknown conversion process %s for LaTeX fragments"
  14288. processing-type)))))))))))
  14289. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14290. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14291. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14292. successful, return the portion between \"<math...> </math>\"
  14293. elements otherwise return nil. When MATHML-FILE is specified,
  14294. write the results in to that file. When invoked as an
  14295. interactive command, prompt for LATEX-FRAG, with initial value
  14296. set to the current active region and echo the results for user
  14297. inspection."
  14298. (interactive (list (let ((frag (when (org-region-active-p)
  14299. (buffer-substring-no-properties
  14300. (region-beginning) (region-end)))))
  14301. (read-string "LaTeX Fragment: " frag nil frag))))
  14302. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14303. (let* ((tmp-in-file
  14304. (let ((file (file-relative-name
  14305. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14306. (write-region latex-frag nil file)
  14307. file))
  14308. (tmp-out-file (file-relative-name
  14309. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14310. (cmd (format-spec
  14311. org-latex-to-mathml-convert-command
  14312. `((?j . ,(and org-latex-to-mathml-jar-file
  14313. (shell-quote-argument
  14314. (expand-file-name
  14315. org-latex-to-mathml-jar-file))))
  14316. (?I . ,(shell-quote-argument tmp-in-file))
  14317. (?i . ,latex-frag)
  14318. (?o . ,(shell-quote-argument tmp-out-file)))))
  14319. mathml shell-command-output)
  14320. (when (called-interactively-p 'any)
  14321. (unless (org-format-latex-mathml-available-p)
  14322. (user-error "LaTeX to MathML converter not configured")))
  14323. (message "Running %s" cmd)
  14324. (setq shell-command-output (shell-command-to-string cmd))
  14325. (setq mathml
  14326. (when (file-readable-p tmp-out-file)
  14327. (with-current-buffer (find-file-noselect tmp-out-file t)
  14328. (goto-char (point-min))
  14329. (when (re-search-forward
  14330. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14331. (regexp-quote
  14332. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14333. nil t)
  14334. (prog1 (match-string 0) (kill-buffer))))))
  14335. (cond
  14336. (mathml
  14337. (setq mathml
  14338. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14339. (when mathml-file
  14340. (write-region mathml nil mathml-file))
  14341. (when (called-interactively-p 'any)
  14342. (message mathml)))
  14343. ((warn "LaTeX to MathML conversion failed")
  14344. (message shell-command-output)))
  14345. (delete-file tmp-in-file)
  14346. (when (file-exists-p tmp-out-file)
  14347. (delete-file tmp-out-file))
  14348. mathml))
  14349. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14350. prefix &optional dir)
  14351. "Use `org-create-math-formula' but check local cache first."
  14352. (let* ((absprefix (expand-file-name prefix dir))
  14353. (print-length nil) (print-level nil)
  14354. (formula-id (concat
  14355. "formula-"
  14356. (sha1
  14357. (prin1-to-string
  14358. (list latex-frag
  14359. org-latex-to-mathml-convert-command)))))
  14360. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14361. (formula-cache-dir (file-name-directory formula-cache)))
  14362. (unless (file-directory-p formula-cache-dir)
  14363. (make-directory formula-cache-dir t))
  14364. (unless (file-exists-p formula-cache)
  14365. (org-create-math-formula latex-frag formula-cache))
  14366. (if (file-exists-p formula-cache)
  14367. ;; Successful conversion. Return the link to MathML file.
  14368. (org-add-props
  14369. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14370. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14371. 'org-latex-src-embed-type (if latex-frag-type
  14372. 'paragraph 'character)))
  14373. ;; Failed conversion. Return the LaTeX fragment verbatim
  14374. latex-frag)))
  14375. (defun org-format-latex-as-html (latex-fragment)
  14376. "Convert LATEX-FRAGMENT to HTML.
  14377. This uses `org-latex-to-html-convert-command', which see."
  14378. (let ((cmd (format-spec org-latex-to-html-convert-command
  14379. `((?i . ,latex-fragment)))))
  14380. (message "Running %s" cmd)
  14381. (shell-command-to-string cmd)))
  14382. (defun org--get-display-dpi ()
  14383. "Get the DPI of the display.
  14384. The function assumes that the display has the same pixel width in
  14385. the horizontal and vertical directions."
  14386. (if (display-graphic-p)
  14387. (round (/ (display-pixel-height)
  14388. (/ (display-mm-height) 25.4)))
  14389. (error "Attempt to calculate the dpi of a non-graphic display")))
  14390. (defun org-create-formula-image
  14391. (string tofile options buffer &optional processing-type)
  14392. "Create an image from LaTeX source using external processes.
  14393. The LaTeX STRING is saved to a temporary LaTeX file, then
  14394. converted to an image file by process PROCESSING-TYPE defined in
  14395. `org-preview-latex-process-alist'. A nil value defaults to
  14396. `org-preview-latex-default-process'.
  14397. The generated image file is eventually moved to TOFILE.
  14398. The OPTIONS argument controls the size, foreground color and
  14399. background color of the generated image.
  14400. When BUFFER non-nil, this function is used for LaTeX previewing.
  14401. Otherwise, it is used to deal with LaTeX snippets showed in
  14402. a HTML file."
  14403. (let* ((processing-type (or processing-type
  14404. org-preview-latex-default-process))
  14405. (processing-info
  14406. (cdr (assq processing-type org-preview-latex-process-alist)))
  14407. (programs (plist-get processing-info :programs))
  14408. (error-message (or (plist-get processing-info :message) ""))
  14409. (image-input-type (plist-get processing-info :image-input-type))
  14410. (image-output-type (plist-get processing-info :image-output-type))
  14411. (post-clean (or (plist-get processing-info :post-clean)
  14412. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14413. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14414. (latex-header
  14415. (or (plist-get processing-info :latex-header)
  14416. (org-latex-make-preamble
  14417. (org-export-get-environment (org-export-get-backend 'latex))
  14418. org-format-latex-header
  14419. 'snippet)))
  14420. (latex-compiler (plist-get processing-info :latex-compiler))
  14421. (tmpdir temporary-file-directory)
  14422. (texfilebase (make-temp-name
  14423. (expand-file-name "orgtex" tmpdir)))
  14424. (texfile (concat texfilebase ".tex"))
  14425. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14426. '(1.0 . 1.0)))
  14427. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14428. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14429. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14430. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14431. "Black"))
  14432. (bg (or (plist-get options (if buffer :background :html-background))
  14433. "Transparent"))
  14434. (image-converter
  14435. (or (and (string= bg "Transparent")
  14436. (plist-get processing-info :transparent-image-converter))
  14437. (plist-get processing-info :image-converter)))
  14438. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14439. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14440. (dolist (program programs)
  14441. (org-check-external-command program error-message))
  14442. (if (eq fg 'default)
  14443. (setq fg (org-latex-color :foreground))
  14444. (setq fg (org-latex-color-format fg)))
  14445. (setq bg (cond
  14446. ((eq bg 'default) (org-latex-color :background))
  14447. ((string= bg "Transparent") nil)
  14448. (t (org-latex-color-format bg))))
  14449. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14450. (if (string-suffix-p string "\n")
  14451. (aset string (1- (length string)) ?%)
  14452. (setq string (concat string "%")))
  14453. (with-temp-file texfile
  14454. (insert latex-header)
  14455. (insert "\n\\begin{document}\n"
  14456. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14457. (if bg
  14458. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14459. "\n\\pagecolor{bg}%\n")
  14460. "")
  14461. "\n{\\color{fg}\n"
  14462. string
  14463. "\n}\n"
  14464. "\n\\end{document}\n"))
  14465. (let* ((err-msg (format "Please adjust `%s' part of \
  14466. `org-preview-latex-process-alist'."
  14467. processing-type))
  14468. (image-input-file
  14469. (org-compile-file
  14470. texfile latex-compiler image-input-type err-msg log-buf))
  14471. (image-output-file
  14472. (org-compile-file
  14473. image-input-file image-converter image-output-type err-msg log-buf
  14474. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14475. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14476. (copy-file image-output-file tofile 'replace)
  14477. (dolist (e post-clean)
  14478. (when (file-exists-p (concat texfilebase e))
  14479. (delete-file (concat texfilebase e))))
  14480. image-output-file)))
  14481. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14482. "Fill a LaTeX header template TPL.
  14483. In the template, the following place holders will be recognized:
  14484. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14485. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14486. [PACKAGES] \\usepackage statements for PKG
  14487. [NO-PACKAGES] do not include PKG
  14488. [EXTRA] the string EXTRA
  14489. [NO-EXTRA] do not include EXTRA
  14490. For backward compatibility, if both the positive and the negative place
  14491. holder is missing, the positive one (without the \"NO-\") will be
  14492. assumed to be present at the end of the template.
  14493. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14494. EXTRA is a string.
  14495. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14496. (let (rpl (end ""))
  14497. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14498. (setq rpl (if (or (match-end 1) (not def-pkg))
  14499. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14500. tpl (replace-match rpl t t tpl))
  14501. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14502. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14503. (setq rpl (if (or (match-end 1) (not pkg))
  14504. "" (org-latex-packages-to-string pkg snippets-p t))
  14505. tpl (replace-match rpl t t tpl))
  14506. (when pkg (setq end
  14507. (concat end "\n"
  14508. (org-latex-packages-to-string pkg snippets-p)))))
  14509. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14510. (setq rpl (if (or (match-end 1) (not extra))
  14511. "" (concat extra "\n"))
  14512. tpl (replace-match rpl t t tpl))
  14513. (when (and extra (string-match "\\S-" extra))
  14514. (setq end (concat end "\n" extra))))
  14515. (if (string-match "\\S-" end)
  14516. (concat tpl "\n" end)
  14517. tpl)))
  14518. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14519. "Turn an alist of packages into a string with the \\usepackage macros."
  14520. (setq pkg (mapconcat (lambda(p)
  14521. (cond
  14522. ((stringp p) p)
  14523. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14524. (format "%% Package %s omitted" (cadr p)))
  14525. ((equal "" (car p))
  14526. (format "\\usepackage{%s}" (cadr p)))
  14527. (t
  14528. (format "\\usepackage[%s]{%s}"
  14529. (car p) (cadr p)))))
  14530. pkg
  14531. "\n"))
  14532. (if newline (concat pkg "\n") pkg))
  14533. (defun org-dvipng-color (attr)
  14534. "Return a RGB color specification for dvipng."
  14535. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14536. (defun org-dvipng-color-format (color-name)
  14537. "Convert COLOR-NAME to a RGB color value for dvipng."
  14538. (apply #'format "rgb %s %s %s"
  14539. (mapcar 'org-normalize-color
  14540. (color-values color-name))))
  14541. (defun org-latex-color (attr)
  14542. "Return a RGB color for the LaTeX color package."
  14543. (org-latex-color-format (face-attribute 'default attr nil)))
  14544. (defun org-latex-color-format (color-name)
  14545. "Convert COLOR-NAME to a RGB color value."
  14546. (apply #'format "%s,%s,%s"
  14547. (mapcar 'org-normalize-color
  14548. (color-values color-name))))
  14549. (defun org-normalize-color (value)
  14550. "Return string to be used as color value for an RGB component."
  14551. (format "%g" (/ value 65535.0)))
  14552. ;; Image display
  14553. (defvar-local org-inline-image-overlays nil)
  14554. (defun org-toggle-inline-images (&optional include-linked)
  14555. "Toggle the display of inline images.
  14556. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14557. (interactive "P")
  14558. (if org-inline-image-overlays
  14559. (progn
  14560. (org-remove-inline-images)
  14561. (when (called-interactively-p 'interactive)
  14562. (message "Inline image display turned off")))
  14563. (org-display-inline-images include-linked)
  14564. (when (called-interactively-p 'interactive)
  14565. (message (if org-inline-image-overlays
  14566. (format "%d images displayed inline"
  14567. (length org-inline-image-overlays))
  14568. "No images to display inline")))))
  14569. (defun org-redisplay-inline-images ()
  14570. "Assure display of inline images and refresh them."
  14571. (interactive)
  14572. (org-toggle-inline-images)
  14573. (unless org-inline-image-overlays
  14574. (org-toggle-inline-images)))
  14575. ;; For without-x builds.
  14576. (declare-function image-refresh "image" (spec &optional frame))
  14577. (defcustom org-display-remote-inline-images 'skip
  14578. "How to display remote inline images.
  14579. Possible values of this option are:
  14580. skip Don't display remote images.
  14581. download Always download and display remote images.
  14582. cache Display remote images, and open them in separate buffers
  14583. for caching. Silently update the image buffer when a file
  14584. change is detected."
  14585. :group 'org-appearance
  14586. :package-version '(Org . "9.4")
  14587. :type '(choice
  14588. (const :tag "Ignore remote images" skip)
  14589. (const :tag "Always display remote images" download)
  14590. (const :tag "Display and silently update remote images" cache))
  14591. :safe #'symbolp)
  14592. (defun org--create-inline-image (file width)
  14593. "Create image located at FILE, or return nil.
  14594. WIDTH is the width of the image. The image may not be created
  14595. according to the value of `org-display-remote-inline-images'."
  14596. (let* ((remote? (file-remote-p file))
  14597. (file-or-data
  14598. (pcase org-display-remote-inline-images
  14599. ((guard (not remote?)) file)
  14600. (`download (with-temp-buffer
  14601. (set-buffer-multibyte nil)
  14602. (insert-file-contents-literally file)
  14603. (buffer-string)))
  14604. (`cache (let ((revert-without-query '(".")))
  14605. (with-current-buffer (find-file-noselect file)
  14606. (buffer-string))))
  14607. (`skip nil)
  14608. (other
  14609. (message "Invalid value of `org-display-remote-inline-images': %S"
  14610. other)
  14611. nil))))
  14612. (when file-or-data
  14613. (create-image file-or-data
  14614. (and (image-type-available-p 'imagemagick)
  14615. width
  14616. 'imagemagick)
  14617. remote?
  14618. :width width :scale 1))))
  14619. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14620. "Display inline images.
  14621. An inline image is a link which follows either of these
  14622. conventions:
  14623. 1. Its path is a file with an extension matching return value
  14624. from `image-file-name-regexp' and it has no contents.
  14625. 2. Its description consists in a single link of the previous
  14626. type. In this case, that link must be a well-formed plain
  14627. or angle link, i.e., it must have an explicit \"file\" type.
  14628. Equip each image with the key-map `image-map'.
  14629. When optional argument INCLUDE-LINKED is non-nil, also links with
  14630. a text description part will be inlined. This can be nice for
  14631. a quick look at those images, but it does not reflect what
  14632. exported files will look like.
  14633. When optional argument REFRESH is non-nil, refresh existing
  14634. images between BEG and END. This will create new image displays
  14635. only if necessary.
  14636. BEG and END define the considered part. They default to the
  14637. buffer boundaries with possible narrowing."
  14638. (interactive "P")
  14639. (when (display-graphic-p)
  14640. (unless refresh
  14641. (org-remove-inline-images)
  14642. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14643. (let ((end (or end (point-max))))
  14644. (org-with-point-at (or beg (point-min))
  14645. (let* ((case-fold-search t)
  14646. (file-extension-re (image-file-name-regexp))
  14647. (link-abbrevs (mapcar #'car
  14648. (append org-link-abbrev-alist-local
  14649. org-link-abbrev-alist)))
  14650. ;; Check absolute, relative file names and explicit
  14651. ;; "file:" links. Also check link abbreviations since
  14652. ;; some might expand to "file" links.
  14653. (file-types-re
  14654. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14655. (if (not link-abbrevs) ""
  14656. (concat "\\|" (regexp-opt link-abbrevs))))))
  14657. (while (re-search-forward file-types-re end t)
  14658. (let* ((link (org-element-lineage
  14659. (save-match-data (org-element-context))
  14660. '(link) t))
  14661. (linktype (org-element-property :type link))
  14662. (inner-start (match-beginning 1))
  14663. (path
  14664. (cond
  14665. ;; No link at point; no inline image.
  14666. ((not link) nil)
  14667. ;; File link without a description. Also handle
  14668. ;; INCLUDE-LINKED here since it should have
  14669. ;; precedence over the next case. I.e., if link
  14670. ;; contains filenames in both the path and the
  14671. ;; description, prioritize the path only when
  14672. ;; INCLUDE-LINKED is non-nil.
  14673. ((or (not (org-element-property :contents-begin link))
  14674. include-linked)
  14675. (and (or (equal "file" linktype)
  14676. (equal "attachment" linktype))
  14677. (org-element-property :path link)))
  14678. ;; Link with a description. Check if description
  14679. ;; is a filename. Even if Org doesn't have syntax
  14680. ;; for those -- clickable image -- constructs, fake
  14681. ;; them, as in `org-export-insert-image-links'.
  14682. ((not inner-start) nil)
  14683. (t
  14684. (org-with-point-at inner-start
  14685. (and (looking-at
  14686. (if (char-equal ?< (char-after inner-start))
  14687. org-link-angle-re
  14688. org-link-plain-re))
  14689. ;; File name must fill the whole
  14690. ;; description.
  14691. (= (org-element-property :contents-end link)
  14692. (match-end 0))
  14693. (match-string 2)))))))
  14694. (when (and path (string-match-p file-extension-re path))
  14695. (let ((file (if (equal "attachment" linktype)
  14696. (progn
  14697. (require 'org-attach)
  14698. (ignore-errors (org-attach-expand path)))
  14699. (expand-file-name path))))
  14700. (when (and file (file-exists-p file))
  14701. (let ((width (org-display-inline-image--width link))
  14702. (old (get-char-property-and-overlay
  14703. (org-element-property :begin link)
  14704. 'org-image-overlay)))
  14705. (if (and (car-safe old) refresh)
  14706. (image-refresh (overlay-get (cdr old) 'display))
  14707. (let ((image (org--create-inline-image file width)))
  14708. (when image
  14709. (let ((ov (make-overlay
  14710. (org-element-property :begin link)
  14711. (progn
  14712. (goto-char
  14713. (org-element-property :end link))
  14714. (skip-chars-backward " \t")
  14715. (point)))))
  14716. (overlay-put ov 'display image)
  14717. (overlay-put ov 'face 'default)
  14718. (overlay-put ov 'org-image-overlay t)
  14719. (overlay-put
  14720. ov 'modification-hooks
  14721. (list 'org-display-inline-remove-overlay))
  14722. (when (boundp 'image-map)
  14723. (overlay-put ov 'keymap image-map))
  14724. (push ov org-inline-image-overlays))))))))))))))))
  14725. (defvar visual-fill-column-width) ; Silence compiler warning
  14726. (defun org-display-inline-image--width (link)
  14727. "Determine the display width of the image LINK, in pixels.
  14728. - When `org-image-actual-width' is t, the image's pixel width is used.
  14729. - When `org-image-actual-width' is a number, that value will is used.
  14730. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14731. set (if it exists) is used to set the image width. A width of X% is
  14732. divided by 100.
  14733. If no :width attribute is given and `org-image-actual-width' is a list with
  14734. a number as the car, then that number is used as the default value.
  14735. If the value is a float between 0 and 2, it interpreted as that proportion
  14736. of the text width in the buffer."
  14737. ;; Apply `org-image-actual-width' specifications.
  14738. (cond
  14739. ((eq org-image-actual-width t) nil)
  14740. ((listp org-image-actual-width)
  14741. (let* ((case-fold-search t)
  14742. (par (org-element-lineage link '(paragraph)))
  14743. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14744. (par-end (org-element-property :post-affiliated par))
  14745. ;; Try to find an attribute providing a :width.
  14746. (attr-width
  14747. (when (and par (org-with-point-at
  14748. (org-element-property :begin par)
  14749. (re-search-forward attr-re par-end t)))
  14750. (match-string 1)))
  14751. (width
  14752. (cond
  14753. ;; Treat :width t as if `org-image-actual-width' were t.
  14754. ((string= attr-width "t") nil)
  14755. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14756. ((or (null attr-width)
  14757. (string-match-p "\\`[^0-9]" attr-width))
  14758. (car org-image-actual-width))
  14759. ;; Convert numeric widths to numbers, converting percentages.
  14760. ((string-match-p "\\`[0-9.]+%" attr-width)
  14761. (/ (string-to-number attr-width) 100.0))
  14762. (t (string-to-number attr-width)))))
  14763. (if (and (floatp width) (<= 0.0 width 2.0))
  14764. ;; A float in [0,2] should be interpereted as this portion of
  14765. ;; the text width in the window. This works well with cases like
  14766. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14767. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14768. ;; bound as cases such as 1.2\linewidth are feasible.
  14769. (round (* width
  14770. (window-pixel-width)
  14771. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14772. (or visual-fill-column-width auto-fill-function))
  14773. (when auto-fill-function fill-column)
  14774. (- (window-text-width) (line-number-display-width)))
  14775. (float (window-total-width)))))
  14776. width)))
  14777. ((numberp org-image-actual-width)
  14778. org-image-actual-width)
  14779. (t nil)))
  14780. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14781. "Remove inline-display overlay if a corresponding region is modified."
  14782. (let ((inhibit-modification-hooks t))
  14783. (when (and ov after)
  14784. (delete ov org-inline-image-overlays)
  14785. (delete-overlay ov))))
  14786. (defun org-remove-inline-images ()
  14787. "Remove inline display of images."
  14788. (interactive)
  14789. (mapc #'delete-overlay org-inline-image-overlays)
  14790. (setq org-inline-image-overlays nil))
  14791. (defvar org-self-insert-command-undo-counter 0)
  14792. (defvar org-speed-command nil)
  14793. (defun org-fix-tags-on-the-fly ()
  14794. "Align tags in headline at point.
  14795. Unlike `org-align-tags', this function does nothing if point is
  14796. either not currently on a tagged headline or on a tag."
  14797. (when (and (org-match-line org-tag-line-re)
  14798. (< (point) (match-beginning 1)))
  14799. (org-align-tags)))
  14800. (defun org-self-insert-command (N)
  14801. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14802. If the cursor is in a table looking at whitespace, the whitespace is
  14803. overwritten, and the table is not marked as requiring realignment."
  14804. (interactive "p")
  14805. (org-fold-check-before-invisible-edit 'insert)
  14806. (cond
  14807. ((and org-use-speed-commands
  14808. (let ((kv (this-command-keys-vector)))
  14809. (setq org-speed-command
  14810. (run-hook-with-args-until-success
  14811. 'org-speed-command-hook
  14812. (make-string 1 (aref kv (1- (length kv))))))))
  14813. (cond
  14814. ((commandp org-speed-command)
  14815. (setq this-command org-speed-command)
  14816. (call-interactively org-speed-command))
  14817. ((functionp org-speed-command)
  14818. (funcall org-speed-command))
  14819. ((consp org-speed-command)
  14820. (eval org-speed-command t))
  14821. (t (let (org-use-speed-commands)
  14822. (call-interactively 'org-self-insert-command)))))
  14823. ((and
  14824. (= N 1)
  14825. (not (org-region-active-p))
  14826. (org-at-table-p)
  14827. (progn
  14828. ;; Check if we blank the field, and if that triggers align.
  14829. (and (featurep 'org-table)
  14830. org-table-auto-blank-field
  14831. (memq last-command
  14832. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14833. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14834. ;; Got extra space, this field does not determine
  14835. ;; column width.
  14836. (let (org-table-may-need-update) (org-table-blank-field))
  14837. ;; No extra space, this field may determine column
  14838. ;; width.
  14839. (org-table-blank-field)))
  14840. t)
  14841. (looking-at "[^|\n]* |"))
  14842. ;; There is room for insertion without re-aligning the table.
  14843. (self-insert-command N)
  14844. (org-table-with-shrunk-field
  14845. (save-excursion
  14846. (skip-chars-forward "^|")
  14847. ;; Do not delete last space, which is
  14848. ;; `org-table-separator-space', but the regular space before
  14849. ;; it.
  14850. (delete-region (- (point) 2) (1- (point))))))
  14851. (t
  14852. (setq org-table-may-need-update t)
  14853. (self-insert-command N)
  14854. (org-fix-tags-on-the-fly)
  14855. (when org-self-insert-cluster-for-undo
  14856. (if (not (eq last-command 'org-self-insert-command))
  14857. (setq org-self-insert-command-undo-counter 1)
  14858. (if (>= org-self-insert-command-undo-counter 20)
  14859. (setq org-self-insert-command-undo-counter 1)
  14860. (and (> org-self-insert-command-undo-counter 0)
  14861. buffer-undo-list (listp buffer-undo-list)
  14862. (not (cadr buffer-undo-list)) ; remove nil entry
  14863. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14864. (setq org-self-insert-command-undo-counter
  14865. (1+ org-self-insert-command-undo-counter))))))))
  14866. (defun org-delete-backward-char (N)
  14867. "Like `delete-backward-char', insert whitespace at field end in tables.
  14868. When deleting backwards, in tables this function will insert whitespace in
  14869. front of the next \"|\" separator, to keep the table aligned. The table will
  14870. still be marked for re-alignment if the field did fill the entire column,
  14871. because, in this case the deletion might narrow the column."
  14872. (interactive "p")
  14873. (save-match-data
  14874. (org-fold-check-before-invisible-edit 'delete-backward)
  14875. (if (and (= N 1)
  14876. (not overwrite-mode)
  14877. (not (org-region-active-p))
  14878. (not (eq (char-before) ?|))
  14879. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14880. (looking-at-p ".*?|")
  14881. (org-at-table-p))
  14882. (progn (forward-char -1) (org-delete-char 1))
  14883. (backward-delete-char N)
  14884. (org-fix-tags-on-the-fly))))
  14885. (defun org-delete-char (N)
  14886. "Like `delete-char', but insert whitespace at field end in tables.
  14887. When deleting characters, in tables this function will insert whitespace in
  14888. front of the next \"|\" separator, to keep the table aligned. The table will
  14889. still be marked for re-alignment if the field did fill the entire column,
  14890. because, in this case the deletion might narrow the column."
  14891. (interactive "p")
  14892. (save-match-data
  14893. (org-fold-check-before-invisible-edit 'delete)
  14894. (cond
  14895. ((or (/= N 1)
  14896. (eq (char-after) ?|)
  14897. (save-excursion (skip-chars-backward " \t") (bolp))
  14898. (not (org-at-table-p)))
  14899. (delete-char N)
  14900. (org-fix-tags-on-the-fly))
  14901. ((looking-at ".\\(.*?\\)|")
  14902. (let* ((update? org-table-may-need-update)
  14903. (noalign (looking-at-p ".*? |")))
  14904. (delete-char 1)
  14905. (org-table-with-shrunk-field
  14906. (save-excursion
  14907. ;; Last space is `org-table-separator-space', so insert
  14908. ;; a regular one before it instead.
  14909. (goto-char (- (match-end 0) 2))
  14910. (insert " ")))
  14911. ;; If there were two spaces at the end, this field does not
  14912. ;; determine the width of the column.
  14913. (when noalign (setq org-table-may-need-update update?))))
  14914. (t
  14915. (delete-char N)))))
  14916. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14917. (put 'org-self-insert-command 'delete-selection
  14918. (lambda ()
  14919. (not (run-hook-with-args-until-success
  14920. 'self-insert-uses-region-functions))))
  14921. (put 'orgtbl-self-insert-command 'delete-selection
  14922. (lambda ()
  14923. (not (run-hook-with-args-until-success
  14924. 'self-insert-uses-region-functions))))
  14925. (put 'org-delete-char 'delete-selection 'supersede)
  14926. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14927. (put 'org-yank 'delete-selection 'yank)
  14928. (put 'org-return 'delete-selection t)
  14929. ;; Make `flyspell-mode' delay after some commands
  14930. (put 'org-self-insert-command 'flyspell-delayed t)
  14931. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14932. (put 'org-delete-char 'flyspell-delayed t)
  14933. (put 'org-delete-backward-char 'flyspell-delayed t)
  14934. ;; Make pabbrev-mode expand after Org mode commands
  14935. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14936. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14937. (defun org-transpose-words ()
  14938. "Transpose words for Org.
  14939. This uses the `org-mode-transpose-word-syntax-table' syntax
  14940. table, which interprets characters in `org-emphasis-alist' as
  14941. word constituents."
  14942. (interactive)
  14943. (with-syntax-table org-mode-transpose-word-syntax-table
  14944. (call-interactively 'transpose-words)))
  14945. (defvar org-ctrl-c-ctrl-c-hook nil
  14946. "Hook for functions attaching themselves to `C-c C-c'.
  14947. This can be used to add additional functionality to the `C-c C-c'
  14948. key which executes context-dependent commands. This hook is run
  14949. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14950. run after the last test.
  14951. Each function will be called with no arguments. The function
  14952. must check if the context is appropriate for it to act. If yes,
  14953. it should do its thing and then return a non-nil value. If the
  14954. context is wrong, just do nothing and return nil.")
  14955. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14956. "Hook for functions attaching themselves to `C-c C-c'.
  14957. This can be used to add additional functionality to the `C-c C-c'
  14958. key which executes context-dependent commands. This hook is run
  14959. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14960. before the first test.
  14961. Each function will be called with no arguments. The function
  14962. must check if the context is appropriate for it to act. If yes,
  14963. it should do its thing and then return a non-nil value. If the
  14964. context is wrong, just do nothing and return nil.")
  14965. (defvar org-tab-after-check-for-table-hook nil
  14966. "Hook for functions to attach themselves to TAB.
  14967. See `org-ctrl-c-ctrl-c-hook' for more information.
  14968. This hook runs after it has been established that the cursor is not in a
  14969. table, but before checking if the cursor is in a headline or if global cycling
  14970. should be done.
  14971. If any function in this hook returns t, not other actions like visibility
  14972. cycling will be done.")
  14973. (defvar org-tab-after-check-for-cycling-hook nil
  14974. "Hook for functions to attach themselves to TAB.
  14975. See `org-ctrl-c-ctrl-c-hook' for more information.
  14976. This hook runs after it has been established that not table field motion and
  14977. not visibility should be done because of current context. This is probably
  14978. the place where a package like yasnippets can hook in.")
  14979. (defvar org-tab-before-tab-emulation-hook nil
  14980. "Hook for functions to attach themselves to TAB.
  14981. See `org-ctrl-c-ctrl-c-hook' for more information.
  14982. This hook runs after every other options for TAB have been exhausted, but
  14983. before indentation and \t insertion takes place.")
  14984. (defvar org-metaleft-hook nil
  14985. "Hook for functions attaching themselves to `M-left'.
  14986. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14987. (defvar org-metaright-hook nil
  14988. "Hook for functions attaching themselves to `M-right'.
  14989. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14990. (defvar org-metaup-hook nil
  14991. "Hook for functions attaching themselves to `M-up'.
  14992. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14993. (defvar org-metadown-hook nil
  14994. "Hook for functions attaching themselves to `M-down'.
  14995. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14996. (defvar org-shiftmetaleft-hook nil
  14997. "Hook for functions attaching themselves to `M-S-left'.
  14998. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14999. (defvar org-shiftmetaright-hook nil
  15000. "Hook for functions attaching themselves to `M-S-right'.
  15001. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15002. (defvar org-shiftmetaup-hook nil
  15003. "Hook for functions attaching themselves to `M-S-up'.
  15004. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15005. (defvar org-shiftmetadown-hook nil
  15006. "Hook for functions attaching themselves to `M-S-down'.
  15007. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15008. (defvar org-metareturn-hook nil
  15009. "Hook for functions attaching themselves to `M-RET'.
  15010. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15011. (defvar org-shiftup-hook nil
  15012. "Hook for functions attaching themselves to `S-up'.
  15013. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15014. (defvar org-shiftup-final-hook nil
  15015. "Hook for functions attaching themselves to `S-up'.
  15016. This one runs after all other options except shift-select have been excluded.
  15017. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15018. (defvar org-shiftdown-hook nil
  15019. "Hook for functions attaching themselves to `S-down'.
  15020. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15021. (defvar org-shiftdown-final-hook nil
  15022. "Hook for functions attaching themselves to `S-down'.
  15023. This one runs after all other options except shift-select have been excluded.
  15024. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15025. (defvar org-shiftleft-hook nil
  15026. "Hook for functions attaching themselves to `S-left'.
  15027. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15028. (defvar org-shiftleft-final-hook nil
  15029. "Hook for functions attaching themselves to `S-left'.
  15030. This one runs after all other options except shift-select have been excluded.
  15031. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15032. (defvar org-shiftright-hook nil
  15033. "Hook for functions attaching themselves to `S-right'.
  15034. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15035. (defvar org-shiftright-final-hook nil
  15036. "Hook for functions attaching themselves to `S-right'.
  15037. This one runs after all other options except shift-select have been excluded.
  15038. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15039. (defun org-modifier-cursor-error ()
  15040. "Throw an error, a modified cursor command was applied in wrong context."
  15041. (user-error "This command is active in special context like tables, headlines or items"))
  15042. (defun org-shiftselect-error ()
  15043. "Throw an error because Shift-Cursor command was applied in wrong context."
  15044. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15045. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15046. (user-error "This command works only in special context like headlines or timestamps")))
  15047. (defun org-call-for-shift-select (cmd)
  15048. (let ((this-command-keys-shift-translated t))
  15049. (call-interactively cmd)))
  15050. (defun org-shifttab (&optional arg)
  15051. "Global visibility cycling or move to previous table field.
  15052. Call `org-table-previous-field' within a table.
  15053. When ARG is nil, cycle globally through visibility states.
  15054. When ARG is a numeric prefix, show contents of this level."
  15055. (interactive "P")
  15056. (cond
  15057. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15058. ((integerp arg)
  15059. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15060. (message "Content view to level: %d" arg)
  15061. (org-cycle-content (prefix-numeric-value arg2))
  15062. (org-cycle-show-empty-lines t)
  15063. (setq org-cycle-global-status 'overview)
  15064. (run-hook-with-args 'org-cycle-hook 'overview)))
  15065. (t (call-interactively 'org-cycle-global))))
  15066. (defun org-shiftmetaleft ()
  15067. "Promote subtree or delete table column.
  15068. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15069. `org-table-delete-column', depending on context. See the
  15070. individual commands for more information."
  15071. (interactive)
  15072. (cond
  15073. ((and (eq system-type 'darwin)
  15074. (or (eq org-support-shift-select 'always)
  15075. (and org-support-shift-select (org-region-active-p))))
  15076. (org-call-for-shift-select 'backward-char))
  15077. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15078. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15079. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15080. ((if (not (org-region-active-p)) (org-at-item-p)
  15081. (save-excursion (goto-char (region-beginning))
  15082. (org-at-item-p)))
  15083. (call-interactively 'org-outdent-item-tree))
  15084. (t (org-modifier-cursor-error))))
  15085. (defun org-shiftmetaright ()
  15086. "Demote subtree or insert table column.
  15087. Calls `org-demote-subtree', `org-indent-item-tree', or
  15088. `org-table-insert-column', depending on context. See the
  15089. individual commands for more information."
  15090. (interactive)
  15091. (cond
  15092. ((and (eq system-type 'darwin)
  15093. (or (eq org-support-shift-select 'always)
  15094. (and org-support-shift-select (org-region-active-p))))
  15095. (org-call-for-shift-select 'forward-char))
  15096. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15097. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15098. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15099. ((if (not (org-region-active-p)) (org-at-item-p)
  15100. (save-excursion (goto-char (region-beginning))
  15101. (org-at-item-p)))
  15102. (call-interactively 'org-indent-item-tree))
  15103. (t (org-modifier-cursor-error))))
  15104. (defun org-shiftmetaup (&optional _arg)
  15105. "Drag the line at point up.
  15106. In a table, kill the current row.
  15107. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15108. but also adjust the previous clocked item in the clock history.
  15109. Everywhere else, drag the line at point up."
  15110. (interactive "P")
  15111. (cond
  15112. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15113. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15114. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15115. (call-interactively 'org-timestamp-up)))
  15116. (t (call-interactively 'org-drag-line-backward))))
  15117. (defun org-shiftmetadown (&optional _arg)
  15118. "Drag the line at point down.
  15119. In a table, insert an empty row at the current line.
  15120. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15121. but also adjust the previous clocked item in the clock history.
  15122. Everywhere else, drag the line at point down."
  15123. (interactive "P")
  15124. (cond
  15125. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15126. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15127. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15128. (call-interactively 'org-timestamp-down)))
  15129. (t (call-interactively 'org-drag-line-forward))))
  15130. (defsubst org-hidden-tree-error ()
  15131. (user-error
  15132. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15133. (defun org-metaleft (&optional _arg)
  15134. "Promote heading, list item at point or move table column left.
  15135. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15136. depending on context. With no specific context, calls the Emacs
  15137. default `backward-word'. See the individual commands for more
  15138. information.
  15139. This function runs the hook `org-metaleft-hook' as a first step,
  15140. and returns at first non-nil value."
  15141. (interactive "P")
  15142. (cond
  15143. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15144. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15145. ((org-with-limited-levels
  15146. (or (org-at-heading-p)
  15147. (and (org-region-active-p)
  15148. (save-excursion
  15149. (goto-char (region-beginning))
  15150. (org-at-heading-p)))))
  15151. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15152. (call-interactively 'org-do-promote))
  15153. ;; At an inline task.
  15154. ((org-at-heading-p)
  15155. (call-interactively 'org-inlinetask-promote))
  15156. ((or (org-at-item-p)
  15157. (and (org-region-active-p)
  15158. (save-excursion
  15159. (goto-char (region-beginning))
  15160. (org-at-item-p))))
  15161. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15162. (call-interactively 'org-outdent-item))
  15163. (t (call-interactively 'backward-word))))
  15164. (defun org-metaright (&optional _arg)
  15165. "Demote heading, list item at point or move table column right.
  15166. In front of a drawer or a block keyword, indent it correctly.
  15167. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15168. `org-indent-drawer' or `org-indent-block' depending on context.
  15169. With no specific context, calls the Emacs default `forward-word'.
  15170. See the individual commands for more information.
  15171. This function runs the hook `org-metaright-hook' as a first step,
  15172. and returns at first non-nil value."
  15173. (interactive "P")
  15174. (cond
  15175. ((run-hook-with-args-until-success 'org-metaright-hook))
  15176. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15177. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15178. ((org-at-block-p) (call-interactively 'org-indent-block))
  15179. ((org-with-limited-levels
  15180. (or (org-at-heading-p)
  15181. (and (org-region-active-p)
  15182. (save-excursion
  15183. (goto-char (region-beginning))
  15184. (org-at-heading-p)))))
  15185. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15186. (call-interactively 'org-do-demote))
  15187. ;; At an inline task.
  15188. ((org-at-heading-p)
  15189. (call-interactively 'org-inlinetask-demote))
  15190. ((or (org-at-item-p)
  15191. (and (org-region-active-p)
  15192. (save-excursion
  15193. (goto-char (region-beginning))
  15194. (org-at-item-p))))
  15195. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15196. (call-interactively 'org-indent-item))
  15197. (t (call-interactively 'forward-word))))
  15198. (defun org-check-for-hidden (what)
  15199. "Check if there are hidden headlines/items in the current visual line.
  15200. WHAT can be either `headlines' or `items'. If the current line is
  15201. an outline or item heading and it has a folded subtree below it,
  15202. this function returns t, nil otherwise."
  15203. (let ((re (cond
  15204. ((eq what 'headlines) org-outline-regexp-bol)
  15205. ((eq what 'items) (org-item-beginning-re))
  15206. (t (error "This should not happen"))))
  15207. beg end)
  15208. (save-excursion
  15209. (catch 'exit
  15210. (unless (org-region-active-p)
  15211. (setq beg (point-at-bol))
  15212. (beginning-of-line 2)
  15213. (while (and (not (eobp)) ;; this is like `next-line'
  15214. (org-invisible-p (1- (point))))
  15215. (beginning-of-line 2))
  15216. (setq end (point))
  15217. (goto-char beg)
  15218. (goto-char (point-at-eol))
  15219. (setq end (max end (point)))
  15220. (while (re-search-forward re end t)
  15221. (when (org-invisible-p (match-beginning 0))
  15222. (throw 'exit t))))
  15223. nil))))
  15224. (defun org-metaup (&optional _arg)
  15225. "Move subtree up or move table row up.
  15226. Calls `org-move-subtree-up' or `org-table-move-row' or
  15227. `org-move-item-up', depending on context. See the individual commands
  15228. for more information."
  15229. (interactive "P")
  15230. (cond
  15231. ((run-hook-with-args-until-success 'org-metaup-hook))
  15232. ((org-region-active-p)
  15233. (let* ((a (save-excursion
  15234. (goto-char (region-beginning))
  15235. (line-beginning-position)))
  15236. (b (save-excursion
  15237. (goto-char (region-end))
  15238. (if (bolp) (1- (point)) (line-end-position))))
  15239. (c (save-excursion
  15240. (goto-char a)
  15241. (move-beginning-of-line 0)
  15242. (point)))
  15243. (d (save-excursion
  15244. (goto-char a)
  15245. (move-end-of-line 0)
  15246. (point))))
  15247. (transpose-regions a b c d)
  15248. (goto-char c)))
  15249. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15250. ((and (featurep 'org-inlinetask)
  15251. (org-inlinetask-in-task-p))
  15252. (org-drag-element-backward))
  15253. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15254. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15255. (t (org-drag-element-backward))))
  15256. (defun org-metadown (&optional _arg)
  15257. "Move subtree down or move table row down.
  15258. Calls `org-move-subtree-down' or `org-table-move-row' or
  15259. `org-move-item-down', depending on context. See the individual
  15260. commands for more information."
  15261. (interactive "P")
  15262. (cond
  15263. ((run-hook-with-args-until-success 'org-metadown-hook))
  15264. ((org-region-active-p)
  15265. (let* ((a (save-excursion
  15266. (goto-char (region-beginning))
  15267. (line-beginning-position)))
  15268. (b (save-excursion
  15269. (goto-char (region-end))
  15270. (if (bolp) (1- (point)) (line-end-position))))
  15271. (c (save-excursion
  15272. (goto-char b)
  15273. (move-beginning-of-line (if (bolp) 1 2))
  15274. (point)))
  15275. (d (save-excursion
  15276. (goto-char b)
  15277. (move-end-of-line (if (bolp) 1 2))
  15278. (point))))
  15279. (transpose-regions a b c d)
  15280. (goto-char d)))
  15281. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15282. ((and (featurep 'org-inlinetask)
  15283. (org-inlinetask-in-task-p))
  15284. (org-drag-element-forward))
  15285. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15286. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15287. (t (org-drag-element-forward))))
  15288. (defun org-shiftup (&optional arg)
  15289. "Act on current element according to context.
  15290. Call `org-timestamp-up' or `org-priority-up', or
  15291. `org-previous-item', or `org-table-move-cell-up'. See the
  15292. individual commands for more information."
  15293. (interactive "P")
  15294. (cond
  15295. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15296. ((and org-support-shift-select (org-region-active-p))
  15297. (org-call-for-shift-select 'previous-line))
  15298. ((org-at-timestamp-p 'lax)
  15299. (call-interactively (if org-edit-timestamp-down-means-later
  15300. 'org-timestamp-down 'org-timestamp-up)))
  15301. ((and (not (eq org-support-shift-select 'always))
  15302. org-priority-enable-commands
  15303. (org-at-heading-p))
  15304. (call-interactively 'org-priority-up))
  15305. ((and (not org-support-shift-select) (org-at-item-p))
  15306. (call-interactively 'org-previous-item))
  15307. ((org-clocktable-try-shift 'up arg))
  15308. ((and (not (eq org-support-shift-select 'always))
  15309. (org-at-table-p))
  15310. (org-table-move-cell-up))
  15311. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15312. (org-support-shift-select
  15313. (org-call-for-shift-select 'previous-line))
  15314. (t (org-shiftselect-error))))
  15315. (defun org-shiftdown (&optional arg)
  15316. "Act on current element according to context.
  15317. Call `org-timestamp-down' or `org-priority-down', or
  15318. `org-next-item', or `org-table-move-cell-down'. See the
  15319. individual commands for more information."
  15320. (interactive "P")
  15321. (cond
  15322. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15323. ((and org-support-shift-select (org-region-active-p))
  15324. (org-call-for-shift-select 'next-line))
  15325. ((org-at-timestamp-p 'lax)
  15326. (call-interactively (if org-edit-timestamp-down-means-later
  15327. 'org-timestamp-up 'org-timestamp-down)))
  15328. ((and (not (eq org-support-shift-select 'always))
  15329. org-priority-enable-commands
  15330. (org-at-heading-p))
  15331. (call-interactively 'org-priority-down))
  15332. ((and (not org-support-shift-select) (org-at-item-p))
  15333. (call-interactively 'org-next-item))
  15334. ((org-clocktable-try-shift 'down arg))
  15335. ((and (not (eq org-support-shift-select 'always))
  15336. (org-at-table-p))
  15337. (org-table-move-cell-down))
  15338. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15339. (org-support-shift-select
  15340. (org-call-for-shift-select 'next-line))
  15341. (t (org-shiftselect-error))))
  15342. (defun org-shiftright (&optional arg)
  15343. "Act on the current element according to context.
  15344. This does one of the following:
  15345. - switch a timestamp at point one day into the future
  15346. - on a headline, switch to the next TODO keyword
  15347. - on an item, switch entire list to the next bullet type
  15348. - on a property line, switch to the next allowed value
  15349. - on a clocktable definition line, move time block into the future
  15350. - in a table, move a single cell right"
  15351. (interactive "P")
  15352. (cond
  15353. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15354. ((and org-support-shift-select (org-region-active-p))
  15355. (org-call-for-shift-select 'forward-char))
  15356. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15357. ((and (not (eq org-support-shift-select 'always))
  15358. (org-at-heading-p))
  15359. (let ((org-inhibit-logging
  15360. (not org-treat-S-cursor-todo-selection-as-state-change))
  15361. (org-inhibit-blocking
  15362. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15363. (org-call-with-arg 'org-todo 'right)))
  15364. ((or (and org-support-shift-select
  15365. (not (eq org-support-shift-select 'always))
  15366. (org-at-item-bullet-p))
  15367. (and (not org-support-shift-select) (org-at-item-p)))
  15368. (org-call-with-arg 'org-cycle-list-bullet nil))
  15369. ((and (not (eq org-support-shift-select 'always))
  15370. (org-at-property-p))
  15371. (call-interactively 'org-property-next-allowed-value))
  15372. ((org-clocktable-try-shift 'right arg))
  15373. ((and (not (eq org-support-shift-select 'always))
  15374. (org-at-table-p))
  15375. (org-table-move-cell-right))
  15376. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15377. (org-support-shift-select
  15378. (org-call-for-shift-select 'forward-char))
  15379. (t (org-shiftselect-error))))
  15380. (defun org-shiftleft (&optional arg)
  15381. "Act on current element according to context.
  15382. This does one of the following:
  15383. - switch a timestamp at point one day into the past
  15384. - on a headline, switch to the previous TODO keyword.
  15385. - on an item, switch entire list to the previous bullet type
  15386. - on a property line, switch to the previous allowed value
  15387. - on a clocktable definition line, move time block into the past
  15388. - in a table, move a single cell left"
  15389. (interactive "P")
  15390. (cond
  15391. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15392. ((and org-support-shift-select (org-region-active-p))
  15393. (org-call-for-shift-select 'backward-char))
  15394. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15395. ((and (not (eq org-support-shift-select 'always))
  15396. (org-at-heading-p))
  15397. (let ((org-inhibit-logging
  15398. (not org-treat-S-cursor-todo-selection-as-state-change))
  15399. (org-inhibit-blocking
  15400. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15401. (org-call-with-arg 'org-todo 'left)))
  15402. ((or (and org-support-shift-select
  15403. (not (eq org-support-shift-select 'always))
  15404. (org-at-item-bullet-p))
  15405. (and (not org-support-shift-select) (org-at-item-p)))
  15406. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15407. ((and (not (eq org-support-shift-select 'always))
  15408. (org-at-property-p))
  15409. (call-interactively 'org-property-previous-allowed-value))
  15410. ((org-clocktable-try-shift 'left arg))
  15411. ((and (not (eq org-support-shift-select 'always))
  15412. (org-at-table-p))
  15413. (org-table-move-cell-left))
  15414. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15415. (org-support-shift-select
  15416. (org-call-for-shift-select 'backward-char))
  15417. (t (org-shiftselect-error))))
  15418. (defun org-shiftcontrolright ()
  15419. "Switch to next TODO set."
  15420. (interactive)
  15421. (cond
  15422. ((and org-support-shift-select (org-region-active-p))
  15423. (org-call-for-shift-select 'forward-word))
  15424. ((and (not (eq org-support-shift-select 'always))
  15425. (org-at-heading-p))
  15426. (org-call-with-arg 'org-todo 'nextset))
  15427. (org-support-shift-select
  15428. (org-call-for-shift-select 'forward-word))
  15429. (t (org-shiftselect-error))))
  15430. (defun org-shiftcontrolleft ()
  15431. "Switch to previous TODO set."
  15432. (interactive)
  15433. (cond
  15434. ((and org-support-shift-select (org-region-active-p))
  15435. (org-call-for-shift-select 'backward-word))
  15436. ((and (not (eq org-support-shift-select 'always))
  15437. (org-at-heading-p))
  15438. (org-call-with-arg 'org-todo 'previousset))
  15439. (org-support-shift-select
  15440. (org-call-for-shift-select 'backward-word))
  15441. (t (org-shiftselect-error))))
  15442. (defun org-shiftcontrolup (&optional n)
  15443. "Change timestamps synchronously up in CLOCK log lines.
  15444. Optional argument N tells to change by that many units."
  15445. (interactive "P")
  15446. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15447. (let (org-support-shift-select)
  15448. (org-clock-timestamps-up n))
  15449. (user-error "Not at a clock log")))
  15450. (defun org-shiftcontroldown (&optional n)
  15451. "Change timestamps synchronously down in CLOCK log lines.
  15452. Optional argument N tells to change by that many units."
  15453. (interactive "P")
  15454. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15455. (let (org-support-shift-select)
  15456. (org-clock-timestamps-down n))
  15457. (user-error "Not at a clock log")))
  15458. (defun org-increase-number-at-point (&optional inc)
  15459. "Increment the number at point.
  15460. With an optional prefix numeric argument INC, increment using
  15461. this numeric value."
  15462. (interactive "p")
  15463. (if (not (number-at-point))
  15464. (user-error "Not on a number")
  15465. (unless inc (setq inc 1))
  15466. (let ((pos (point))
  15467. (beg (skip-chars-backward "-+^/*0-9eE."))
  15468. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15469. (setq nap (buffer-substring-no-properties
  15470. (+ pos beg) (+ pos beg end)))
  15471. (delete-region (+ pos beg) (+ pos beg end))
  15472. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15473. (when (org-at-table-p)
  15474. (org-table-align)
  15475. (org-table-end-of-field 1))))
  15476. (defun org-decrease-number-at-point (&optional inc)
  15477. "Decrement the number at point.
  15478. With an optional prefix numeric argument INC, decrement using
  15479. this numeric value."
  15480. (interactive "p")
  15481. (org-increase-number-at-point (- (or inc 1))))
  15482. (defun org-ctrl-c-ret ()
  15483. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15484. (interactive)
  15485. (cond
  15486. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15487. (t (call-interactively 'org-insert-heading))))
  15488. (defun org-copy-visible (beg end)
  15489. "Copy the visible parts of the region."
  15490. (interactive "r")
  15491. (let ((result ""))
  15492. (while (/= beg end)
  15493. (if (eq org-fold-core-style 'text-properties)
  15494. (progn
  15495. (while (org-invisible-p beg)
  15496. (setq beg (org-fold-next-visibility-change beg end)))
  15497. (let ((next (org-fold-next-visibility-change beg end)))
  15498. (setq result (concat result (buffer-substring beg next)))
  15499. (setq beg next)))
  15500. (when (invisible-p beg)
  15501. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15502. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15503. (setq result (concat result (buffer-substring beg next)))
  15504. (setq beg next))))
  15505. (setq deactivate-mark t)
  15506. (kill-new result)
  15507. (message "Visible strings have been copied to the kill ring.")))
  15508. (defun org-copy-special ()
  15509. "Copy region in table or copy current subtree.
  15510. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15511. context. See the individual commands for more information."
  15512. (interactive)
  15513. (call-interactively
  15514. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15515. (defun org-cut-special ()
  15516. "Cut region in table or cut current subtree.
  15517. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15518. context. See the individual commands for more information."
  15519. (interactive)
  15520. (call-interactively
  15521. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15522. (defun org-paste-special (arg)
  15523. "Paste rectangular region into table, or past subtree relative to level.
  15524. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15525. See the individual commands for more information."
  15526. (interactive "P")
  15527. (if (org-at-table-p)
  15528. (org-table-paste-rectangle)
  15529. (org-paste-subtree arg)))
  15530. (defun org-edit-special (&optional arg)
  15531. "Call a special editor for the element at point.
  15532. When at a table, call the formula editor with `org-table-edit-formulas'.
  15533. When in a source code block, call `org-edit-src-code'.
  15534. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15535. When in an export block, call `org-edit-export-block'.
  15536. When in a LaTeX environment, call `org-edit-latex-environment'.
  15537. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15538. When at a footnote reference, call `org-edit-footnote-reference'.
  15539. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15540. When at an active timestamp, call `org-time-stamp'.
  15541. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15542. On a link, call `ffap' to visit the link at point.
  15543. Otherwise, return a user error."
  15544. (interactive "P")
  15545. (let ((element (org-element-at-point)))
  15546. (barf-if-buffer-read-only)
  15547. (pcase (org-element-type element)
  15548. (`src-block
  15549. (if (not arg) (org-edit-src-code)
  15550. (let* ((info (org-babel-get-src-block-info))
  15551. (lang (nth 0 info))
  15552. (params (nth 2 info))
  15553. (session (cdr (assq :session params))))
  15554. (if (not session) (org-edit-src-code)
  15555. ;; At a source block with a session and function called
  15556. ;; with an ARG: switch to the buffer related to the
  15557. ;; inferior process.
  15558. (switch-to-buffer
  15559. (funcall (intern (concat "org-babel-prep-session:" lang))
  15560. session params))))))
  15561. (`keyword
  15562. (unless (member (org-element-property :key element)
  15563. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15564. (user-error "No special environment to edit here"))
  15565. (let ((value (org-element-property :value element)))
  15566. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15567. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15568. (or (match-string 1 value)
  15569. (match-string 0 value)))))
  15570. (when (org-url-p file)
  15571. (user-error "Files located with a URL cannot be edited"))
  15572. (org-link-open-from-string
  15573. (format "[[%s]]" (expand-file-name file))))))
  15574. (`table
  15575. (if (eq (org-element-property :type element) 'table.el)
  15576. (org-edit-table.el)
  15577. (call-interactively 'org-table-edit-formulas)))
  15578. ;; Only Org tables contain `table-row' type elements.
  15579. (`table-row (call-interactively 'org-table-edit-formulas))
  15580. (`example-block (org-edit-src-code))
  15581. (`export-block (org-edit-export-block))
  15582. (`fixed-width (org-edit-fixed-width-region))
  15583. (`latex-environment (org-edit-latex-environment))
  15584. (`planning
  15585. (let ((proplist (cadr element)))
  15586. (mapc #'call-interactively
  15587. (remq nil
  15588. (list
  15589. (when (plist-get proplist :deadline) #'org-deadline)
  15590. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15591. (_
  15592. ;; No notable element at point. Though, we may be at a link or
  15593. ;; a footnote reference, which are objects. Thus, scan deeper.
  15594. (let ((context (org-element-context element)))
  15595. (pcase (org-element-type context)
  15596. (`footnote-reference (org-edit-footnote-reference))
  15597. (`inline-src-block (org-edit-inline-src-code))
  15598. (`latex-fragment (org-edit-latex-fragment))
  15599. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15600. (call-interactively #'org-time-stamp-inactive)
  15601. (call-interactively #'org-time-stamp)))
  15602. (`link (call-interactively #'ffap))
  15603. (_ (user-error "No special environment to edit here"))))))))
  15604. (defun org-ctrl-c-ctrl-c (&optional arg)
  15605. "Set tags in headline, or update according to changed information at point.
  15606. This command does many different things, depending on context:
  15607. - If column view is active, in agenda or org buffers, quit it.
  15608. - If there are highlights, remove them.
  15609. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15610. this is what we do.
  15611. - If the cursor is on a statistics cookie, update it.
  15612. - If the cursor is in a headline, in an agenda or an org buffer,
  15613. prompt for tags and insert them into the current line, aligned
  15614. to `org-tags-column'. When called with prefix arg, realign all
  15615. tags in the current buffer.
  15616. - If the cursor is in one of the special #+KEYWORD lines, this
  15617. triggers scanning the buffer for these lines and updating the
  15618. information.
  15619. - If the cursor is inside a table, realign the table. This command
  15620. works even if the automatic table editor has been turned off.
  15621. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15622. the entire table.
  15623. - If the cursor is at a footnote reference or definition, jump to
  15624. the corresponding definition or references, respectively.
  15625. - If the cursor is a the beginning of a dynamic block, update it.
  15626. - If the current buffer is a capture buffer, close note and file it.
  15627. - If the cursor is on a <<<target>>>, update radio targets and
  15628. corresponding links in this buffer.
  15629. - If the cursor is on a numbered item in a plain list, renumber the
  15630. ordered list.
  15631. - If the cursor is on a checkbox, toggle it.
  15632. - If the cursor is on a code block, evaluate it. The variable
  15633. `org-confirm-babel-evaluate' can be used to control prompting
  15634. before code block evaluation, by default every code block
  15635. evaluation requires confirmation. Code block evaluation can be
  15636. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15637. (interactive "P")
  15638. (cond
  15639. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15640. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15641. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15642. (org-remove-occur-highlights)
  15643. (message "Temporary highlights/overlays removed from current buffer"))
  15644. ((and (local-variable-p 'org-finish-function)
  15645. (fboundp org-finish-function))
  15646. (funcall org-finish-function))
  15647. ((org-babel-hash-at-point))
  15648. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15649. (t
  15650. (let* ((context
  15651. (org-element-lineage
  15652. (org-element-context)
  15653. ;; Limit to supported contexts.
  15654. '(babel-call clock dynamic-block footnote-definition
  15655. footnote-reference inline-babel-call inline-src-block
  15656. inlinetask item keyword node-property paragraph
  15657. plain-list planning property-drawer radio-target
  15658. src-block statistics-cookie table table-cell table-row
  15659. timestamp)
  15660. t))
  15661. (radio-list-p (org-at-radio-list-p))
  15662. (type (org-element-type context)))
  15663. ;; For convenience: at the first line of a paragraph on the same
  15664. ;; line as an item, apply function on that item instead.
  15665. (when (eq type 'paragraph)
  15666. (let ((parent (org-element-property :parent context)))
  15667. (when (and (eq (org-element-type parent) 'item)
  15668. (= (line-beginning-position)
  15669. (org-element-property :begin parent)))
  15670. (setq context parent)
  15671. (setq type 'item))))
  15672. ;; Act according to type of element or object at point.
  15673. ;;
  15674. ;; Do nothing on a blank line, except if it is contained in
  15675. ;; a source block. Hence, we first check if point is in such
  15676. ;; a block and then if it is at a blank line.
  15677. (pcase type
  15678. ((or `inline-src-block `src-block)
  15679. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15680. (org-babel-eval-wipe-error-buffer)
  15681. (org-babel-execute-src-block
  15682. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15683. ((guard (org-match-line "[ \t]*$"))
  15684. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15685. (user-error
  15686. (substitute-command-keys
  15687. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15688. ((or `babel-call `inline-babel-call)
  15689. (let ((info (org-babel-lob-get-info context)))
  15690. (when info (org-babel-execute-src-block nil info))))
  15691. (`clock (org-clock-update-time-maybe))
  15692. (`dynamic-block
  15693. (save-excursion
  15694. (goto-char (org-element-property :post-affiliated context))
  15695. (org-update-dblock)))
  15696. (`footnote-definition
  15697. (goto-char (org-element-property :post-affiliated context))
  15698. (call-interactively 'org-footnote-action))
  15699. (`footnote-reference (call-interactively #'org-footnote-action))
  15700. ((or `headline `inlinetask)
  15701. (save-excursion (goto-char (org-element-property :begin context))
  15702. (call-interactively #'org-set-tags-command)))
  15703. (`item
  15704. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15705. ;; unconditionally, whereas `C-u' will toggle its presence.
  15706. ;; Without a universal argument, if the item has a checkbox,
  15707. ;; toggle it. Otherwise repair the list.
  15708. (if (or radio-list-p
  15709. (and (boundp org-list-checkbox-radio-mode)
  15710. org-list-checkbox-radio-mode))
  15711. (org-toggle-radio-button arg)
  15712. (let* ((box (org-element-property :checkbox context))
  15713. (struct (org-element-property :structure context))
  15714. (old-struct (copy-tree struct))
  15715. (parents (org-list-parents-alist struct))
  15716. (prevs (org-list-prevs-alist struct))
  15717. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15718. (org-list-set-checkbox
  15719. (org-element-property :begin context) struct
  15720. (cond ((equal arg '(16)) "[-]")
  15721. ((and (not box) (equal arg '(4))) "[ ]")
  15722. ((or (not box) (equal arg '(4))) nil)
  15723. ((eq box 'on) "[ ]")
  15724. (t "[X]")))
  15725. ;; Mimic `org-list-write-struct' but with grabbing a return
  15726. ;; value from `org-list-struct-fix-box'.
  15727. (org-list-struct-fix-ind struct parents 2)
  15728. (org-list-struct-fix-item-end struct)
  15729. (org-list-struct-fix-bul struct prevs)
  15730. (org-list-struct-fix-ind struct parents)
  15731. (let ((block-item
  15732. (org-list-struct-fix-box struct parents prevs orderedp)))
  15733. (if (and box (equal struct old-struct))
  15734. (if (equal arg '(16))
  15735. (message "Checkboxes already reset")
  15736. (user-error "Cannot toggle this checkbox: %s"
  15737. (if (eq box 'on)
  15738. "all subitems checked"
  15739. "unchecked subitems")))
  15740. (org-list-struct-apply-struct struct old-struct)
  15741. (org-update-checkbox-count-maybe))
  15742. (when block-item
  15743. (message "Checkboxes were removed due to empty box at line %d"
  15744. (org-current-line block-item)))))))
  15745. (`plain-list
  15746. ;; At a plain list, with a double C-u argument, set
  15747. ;; checkboxes of each item to "[-]", whereas a single one
  15748. ;; will toggle their presence according to the state of the
  15749. ;; first item in the list. Without an argument, repair the
  15750. ;; list.
  15751. (if (or radio-list-p
  15752. (and (boundp org-list-checkbox-radio-mode)
  15753. org-list-checkbox-radio-mode))
  15754. (org-toggle-radio-button arg)
  15755. (let* ((begin (org-element-property :contents-begin context))
  15756. (struct (org-element-property :structure context))
  15757. (old-struct (copy-tree struct))
  15758. (first-box (save-excursion
  15759. (goto-char begin)
  15760. (looking-at org-list-full-item-re)
  15761. (match-string-no-properties 3)))
  15762. (new-box (cond ((equal arg '(16)) "[-]")
  15763. ((equal arg '(4)) (unless first-box "[ ]"))
  15764. ((equal first-box "[X]") "[ ]")
  15765. (t "[X]"))))
  15766. (cond
  15767. (arg
  15768. (dolist (pos
  15769. (org-list-get-all-items
  15770. begin struct (org-list-prevs-alist struct)))
  15771. (org-list-set-checkbox pos struct new-box)))
  15772. ((and first-box (eq (point) begin))
  15773. ;; For convenience, when point is at bol on the first
  15774. ;; item of the list and no argument is provided, simply
  15775. ;; toggle checkbox of that item, if any.
  15776. (org-list-set-checkbox begin struct new-box)))
  15777. (when (equal
  15778. (org-list-write-struct
  15779. struct (org-list-parents-alist struct) old-struct)
  15780. old-struct)
  15781. (message "Cannot update this checkbox"))
  15782. (org-update-checkbox-count-maybe))))
  15783. (`keyword
  15784. (let ((org-inhibit-startup-visibility-stuff t)
  15785. (org-startup-align-all-tables nil))
  15786. (when (boundp 'org-table-coordinate-overlays)
  15787. (mapc #'delete-overlay org-table-coordinate-overlays)
  15788. (setq org-table-coordinate-overlays nil))
  15789. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15790. (message "Local setup has been refreshed"))
  15791. ((or `property-drawer `node-property)
  15792. (call-interactively #'org-property-action))
  15793. (`radio-target
  15794. (call-interactively #'org-update-radio-target-regexp))
  15795. (`statistics-cookie
  15796. (call-interactively #'org-update-statistics-cookies))
  15797. ((or `table `table-cell `table-row)
  15798. ;; At a table, generate a plot if on the #+plot line,
  15799. ;; recalculate every field and align it otherwise. Also
  15800. ;; send the table if necessary.
  15801. (cond
  15802. ((and (org-match-line "[ \t]*#\\+plot:")
  15803. (< (point) (org-element-property :post-affiliated context)))
  15804. (org-plot/gnuplot))
  15805. ;; If the table has a `table.el' type, just give up.
  15806. ((eq (org-element-property :type context) 'table.el)
  15807. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15808. Use `\\[org-edit-special]' to edit table.el tables")))
  15809. ;; At a table row or cell, maybe recalculate line but always
  15810. ;; align table.
  15811. ((or (eq type 'table)
  15812. ;; Check if point is at a TBLFM line.
  15813. (and (eq type 'table-row)
  15814. (= (point) (org-element-property :end context))))
  15815. (save-excursion
  15816. (if (org-at-TBLFM-p)
  15817. (progn (require 'org-table)
  15818. (org-table-calc-current-TBLFM))
  15819. (goto-char (org-element-property :contents-begin context))
  15820. (org-call-with-arg 'org-table-recalculate (or arg t))
  15821. (orgtbl-send-table 'maybe))))
  15822. (t
  15823. (org-table-maybe-eval-formula)
  15824. (cond (arg (call-interactively #'org-table-recalculate))
  15825. ((org-table-maybe-recalculate-line))
  15826. (t (org-table-align))))))
  15827. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15828. (org-timestamp-change 0 'day))
  15829. ((and `nil (guard (org-at-heading-p)))
  15830. ;; When point is on an unsupported object type, we can miss
  15831. ;; the fact that it also is at a heading. Handle it here.
  15832. (call-interactively #'org-set-tags-command))
  15833. ((guard
  15834. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15835. (_
  15836. (user-error
  15837. (substitute-command-keys
  15838. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15839. (defun org-mode-restart ()
  15840. "Restart `org-mode'."
  15841. (interactive)
  15842. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15843. (funcall major-mode)
  15844. (hack-local-variables)
  15845. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15846. (org-indent-mode -1))
  15847. (org-reset-file-cache))
  15848. (message "%s restarted" major-mode))
  15849. (defun org-kill-note-or-show-branches ()
  15850. "Abort storing current note, or show just branches."
  15851. (interactive)
  15852. (cond (org-finish-function
  15853. (let ((org-note-abort t)) (funcall org-finish-function)))
  15854. ((org-before-first-heading-p)
  15855. (org-fold-show-branches-buffer)
  15856. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15857. (t
  15858. (let ((beg (progn (org-back-to-heading) (point)))
  15859. (end (save-excursion (org-end-of-subtree t t) (point))))
  15860. (org-fold-hide-subtree)
  15861. (org-fold-show-branches)
  15862. (org-fold-hide-archived-subtrees beg end)))))
  15863. (defun org-delete-indentation (&optional arg)
  15864. "Join current line to previous and fix whitespace at join.
  15865. If previous line is a headline add to headline title. Otherwise
  15866. the function calls `delete-indentation'.
  15867. I.e. with a non-nil optional argument, join the line with the
  15868. following one. If there is a region then join the lines in that
  15869. region."
  15870. (interactive "*P")
  15871. (if (save-excursion
  15872. (beginning-of-line (if arg 1 0))
  15873. (let ((case-fold-search nil))
  15874. (looking-at org-complex-heading-regexp)))
  15875. ;; At headline.
  15876. (let ((tags-column (when (match-beginning 5)
  15877. (save-excursion (goto-char (match-beginning 5))
  15878. (current-column))))
  15879. (string (concat " " (progn (when arg (forward-line 1))
  15880. (org-trim (delete-and-extract-region
  15881. (line-beginning-position)
  15882. (line-end-position)))))))
  15883. (unless (bobp) (delete-region (point) (1- (point))))
  15884. (goto-char (or (match-end 4)
  15885. (match-beginning 5)
  15886. (match-end 0)))
  15887. (skip-chars-backward " \t")
  15888. (save-excursion (insert string))
  15889. ;; Adjust alignment of tags.
  15890. (cond
  15891. ((not tags-column)) ;no tags
  15892. (org-auto-align-tags (org-align-tags))
  15893. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15894. (let ((current-prefix-arg arg))
  15895. (call-interactively #'delete-indentation))))
  15896. (defun org-open-line (n)
  15897. "Insert a new row in tables, call `open-line' elsewhere.
  15898. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15899. As a special case, when a document starts with a table, allow to
  15900. call `open-line' on the very first character."
  15901. (interactive "*p")
  15902. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15903. (org-table-insert-row)
  15904. (open-line n)))
  15905. (defun org--newline (indent arg interactive)
  15906. "Call `newline-and-indent' or just `newline'.
  15907. If INDENT is non-nil, call `newline-and-indent' with ARG to
  15908. indent unconditionally; otherwise, call `newline' with ARG and
  15909. INTERACTIVE, which can trigger indentation if
  15910. `electric-indent-mode' is enabled."
  15911. (if indent
  15912. (org-newline-and-indent arg)
  15913. (newline arg interactive)))
  15914. (defun org-return (&optional indent arg interactive)
  15915. "Goto next table row or insert a newline.
  15916. Calls `org-table-next-row' or `newline', depending on context.
  15917. When optional INDENT argument is non-nil, call
  15918. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  15919. and INTERACTIVE.
  15920. When `org-return-follows-link' is non-nil and point is on
  15921. a timestamp or a link, call `org-open-at-point'. However, it
  15922. will not happen if point is in a table or on a \"dead\"
  15923. object (e.g., within a comment). In these case, you need to use
  15924. `org-open-at-point' directly."
  15925. (interactive "i\nP\np")
  15926. (let* ((context (if org-return-follows-link (org-element-context)
  15927. (org-element-at-point)))
  15928. (element-type (org-element-type context)))
  15929. (cond
  15930. ;; In a table, call `org-table-next-row'. However, before first
  15931. ;; column or after last one, split the table.
  15932. ((or (and (eq 'table element-type)
  15933. (not (eq 'table.el (org-element-property :type context)))
  15934. (>= (point) (org-element-property :contents-begin context))
  15935. (< (point) (org-element-property :contents-end context)))
  15936. (org-element-lineage context '(table-row table-cell) t))
  15937. (if (or (looking-at-p "[ \t]*$")
  15938. (save-excursion (skip-chars-backward " \t") (bolp)))
  15939. (insert "\n")
  15940. (org-table-justify-field-maybe)
  15941. (call-interactively #'org-table-next-row)))
  15942. ;; On a link or a timestamp, call `org-open-at-point' if
  15943. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15944. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15945. ((and org-return-follows-link
  15946. (or (and (eq 'link element-type)
  15947. ;; Ensure point is not on the white spaces after
  15948. ;; the link.
  15949. (let ((origin (point)))
  15950. (org-with-point-at (org-element-property :end context)
  15951. (skip-chars-backward " \t")
  15952. (> (point) origin))))
  15953. (org-in-regexp org-ts-regexp-both nil t)
  15954. (org-in-regexp org-tsr-regexp-both nil t)
  15955. (org-in-regexp org-link-any-re nil t)))
  15956. (call-interactively #'org-open-at-point))
  15957. ;; Insert newline in heading, but preserve tags.
  15958. ((and (not (bolp))
  15959. (let ((case-fold-search nil))
  15960. (org-match-line org-complex-heading-regexp)))
  15961. ;; At headline. Split line. However, if point is on keyword,
  15962. ;; priority cookie or tags, do not break any of them: add
  15963. ;; a newline after the headline instead.
  15964. (let ((tags-column (and (match-beginning 5)
  15965. (save-excursion (goto-char (match-beginning 5))
  15966. (current-column))))
  15967. (string
  15968. (when (and (match-end 4) (org-point-in-group (point) 4))
  15969. (delete-and-extract-region (point) (match-end 4)))))
  15970. ;; Adjust tag alignment.
  15971. (cond
  15972. ((not (and tags-column string)))
  15973. (org-auto-align-tags (org-align-tags))
  15974. (t (org--align-tags-here tags-column))) ;preserve tags column
  15975. (end-of-line)
  15976. (org-fold-show-entry 'hide-drawers)
  15977. (org--newline indent arg interactive)
  15978. (when string (save-excursion (insert (org-trim string))))))
  15979. ;; In a list, make sure indenting keeps trailing text within.
  15980. ((and (not (eolp))
  15981. (org-element-lineage context '(item)))
  15982. (let ((trailing-data
  15983. (delete-and-extract-region (point) (line-end-position))))
  15984. (org--newline indent arg interactive)
  15985. (save-excursion (insert trailing-data))))
  15986. (t
  15987. ;; Do not auto-fill when point is in an Org property drawer.
  15988. (let ((auto-fill-function (and (not (org-at-property-p))
  15989. auto-fill-function)))
  15990. (org--newline indent arg interactive))))))
  15991. (defun org-return-and-maybe-indent ()
  15992. "Goto next table row, or insert a newline, maybe indented.
  15993. Call `org-table-next-row' or `org-return', depending on context.
  15994. See the individual commands for more information.
  15995. When inserting a newline, if `org-adapt-indentation' is t:
  15996. indent the line if `electric-indent-mode' is disabled, don't
  15997. indent it if it is enabled."
  15998. (interactive)
  15999. (org-return (not electric-indent-mode)))
  16000. (defun org-ctrl-c-tab (&optional arg)
  16001. "Toggle columns width in a table, or show children.
  16002. Call `org-table-toggle-column-width' if point is in a table.
  16003. Otherwise provide a compact view of the children. ARG is the
  16004. level to hide."
  16005. (interactive "p")
  16006. (cond
  16007. ((org-at-table-p)
  16008. (call-interactively #'org-table-toggle-column-width))
  16009. ((org-before-first-heading-p)
  16010. (save-excursion
  16011. (org-fold-flag-above-first-heading)
  16012. (org-fold-hide-sublevels (or arg 1))))
  16013. (t
  16014. (org-fold-hide-subtree)
  16015. (org-fold-show-children arg))))
  16016. (defun org-ctrl-c-star ()
  16017. "Compute table, or change heading status of lines.
  16018. Calls `org-table-recalculate' or `org-toggle-heading',
  16019. depending on context."
  16020. (interactive)
  16021. (cond
  16022. ((org-at-table-p)
  16023. (call-interactively 'org-table-recalculate))
  16024. (t
  16025. ;; Convert all lines in region to list items
  16026. (call-interactively 'org-toggle-heading))))
  16027. (defun org-ctrl-c-minus ()
  16028. "Insert separator line in table or modify bullet status of line.
  16029. Also turns a plain line or a region of lines into list items.
  16030. Calls `org-table-insert-hline', `org-toggle-item', or
  16031. `org-cycle-list-bullet', depending on context."
  16032. (interactive)
  16033. (cond
  16034. ((org-at-table-p)
  16035. (call-interactively 'org-table-insert-hline))
  16036. ((org-region-active-p)
  16037. (call-interactively 'org-toggle-item))
  16038. ((org-in-item-p)
  16039. (call-interactively 'org-cycle-list-bullet))
  16040. (t
  16041. (call-interactively 'org-toggle-item))))
  16042. (defun org-toggle-heading (&optional nstars)
  16043. "Convert headings to normal text, or items or text to headings.
  16044. If there is no active region, only convert the current line.
  16045. With a `\\[universal-argument]' prefix, convert the whole list at
  16046. point into heading.
  16047. In a region:
  16048. - If the first non blank line is a headline, remove the stars
  16049. from all headlines in the region.
  16050. - If it is a normal line, turn each and every normal line (i.e.,
  16051. not an heading or an item) in the region into headings. If you
  16052. want to convert only the first line of this region, use one
  16053. universal prefix argument.
  16054. - If it is a plain list item, turn all plain list items into headings.
  16055. When converting a line into a heading, the number of stars is chosen
  16056. such that the lines become children of the current entry. However,
  16057. when a numeric prefix argument is given, its value determines the
  16058. number of stars to add."
  16059. (interactive "P")
  16060. (let ((skip-blanks
  16061. ;; Return beginning of first non-blank line, starting from
  16062. ;; line at POS.
  16063. (lambda (pos)
  16064. (save-excursion
  16065. (goto-char pos)
  16066. (while (org-at-comment-p) (forward-line))
  16067. (skip-chars-forward " \r\t\n")
  16068. (point-at-bol))))
  16069. beg end toggled)
  16070. ;; Determine boundaries of changes. If a universal prefix has
  16071. ;; been given, put the list in a region. If region ends at a bol,
  16072. ;; do not consider the last line to be in the region.
  16073. (when (and current-prefix-arg (org-at-item-p))
  16074. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16075. (org-mark-element))
  16076. (if (org-region-active-p)
  16077. (setq beg (funcall skip-blanks (region-beginning))
  16078. end (copy-marker (save-excursion
  16079. (goto-char (region-end))
  16080. (if (bolp) (point) (point-at-eol)))))
  16081. (setq beg (funcall skip-blanks (point-at-bol))
  16082. end (copy-marker (point-at-eol))))
  16083. ;; Ensure inline tasks don't count as headings.
  16084. (org-with-limited-levels
  16085. (save-excursion
  16086. (goto-char beg)
  16087. (cond
  16088. ;; Case 1. Started at an heading: de-star headings.
  16089. ((org-at-heading-p)
  16090. (while (< (point) end)
  16091. (when (org-at-heading-p)
  16092. (looking-at org-outline-regexp) (replace-match "")
  16093. (setq toggled t))
  16094. (forward-line)))
  16095. ;; Case 2. Started at an item: change items into headlines.
  16096. ;; One star will be added by `org-list-to-subtree'.
  16097. ((org-at-item-p)
  16098. (while (< (point) end)
  16099. (when (org-at-item-p)
  16100. ;; Pay attention to cases when region ends before list.
  16101. (let* ((struct (org-list-struct))
  16102. (list-end
  16103. (min (org-list-get-bottom-point struct) (1+ end))))
  16104. (save-restriction
  16105. (narrow-to-region (point) list-end)
  16106. (insert (org-list-to-subtree
  16107. (org-list-to-lisp t)
  16108. (pcase (org-current-level)
  16109. (`nil 1)
  16110. (l (1+ (org-reduced-level l)))))
  16111. "\n")))
  16112. (setq toggled t))
  16113. (forward-line)))
  16114. ;; Case 3. Started at normal text: make every line an heading,
  16115. ;; skipping headlines and items.
  16116. (t (let* ((stars
  16117. (make-string
  16118. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16119. (add-stars
  16120. (cond (nstars "") ; stars from prefix only
  16121. ((equal stars "") "*") ; before first heading
  16122. (org-odd-levels-only "**") ; inside heading, odd
  16123. (t "*"))) ; inside heading, oddeven
  16124. (rpl (concat stars add-stars " "))
  16125. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16126. (while (< (point) (if (equal nstars '(4)) lend end))
  16127. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16128. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16129. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16130. (forward-line)))))))
  16131. (unless toggled (message "Cannot toggle heading from here"))))
  16132. (defun org-meta-return (&optional arg)
  16133. "Insert a new heading or wrap a region in a table.
  16134. Calls `org-insert-heading', `org-insert-item' or
  16135. `org-table-wrap-region', depending on context. When called with
  16136. an argument, unconditionally call `org-insert-heading'."
  16137. (interactive "P")
  16138. (org-fold-check-before-invisible-edit 'insert)
  16139. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16140. (call-interactively (cond (arg #'org-insert-heading)
  16141. ((org-at-table-p) #'org-table-wrap-region)
  16142. ((org-in-item-p) #'org-insert-item)
  16143. (t #'org-insert-heading)))))
  16144. ;;; Menu entries
  16145. (defsubst org-in-subtree-not-table-p ()
  16146. "Are we in a subtree and not in a table?"
  16147. (and (not (org-before-first-heading-p))
  16148. (not (org-at-table-p))))
  16149. ;; Define the Org mode menus
  16150. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16151. `("Org"
  16152. ("Show/Hide"
  16153. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16154. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16155. ["Sparse Tree..." org-sparse-tree t]
  16156. ["Reveal Context" org-fold-reveal t]
  16157. ["Show All" org-fold-show-all t]
  16158. "--"
  16159. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16160. "--"
  16161. ["New Heading" org-insert-heading t]
  16162. ("Navigate Headings"
  16163. ["Up" outline-up-heading t]
  16164. ["Next" outline-next-visible-heading t]
  16165. ["Previous" outline-previous-visible-heading t]
  16166. ["Next Same Level" outline-forward-same-level t]
  16167. ["Previous Same Level" outline-backward-same-level t]
  16168. "--"
  16169. ["Jump" org-goto t])
  16170. ("Edit Structure"
  16171. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16172. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16173. "--"
  16174. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16175. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16176. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16177. "--"
  16178. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16179. "--"
  16180. ["Copy visible text" org-copy-visible t]
  16181. "--"
  16182. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16183. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16184. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16185. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16186. "--"
  16187. ["Sort Region/Children" org-sort t]
  16188. "--"
  16189. ["Convert to odd levels" org-convert-to-odd-levels t]
  16190. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16191. ("Editing"
  16192. ["Emphasis..." org-emphasize t]
  16193. ["Add block structure" org-insert-structure-template t]
  16194. ["Edit Source Example" org-edit-special t]
  16195. "--"
  16196. ["Footnote new/jump" org-footnote-action t]
  16197. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16198. ("Archive"
  16199. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16200. "--"
  16201. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16202. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16203. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16204. "--"
  16205. ("Hyperlinks"
  16206. ["Store Link (Global)" org-store-link t]
  16207. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16208. ["Insert Link" org-insert-link t]
  16209. ["Follow Link" org-open-at-point t]
  16210. "--"
  16211. ["Next link" org-next-link t]
  16212. ["Previous link" org-previous-link t]
  16213. "--"
  16214. ["Descriptive Links"
  16215. org-toggle-link-display
  16216. :style radio
  16217. :selected org-descriptive-links
  16218. ]
  16219. ["Literal Links"
  16220. org-toggle-link-display
  16221. :style radio
  16222. :selected (not org-descriptive-links)])
  16223. "--"
  16224. ("TODO Lists"
  16225. ["TODO/DONE/-" org-todo t]
  16226. ("Select keyword"
  16227. ["Next keyword" org-shiftright (org-at-heading-p)]
  16228. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16229. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16230. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16231. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16232. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16233. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16234. "--"
  16235. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16236. :selected org-enforce-todo-dependencies :style toggle :active t]
  16237. "Settings for tree at point"
  16238. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16239. :selected (org-entry-get nil "ORDERED")
  16240. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16241. ["Do Children parallel" org-toggle-ordered-property :style radio
  16242. :selected (not (org-entry-get nil "ORDERED"))
  16243. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16244. "--"
  16245. ["Set Priority" org-priority t]
  16246. ["Priority Up" org-shiftup t]
  16247. ["Priority Down" org-shiftdown t]
  16248. "--"
  16249. ["Get news from all feeds" org-feed-update-all t]
  16250. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16251. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16252. ("TAGS and Properties"
  16253. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16254. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16255. "--"
  16256. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16257. ["Column view of properties" org-columns t]
  16258. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16259. ("Dates and Scheduling"
  16260. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16261. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16262. ("Change Date"
  16263. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16264. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16265. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16266. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16267. ["Compute Time Range" org-evaluate-time-range t]
  16268. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16269. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16270. "--"
  16271. ["Custom time format" org-toggle-time-stamp-overlays
  16272. :style radio :selected org-display-custom-times]
  16273. "--"
  16274. ["Goto Calendar" org-goto-calendar t]
  16275. ["Date from Calendar" org-date-from-calendar t]
  16276. "--"
  16277. ["Start/Restart Timer" org-timer-start t]
  16278. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16279. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16280. ["Insert Timer String" org-timer t]
  16281. ["Insert Timer Item" org-timer-item t])
  16282. ("Logging work"
  16283. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16284. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16285. ["Clock out" org-clock-out t]
  16286. ["Clock cancel" org-clock-cancel t]
  16287. "--"
  16288. ["Mark as default task" org-clock-mark-default-task t]
  16289. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16290. ["Goto running clock" org-clock-goto t]
  16291. "--"
  16292. ["Display times" org-clock-display t]
  16293. ["Create clock table" org-clock-report t]
  16294. "--"
  16295. ["Record DONE time"
  16296. (progn (setq org-log-done (not org-log-done))
  16297. (message "Switching to %s will %s record a timestamp"
  16298. (car org-done-keywords)
  16299. (if org-log-done "automatically" "not")))
  16300. :style toggle :selected org-log-done])
  16301. "--"
  16302. ["Agenda Command..." org-agenda t]
  16303. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16304. ("File List for Agenda")
  16305. ("Special views current file"
  16306. ["TODO Tree" org-show-todo-tree t]
  16307. ["Check Deadlines" org-check-deadlines t]
  16308. ["Tags/Property tree" org-match-sparse-tree t])
  16309. "--"
  16310. ["Export/Publish..." org-export-dispatch t]
  16311. ("LaTeX"
  16312. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16313. :style toggle :selected org-cdlatex-mode]
  16314. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16315. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16316. ["Modify math symbol" org-cdlatex-math-modify
  16317. (org-inside-LaTeX-fragment-p)]
  16318. ["Insert citation" org-reftex-citation t])
  16319. "--"
  16320. ("Documentation"
  16321. ["Show Version" org-version t]
  16322. ["Info Documentation" org-info t]
  16323. ["Browse Org News" org-browse-news t])
  16324. ("Customize"
  16325. ["Browse Org Group" org-customize t]
  16326. "--"
  16327. ["Expand This Menu" org-create-customize-menu t])
  16328. ["Send bug report" org-submit-bug-report t]
  16329. "--"
  16330. ("Refresh/Reload"
  16331. ["Refresh setup current buffer" org-mode-restart t]
  16332. ["Reload Org (after update)" org-reload t]
  16333. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16334. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16335. '("Table"
  16336. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16337. ["Next Field" org-cycle (org-at-table-p)]
  16338. ["Previous Field" org-shifttab (org-at-table-p)]
  16339. ["Next Row" org-return (org-at-table-p)]
  16340. "--"
  16341. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16342. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16343. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16344. "--"
  16345. ("Column"
  16346. ["Move Column Left" org-metaleft (org-at-table-p)]
  16347. ["Move Column Right" org-metaright (org-at-table-p)]
  16348. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16349. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16350. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16351. ("Row"
  16352. ["Move Row Up" org-metaup (org-at-table-p)]
  16353. ["Move Row Down" org-metadown (org-at-table-p)]
  16354. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16355. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16356. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16357. "--"
  16358. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16359. ("Rectangle"
  16360. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16361. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16362. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16363. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16364. "--"
  16365. ("Calculate"
  16366. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16367. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16368. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16369. "--"
  16370. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16371. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16372. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16373. "--"
  16374. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16375. "--"
  16376. ["Sum Column/Rectangle" org-table-sum
  16377. (or (org-at-table-p) (org-region-active-p))]
  16378. ["Which Column?" org-table-current-column (org-at-table-p)])
  16379. ["Debug Formulas"
  16380. org-table-toggle-formula-debugger
  16381. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16382. ["Show Col/Row Numbers"
  16383. org-table-toggle-coordinate-overlays
  16384. :style toggle
  16385. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16386. "--"
  16387. ["Create" org-table-create (not (org-at-table-p))]
  16388. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16389. ["Import from File" org-table-import (not (org-at-table-p))]
  16390. ["Export to File" org-table-export (org-at-table-p)]
  16391. "--"
  16392. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16393. "--"
  16394. ("Plot"
  16395. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16396. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16397. (defun org-info (&optional node)
  16398. "Read documentation for Org in the info system.
  16399. With optional NODE, go directly to that node."
  16400. (interactive)
  16401. (info (format "(org)%s" (or node ""))))
  16402. (defun org-browse-news ()
  16403. "Browse the news for the latest major release."
  16404. (interactive)
  16405. (browse-url "https://orgmode.org/Changes.html"))
  16406. ;;;###autoload
  16407. (defun org-submit-bug-report ()
  16408. "Submit a bug report on Org via mail.
  16409. Don't hesitate to report any problems or inaccurate documentation.
  16410. If you don't have setup sending mail from (X)Emacs, please copy the
  16411. output buffer into your mail program, as it gives us important
  16412. information about your Org version and configuration."
  16413. (interactive)
  16414. (require 'reporter)
  16415. (defvar reporter-prompt-for-summary-p)
  16416. (org-load-modules-maybe)
  16417. (org-require-autoloaded-modules)
  16418. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16419. (reporter-submit-bug-report
  16420. "emacs-orgmode@gnu.org"
  16421. (org-version nil 'full)
  16422. (let (list)
  16423. (save-window-excursion
  16424. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16425. (delete-other-windows)
  16426. (erase-buffer)
  16427. (insert "You are about to submit a bug report to the Org mailing list.
  16428. If your report is about Org installation, please read this section:
  16429. https://orgmode.org/org.html#Installation
  16430. Please read https://orgmode.org/org.html#Feedback on how to make
  16431. a good report, it will help Org contributors fixing your problem.
  16432. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16433. if the issue you are about to raise has already been dealt with.
  16434. We also would like to add your full Org and Outline configuration
  16435. to the bug report. It will help us debugging the issue.
  16436. *HOWEVER*, some variables you have customized may contain private
  16437. information. The names of customers, colleagues, or friends, might
  16438. appear in the form of file names, tags, todo states or search strings.
  16439. If you answer \"yes\" to the prompt, you might want to check and remove
  16440. such private information before sending the email.")
  16441. (add-text-properties (point-min) (point-max) '(face org-warning))
  16442. (when (yes-or-no-p "Include your Org configuration ")
  16443. (mapatoms
  16444. (lambda (v)
  16445. (and (boundp v)
  16446. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16447. (or (and (symbol-value v)
  16448. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16449. (and
  16450. (get v 'custom-type) (get v 'standard-value)
  16451. (not (equal (symbol-value v)
  16452. (eval (car (get v 'standard-value)) t)))))
  16453. (push v list)))))
  16454. (kill-buffer (get-buffer "*Warn about privacy*"))
  16455. list))
  16456. nil nil
  16457. "Remember to cover the basics, that is, what you expected to happen and
  16458. what in fact did happen. You don't know how to make a good report? See
  16459. https://orgmode.org/manual/Feedback.html#Feedback
  16460. Your bug report will be posted to the Org mailing list.
  16461. ------------------------------------------------------------------------")
  16462. (save-excursion
  16463. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16464. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16465. (defun org-install-agenda-files-menu ()
  16466. "Install agenda file menu."
  16467. (let ((bl (buffer-list)))
  16468. (save-excursion
  16469. (while bl
  16470. (set-buffer (pop bl))
  16471. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16472. (when (derived-mode-p 'org-mode)
  16473. (easy-menu-change
  16474. '("Org") "File List for Agenda"
  16475. (append
  16476. (list
  16477. ["Edit File List" (org-edit-agenda-file-list) t]
  16478. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16479. ["Remove Current File from List" org-remove-file t]
  16480. ["Cycle through agenda files" org-cycle-agenda-files t]
  16481. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16482. "--")
  16483. (mapcar 'org-file-menu-entry
  16484. ;; Prevent initialization from failing.
  16485. (ignore-errors (org-agenda-files t)))))))))
  16486. ;;;; Documentation
  16487. (defun org-require-autoloaded-modules ()
  16488. (interactive)
  16489. (mapc #'require
  16490. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16491. org-table org-timer)))
  16492. ;;;###autoload
  16493. (defun org-reload (&optional uncompiled)
  16494. "Reload all Org Lisp files.
  16495. With prefix arg UNCOMPILED, load the uncompiled versions."
  16496. (interactive "P")
  16497. (require 'loadhist)
  16498. (let* ((org-dir (org-find-library-dir "org"))
  16499. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16500. (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  16501. (remove-re (format "\\`%s\\'"
  16502. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16503. (feats (delete-dups
  16504. (mapcar 'file-name-sans-extension
  16505. (mapcar 'file-name-nondirectory
  16506. (delq nil
  16507. (mapcar 'feature-file
  16508. features))))))
  16509. (lfeat (append
  16510. (sort
  16511. (setq feats
  16512. (delq nil (mapcar
  16513. (lambda (f)
  16514. (if (and (string-match feature-re f)
  16515. (not (string-match remove-re f)))
  16516. f nil))
  16517. feats)))
  16518. 'string-lessp)
  16519. (list "org-version" "org")))
  16520. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16521. load-uncore load-misses)
  16522. (setq load-misses
  16523. (delq t
  16524. (mapcar (lambda (f)
  16525. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16526. (and (string= org-dir contrib-dir)
  16527. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16528. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16529. (push f load-uncore)
  16530. t)
  16531. f))
  16532. lfeat)))
  16533. (when load-uncore
  16534. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16535. (if (> (length load-uncore) 1) "s were" " was")
  16536. (reverse load-uncore)))
  16537. (if load-misses
  16538. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16539. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16540. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16541. ;;;###autoload
  16542. (defun org-customize ()
  16543. "Call the customize function with org as argument."
  16544. (interactive)
  16545. (org-load-modules-maybe)
  16546. (org-require-autoloaded-modules)
  16547. (customize-browse 'org))
  16548. (defun org-create-customize-menu ()
  16549. "Create a full customization menu for Org mode, insert it into the menu."
  16550. (interactive)
  16551. (org-load-modules-maybe)
  16552. (org-require-autoloaded-modules)
  16553. (easy-menu-change
  16554. '("Org") "Customize"
  16555. `(["Browse Org group" org-customize t]
  16556. "--"
  16557. ,(customize-menu-create 'org)
  16558. ["Set" Custom-set t]
  16559. ["Save" Custom-save t]
  16560. ["Reset to Current" Custom-reset-current t]
  16561. ["Reset to Saved" Custom-reset-saved t]
  16562. ["Reset to Standard Settings" Custom-reset-standard t]))
  16563. (message "\"Org\"-menu now contains full customization menu"))
  16564. ;;;; Miscellaneous stuff
  16565. ;;; Generally useful functions
  16566. (defun org-in-clocktable-p ()
  16567. "Check if the cursor is in a clocktable."
  16568. (let ((pos (point)) start)
  16569. (save-excursion
  16570. (end-of-line 1)
  16571. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16572. (setq start (match-beginning 0))
  16573. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16574. (>= (match-end 0) pos)
  16575. start))))
  16576. (defun org-in-verbatim-emphasis ()
  16577. (save-match-data
  16578. (and (org-in-regexp org-verbatim-re 2)
  16579. (>= (point) (match-beginning 3))
  16580. (<= (point) (match-end 4)))))
  16581. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16582. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16583. (if (and marker (marker-buffer marker)
  16584. (buffer-live-p (marker-buffer marker)))
  16585. (progn
  16586. (pop-to-buffer-same-window (marker-buffer marker))
  16587. (when (or (> marker (point-max)) (< marker (point-min)))
  16588. (widen))
  16589. (goto-char marker)
  16590. (org-fold-show-context 'org-goto))
  16591. (if bookmark
  16592. (bookmark-jump bookmark)
  16593. (error "Cannot find location"))))
  16594. (defun org-quote-csv-field (s)
  16595. "Quote field for inclusion in CSV material."
  16596. (if (string-match "[\",]" s)
  16597. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16598. s))
  16599. (defun org-force-self-insert (N)
  16600. "Needed to enforce self-insert under remapping."
  16601. (interactive "p")
  16602. (self-insert-command N))
  16603. (defun org-quote-vert (s)
  16604. "Replace \"|\" with \"\\vert\"."
  16605. (while (string-match "|" s)
  16606. (setq s (replace-match "\\vert" t t s)))
  16607. s)
  16608. (defun org-uuidgen-p (s)
  16609. "Is S an ID created by UUIDGEN?"
  16610. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16611. (defun org-in-src-block-p (&optional inside element)
  16612. "Whether point is in a code source block.
  16613. When INSIDE is non-nil, don't consider we are within a source
  16614. block when point is at #+BEGIN_SRC or #+END_SRC.
  16615. When ELEMENT is provided, it is considered to be element at point."
  16616. (save-match-data (setq element (or element (org-element-at-point))))
  16617. (when (eq 'src-block (org-element-type element))
  16618. (or (not inside)
  16619. (not (or (= (line-beginning-position)
  16620. (org-element-property :post-affiliated element))
  16621. (= (1+ (line-end-position))
  16622. (- (org-element-property :end element)
  16623. (org-element-property :post-blank element))))))))
  16624. (defun org-context ()
  16625. "Return a list of contexts of the current cursor position.
  16626. If several contexts apply, all are returned.
  16627. Each context entry is a list with a symbol naming the context, and
  16628. two positions indicating start and end of the context. Possible
  16629. contexts are:
  16630. :headline anywhere in a headline
  16631. :headline-stars on the leading stars in a headline
  16632. :todo-keyword on a TODO keyword (including DONE) in a headline
  16633. :tags on the TAGS in a headline
  16634. :priority on the priority cookie in a headline
  16635. :item on the first line of a plain list item
  16636. :item-bullet on the bullet/number of a plain list item
  16637. :checkbox on the checkbox in a plain list item
  16638. :table in an Org table
  16639. :table-special on a special filed in a table
  16640. :table-table in a table.el table
  16641. :clocktable in a clocktable
  16642. :src-block in a source block
  16643. :link on a hyperlink
  16644. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16645. :latex-fragment on a LaTeX fragment
  16646. :latex-preview on a LaTeX fragment with overlaid preview image
  16647. This function expects the position to be visible because it uses font-lock
  16648. faces as a help to recognize the following contexts: :table-special, :link,
  16649. and :keyword."
  16650. (let* ((f (get-text-property (point) 'face))
  16651. (faces (if (listp f) f (list f)))
  16652. (case-fold-search t)
  16653. (p (point)) clist o)
  16654. ;; First the large context
  16655. (cond
  16656. ((org-at-heading-p)
  16657. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16658. (when (progn
  16659. (beginning-of-line 1)
  16660. (looking-at org-todo-line-tags-regexp))
  16661. (push (org-point-in-group p 1 :headline-stars) clist)
  16662. (push (org-point-in-group p 2 :todo-keyword) clist)
  16663. (push (org-point-in-group p 4 :tags) clist))
  16664. (goto-char p)
  16665. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16666. (when (looking-at "\\[#[A-Z0-9]\\]")
  16667. (push (org-point-in-group p 0 :priority) clist)))
  16668. ((org-at-item-p)
  16669. (push (org-point-in-group p 2 :item-bullet) clist)
  16670. (push (list :item (point-at-bol)
  16671. (save-excursion (org-end-of-item) (point)))
  16672. clist)
  16673. (and (org-at-item-checkbox-p)
  16674. (push (org-point-in-group p 0 :checkbox) clist)))
  16675. ((org-at-table-p)
  16676. (push (list :table (org-table-begin) (org-table-end)) clist)
  16677. (when (memq 'org-formula faces)
  16678. (push (list :table-special
  16679. (previous-single-property-change p 'face)
  16680. (next-single-property-change p 'face))
  16681. clist)))
  16682. ((org-at-table-p 'any)
  16683. (push (list :table-table) clist)))
  16684. (goto-char p)
  16685. (let ((case-fold-search t))
  16686. ;; New the "medium" contexts: clocktables, source blocks
  16687. (cond ((org-in-clocktable-p)
  16688. (push (list :clocktable
  16689. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16690. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16691. (match-beginning 1))
  16692. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16693. (match-end 0)))
  16694. clist))
  16695. ((org-in-src-block-p)
  16696. (push (list :src-block
  16697. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16698. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16699. (match-beginning 1))
  16700. (and (search-forward "#+END_SRC" nil t)
  16701. (match-beginning 0)))
  16702. clist))))
  16703. (goto-char p)
  16704. ;; Now the small context
  16705. (cond
  16706. ((org-at-timestamp-p)
  16707. (push (org-point-in-group p 0 :timestamp) clist))
  16708. ((memq 'org-link faces)
  16709. (push (list :link
  16710. (previous-single-property-change p 'face)
  16711. (next-single-property-change p 'face))
  16712. clist))
  16713. ((memq 'org-special-keyword faces)
  16714. (push (list :keyword
  16715. (previous-single-property-change p 'face)
  16716. (next-single-property-change p 'face))
  16717. clist))
  16718. ((setq o (cl-some
  16719. (lambda (o)
  16720. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16721. o))
  16722. (overlays-at (point))))
  16723. (push (list :latex-fragment
  16724. (overlay-start o) (overlay-end o))
  16725. clist)
  16726. (push (list :latex-preview
  16727. (overlay-start o) (overlay-end o))
  16728. clist))
  16729. ((org-inside-LaTeX-fragment-p)
  16730. ;; FIXME: positions wrong.
  16731. (push (list :latex-fragment (point) (point)) clist)))
  16732. (setq clist (nreverse (delq nil clist)))
  16733. clist))
  16734. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16735. "Non-nil when point is between matches of START-RE and END-RE.
  16736. Also return a non-nil value when point is on one of the matches.
  16737. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16738. buffer positions. Default values are the positions of headlines
  16739. surrounding the point.
  16740. The functions returns a cons cell whose car (resp. cdr) is the
  16741. position before START-RE (resp. after END-RE)."
  16742. (save-match-data
  16743. (let ((pos (point))
  16744. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16745. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16746. beg end)
  16747. (save-excursion
  16748. ;; Point is on a block when on START-RE or if START-RE can be
  16749. ;; found before it...
  16750. (and (or (org-in-regexp start-re)
  16751. (re-search-backward start-re limit-up t))
  16752. (setq beg (match-beginning 0))
  16753. ;; ... and END-RE after it...
  16754. (goto-char (match-end 0))
  16755. (re-search-forward end-re limit-down t)
  16756. (> (setq end (match-end 0)) pos)
  16757. ;; ... without another START-RE in-between.
  16758. (goto-char (match-beginning 0))
  16759. (not (re-search-backward start-re (1+ beg) t))
  16760. ;; Return value.
  16761. (cons beg end))))))
  16762. (defun org-in-block-p (names)
  16763. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16764. NAMES is a list of strings containing names of blocks.
  16765. Return first block name matched, or nil. Beware that in case of
  16766. nested blocks, the returned name may not belong to the closest
  16767. block from point."
  16768. (save-match-data
  16769. (catch 'exit
  16770. (let ((case-fold-search t)
  16771. (lim-up (save-excursion (outline-previous-heading)))
  16772. (lim-down (save-excursion (outline-next-heading))))
  16773. (dolist (name names)
  16774. (let ((n (regexp-quote name)))
  16775. (when (org-between-regexps-p
  16776. (concat "^[ \t]*#\\+begin_" n)
  16777. (concat "^[ \t]*#\\+end_" n)
  16778. lim-up lim-down)
  16779. (throw 'exit n)))))
  16780. nil)))
  16781. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16782. "Call `multi-occur' with buffers for all agenda files."
  16783. (interactive "sOrg-files matching: ")
  16784. (let* ((files (org-agenda-files))
  16785. (tnames (mapcar #'file-truename files))
  16786. (extra org-agenda-text-search-extra-files))
  16787. (when (eq (car extra) 'agenda-archives)
  16788. (setq extra (cdr extra))
  16789. (setq files (org-add-archive-files files)))
  16790. (dolist (f extra)
  16791. (unless (member (file-truename f) tnames)
  16792. (unless (member f files) (setq files (append files (list f))))
  16793. (setq tnames (append tnames (list (file-truename f))))))
  16794. (multi-occur
  16795. (mapcar (lambda (x)
  16796. (with-current-buffer
  16797. ;; FIXME: Why not just (find-file-noselect x)?
  16798. ;; Is it to avoid the "revert buffer" prompt?
  16799. (or (get-file-buffer x) (find-file-noselect x))
  16800. (widen)
  16801. (current-buffer)))
  16802. files)
  16803. regexp)))
  16804. (add-hook 'occur-mode-find-occurrence-hook
  16805. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16806. (defun org-occur-link-in-agenda-files ()
  16807. "Create a link and search for it in the agendas.
  16808. The link is not stored in `org-stored-links', it is just created
  16809. for the search purpose."
  16810. (interactive)
  16811. (let ((link (condition-case nil
  16812. (org-store-link nil)
  16813. (error "Unable to create a link to here"))))
  16814. (org-occur-in-agenda-files (regexp-quote link))))
  16815. (defun org-back-over-empty-lines ()
  16816. "Move backwards over whitespace, to the beginning of the first empty line.
  16817. Returns the number of empty lines passed."
  16818. (let ((pos (point)))
  16819. (if (cdr (assq 'heading org-blank-before-new-entry))
  16820. (skip-chars-backward " \t\n\r")
  16821. (unless (eobp)
  16822. (forward-line -1)))
  16823. (beginning-of-line 2)
  16824. (goto-char (min (point) pos))
  16825. (count-lines (point) pos)))
  16826. ;;; TODO: Only called once, from ox-odt which should probably use
  16827. ;;; org-export-inline-image-p or something.
  16828. (defun org-file-image-p (file)
  16829. "Return non-nil if FILE is an image."
  16830. (save-match-data
  16831. (string-match (image-file-name-regexp) file)))
  16832. (defun org-get-cursor-date (&optional with-time)
  16833. "Return the date at cursor in as a time.
  16834. This works in the calendar and in the agenda, anywhere else it just
  16835. returns the current time.
  16836. If WITH-TIME is non-nil, returns the time of the event at point (in
  16837. the agenda) or the current time of the day; otherwise returns the
  16838. earliest time on the cursor date that Org treats as that date
  16839. (bearing in mind `org-extend-today-until')."
  16840. (let (date day defd tp hod mod)
  16841. (when with-time
  16842. (setq tp (get-text-property (point) 'time))
  16843. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16844. (setq hod (string-to-number (match-string 1 tp))
  16845. mod (string-to-number (match-string 2 tp))))
  16846. (or tp (let ((now (decode-time)))
  16847. (setq hod (nth 2 now)
  16848. mod (nth 1 now)))))
  16849. (cond
  16850. ((eq major-mode 'calendar-mode)
  16851. (setq date (calendar-cursor-to-date)
  16852. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16853. (nth 1 date) (nth 0 date) (nth 2 date))))
  16854. ((eq major-mode 'org-agenda-mode)
  16855. (setq day (get-text-property (point) 'day))
  16856. (when day
  16857. (setq date (calendar-gregorian-from-absolute day)
  16858. defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16859. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16860. (or defd (current-time))))
  16861. (defun org-mark-subtree (&optional up)
  16862. "Mark the current subtree.
  16863. This puts point at the start of the current subtree, and mark at
  16864. the end. If a numeric prefix UP is given, move up into the
  16865. hierarchy of headlines by UP levels before marking the subtree."
  16866. (interactive "P")
  16867. (org-with-limited-levels
  16868. (cond ((org-at-heading-p) (beginning-of-line))
  16869. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16870. (t (outline-previous-visible-heading 1))))
  16871. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16872. (if (called-interactively-p 'any)
  16873. (call-interactively 'org-mark-element)
  16874. (org-mark-element)))
  16875. ;;; Indentation
  16876. (defvar org-element-greater-elements)
  16877. (defun org--get-expected-indentation (element contentsp)
  16878. "Expected indentation column for current line, according to ELEMENT.
  16879. ELEMENT is an element containing point. CONTENTSP is non-nil
  16880. when indentation is to be computed according to contents of
  16881. ELEMENT."
  16882. (let ((type (org-element-type element))
  16883. (start (org-element-property :begin element))
  16884. (post-affiliated (org-element-property :post-affiliated element)))
  16885. (org-with-wide-buffer
  16886. (cond
  16887. (contentsp
  16888. (cl-case type
  16889. ((diary-sexp footnote-definition) 0)
  16890. (section
  16891. (org--get-expected-indentation
  16892. (org-element-property :parent element)
  16893. t))
  16894. ((headline inlinetask nil)
  16895. (if (not org-adapt-indentation) 0
  16896. (let ((level (org-current-level)))
  16897. (if level (1+ level) 0))))
  16898. ((item plain-list) (org-list-item-body-column post-affiliated))
  16899. (t
  16900. (goto-char start)
  16901. (current-indentation))))
  16902. ((memq type '(headline inlinetask nil))
  16903. (if (org-match-line "[ \t]*$")
  16904. (org--get-expected-indentation element t)
  16905. 0))
  16906. ((memq type '(diary-sexp footnote-definition)) 0)
  16907. ;; First paragraph of a footnote definition or an item.
  16908. ;; Indent like parent.
  16909. ((< (line-beginning-position) start)
  16910. (org--get-expected-indentation
  16911. (org-element-property :parent element) t))
  16912. ;; At first line: indent according to previous sibling, if any,
  16913. ;; ignoring footnote definitions and inline tasks, or parent's
  16914. ;; contents. If `org-adapt-indentation' is `headline-data', ignore
  16915. ;; previous headline data siblings.
  16916. ((= (line-beginning-position) start)
  16917. (catch 'exit
  16918. (while t
  16919. (if (= (point-min) start) (throw 'exit 0)
  16920. (goto-char (1- start))
  16921. (let* ((previous (org-element-at-point))
  16922. (parent previous))
  16923. (while (and parent (<= (org-element-property :end parent) start))
  16924. (setq previous parent
  16925. parent (org-element-property :parent parent)))
  16926. (cond
  16927. ((not previous) (throw 'exit 0))
  16928. ((> (org-element-property :end previous) start)
  16929. (throw 'exit (org--get-expected-indentation previous t)))
  16930. ((memq (org-element-type previous)
  16931. '(footnote-definition inlinetask))
  16932. (setq start (org-element-property :begin previous)))
  16933. ;; Do not indent like previous when the previous
  16934. ;; element is headline data and `org-adapt-indentation'
  16935. ;; is set to `headline-data'.
  16936. ((save-excursion
  16937. (goto-char start)
  16938. (and
  16939. (eq org-adapt-indentation 'headline-data)
  16940. (not (or (org-at-clock-log-p)
  16941. (org-at-planning-p)))
  16942. (progn
  16943. (beginning-of-line 1)
  16944. (skip-chars-backward "\n")
  16945. (or (org-at-heading-p)
  16946. (looking-back ":END:.*" (point-at-bol))))))
  16947. (throw 'exit 0))
  16948. (t (goto-char (org-element-property :begin previous))
  16949. (throw 'exit
  16950. (if (bolp) (current-indentation)
  16951. ;; At first paragraph in an item or
  16952. ;; a footnote definition.
  16953. (org--get-expected-indentation
  16954. (org-element-property :parent previous) t))))))))))
  16955. ;; Otherwise, move to the first non-blank line above.
  16956. (t
  16957. (beginning-of-line)
  16958. (let ((pos (point)))
  16959. (skip-chars-backward " \r\t\n")
  16960. (cond
  16961. ;; Two blank lines end a footnote definition or a plain
  16962. ;; list. When we indent an empty line after them, the
  16963. ;; containing list or footnote definition is over, so it
  16964. ;; qualifies as a previous sibling. Therefore, we indent
  16965. ;; like its first line.
  16966. ((and (memq type '(footnote-definition plain-list))
  16967. (> (count-lines (point) pos) 2))
  16968. (goto-char start)
  16969. (current-indentation))
  16970. ;; Line above is the first one of a paragraph at the
  16971. ;; beginning of an item or a footnote definition. Indent
  16972. ;; like parent.
  16973. ((< (line-beginning-position) start)
  16974. (org--get-expected-indentation
  16975. (org-element-property :parent element) t))
  16976. ;; Line above is the beginning of an element, i.e., point
  16977. ;; was originally on the blank lines between element's start
  16978. ;; and contents.
  16979. ((= (line-beginning-position) post-affiliated)
  16980. (org--get-expected-indentation element t))
  16981. ;; POS is after contents in a greater element. Indent like
  16982. ;; the beginning of the element.
  16983. ((and (memq type org-element-greater-elements)
  16984. (let ((cend (org-element-property :contents-end element)))
  16985. (and cend (<= cend pos))))
  16986. ;; As a special case, if point is at the end of a footnote
  16987. ;; definition or an item, indent like the very last element
  16988. ;; within. If that last element is an item, indent like
  16989. ;; its contents.
  16990. (if (memq type '(footnote-definition item plain-list))
  16991. (let ((last (org-element-at-point)))
  16992. (goto-char pos)
  16993. (org--get-expected-indentation
  16994. last (eq (org-element-type last) 'item)))
  16995. (goto-char start)
  16996. (current-indentation)))
  16997. ;; In any other case, indent like the current line.
  16998. (t (current-indentation)))))
  16999. ;; Finally, no indentation is needed, fall back to 0.
  17000. (t (current-indentation))))))
  17001. (defun org--align-node-property ()
  17002. "Align node property at point.
  17003. Alignment is done according to `org-property-format', which see."
  17004. (when (save-excursion
  17005. (beginning-of-line)
  17006. (looking-at org-property-re))
  17007. (combine-change-calls (match-beginning 0) (match-end 0)
  17008. (let ((newtext (concat (match-string 4)
  17009. (org-trim
  17010. (format org-property-format (match-string 1) (match-string 3))))))
  17011. ;; Do not use `replace-match' here as we want to inherit folding
  17012. ;; properties if inside fold.
  17013. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  17014. (insert-and-inherit newtext)))))
  17015. (defun org-indent-line ()
  17016. "Indent line depending on context.
  17017. Indentation is done according to the following rules:
  17018. - Footnote definitions, diary sexps, headlines and inline tasks
  17019. have to start at column 0.
  17020. - On the very first line of an element, consider, in order, the
  17021. next rules until one matches:
  17022. 1. If there's a sibling element before, ignoring footnote
  17023. definitions and inline tasks, indent like its first line.
  17024. 2. If element has a parent, indent like its contents. More
  17025. precisely, if parent is an item, indent after the bullet.
  17026. Else, indent like parent's first line.
  17027. 3. Otherwise, indent relatively to current level, if
  17028. `org-adapt-indentation' is t, or to left margin.
  17029. - On a blank line at the end of an element, indent according to
  17030. the type of the element. More precisely
  17031. 1. If element is a plain list, an item, or a footnote
  17032. definition, indent like the very last element within.
  17033. 2. If element is a paragraph, indent like its last non blank
  17034. line.
  17035. 3. Otherwise, indent like its very first line.
  17036. - In the code part of a source block, use language major mode
  17037. to indent current line if `org-src-tab-acts-natively' is
  17038. non-nil. If it is nil, do nothing.
  17039. - Otherwise, indent like the first non-blank line above.
  17040. The function doesn't indent an item as it could break the whole
  17041. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17042. `\\[org-shiftmetaright]'.
  17043. Also align node properties according to `org-property-format'."
  17044. (interactive)
  17045. (unless (or (org-at-heading-p)
  17046. (and (eq org-adapt-indentation 'headline-data)
  17047. (not (or (org-at-clock-log-p)
  17048. (org-at-planning-p)))
  17049. (save-excursion
  17050. (beginning-of-line 1)
  17051. (skip-chars-backward "\n")
  17052. (or (org-at-heading-p)
  17053. (looking-back ":END:.*" (point-at-bol))))))
  17054. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  17055. (type (org-element-type element)))
  17056. (cond ((and (memq type '(plain-list item))
  17057. (= (line-beginning-position)
  17058. (org-element-property :post-affiliated element)))
  17059. nil)
  17060. ((and (eq type 'latex-environment)
  17061. (>= (point) (org-element-property :post-affiliated element))
  17062. (< (point)
  17063. (org-with-point-at (org-element-property :end element)
  17064. (skip-chars-backward " \t\n")
  17065. (line-beginning-position 2))))
  17066. nil)
  17067. ((and (eq type 'src-block)
  17068. org-src-tab-acts-natively
  17069. (> (line-beginning-position)
  17070. (org-element-property :post-affiliated element))
  17071. (< (line-beginning-position)
  17072. (org-with-point-at (org-element-property :end element)
  17073. (skip-chars-backward " \t\n")
  17074. (line-beginning-position))))
  17075. ;; At the beginning of a blank line, do some preindentation. This
  17076. ;; signals org-src--edit-element to preserve the indentation on exit
  17077. (when (and (looking-at-p "^[[:space:]]*$")
  17078. (not org-src-preserve-indentation))
  17079. (let ((element (org-element-at-point))
  17080. block-content-ind some-ind)
  17081. (org-with-point-at (org-element-property :begin element)
  17082. (setq block-content-ind (+ (current-indentation)
  17083. org-edit-src-content-indentation))
  17084. (forward-line)
  17085. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17086. (backward-char)
  17087. (setq some-ind (if (looking-at-p "#\\+end_src")
  17088. block-content-ind (current-indentation))))
  17089. (indent-line-to (min block-content-ind some-ind))))
  17090. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17091. (t
  17092. (let ((column (org--get-expected-indentation element nil)))
  17093. ;; Preserve current column.
  17094. (if (<= (current-column) (current-indentation))
  17095. (indent-line-to column)
  17096. (save-excursion (indent-line-to column))))
  17097. ;; Align node property. Also preserve current column.
  17098. (when (eq type 'node-property)
  17099. (let ((column (current-column)))
  17100. (org--align-node-property)
  17101. (org-move-to-column column))))))))
  17102. (defun org-indent-region (start end)
  17103. "Indent each non-blank line in the region.
  17104. Called from a program, START and END specify the region to
  17105. indent. The function will not indent contents of example blocks,
  17106. verse blocks and export blocks as leading white spaces are
  17107. assumed to be significant there."
  17108. (interactive "r")
  17109. (save-excursion
  17110. (goto-char start)
  17111. (skip-chars-forward " \r\t\n")
  17112. (unless (eobp) (beginning-of-line))
  17113. (let ((indent-to
  17114. (lambda (ind pos)
  17115. ;; Set IND as indentation for all lines between point and
  17116. ;; POS. Blank lines are ignored. Leave point after POS
  17117. ;; once done.
  17118. (let ((limit (copy-marker pos)))
  17119. (while (< (point) limit)
  17120. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17121. (forward-line))
  17122. (set-marker limit nil))))
  17123. (end (copy-marker end)))
  17124. (while (< (point) end)
  17125. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17126. (let* ((element (org-element-at-point-no-context))
  17127. (type (org-element-type element))
  17128. (element-end (copy-marker (org-element-property :end element)))
  17129. (ind (org--get-expected-indentation element nil)))
  17130. (cond
  17131. ;; Element indented as a single block. Example blocks
  17132. ;; preserving indentation are a special case since the
  17133. ;; "contents" must not be indented whereas the block
  17134. ;; boundaries can.
  17135. ((or (memq type '(export-block latex-environment))
  17136. (and (eq type 'example-block)
  17137. (not
  17138. (or org-src-preserve-indentation
  17139. (org-element-property :preserve-indent element)))))
  17140. (let ((offset (- ind (current-indentation))))
  17141. (unless (zerop offset)
  17142. (indent-rigidly (org-element-property :begin element)
  17143. (org-element-property :end element)
  17144. offset)))
  17145. (goto-char element-end))
  17146. ;; Elements indented line wise. Be sure to exclude
  17147. ;; example blocks (preserving indentation) and source
  17148. ;; blocks from this category as they are treated
  17149. ;; specially later.
  17150. ((or (memq type '(paragraph table table-row))
  17151. (not (or (org-element-property :contents-begin element)
  17152. (memq type '(example-block src-block)))))
  17153. (when (eq type 'node-property)
  17154. (org--align-node-property)
  17155. (beginning-of-line))
  17156. (funcall indent-to ind (min element-end end)))
  17157. ;; Elements consisting of three parts: before the
  17158. ;; contents, the contents, and after the contents. The
  17159. ;; contents are treated specially, according to the
  17160. ;; element type, or not indented at all. Other parts are
  17161. ;; indented as a single block.
  17162. (t
  17163. (let* ((post (copy-marker
  17164. (org-element-property :post-affiliated element)))
  17165. (cbeg
  17166. (copy-marker
  17167. (cond
  17168. ((not (org-element-property :contents-begin element))
  17169. ;; Fake contents for source blocks.
  17170. (org-with-wide-buffer
  17171. (goto-char post)
  17172. (line-beginning-position 2)))
  17173. ((memq type '(footnote-definition item plain-list))
  17174. ;; Contents in these elements could start on
  17175. ;; the same line as the beginning of the
  17176. ;; element. Make sure we start indenting
  17177. ;; from the second line.
  17178. (org-with-wide-buffer
  17179. (goto-char post)
  17180. (end-of-line)
  17181. (skip-chars-forward " \r\t\n")
  17182. (if (eobp) (point) (line-beginning-position))))
  17183. (t (org-element-property :contents-begin element)))))
  17184. (cend (copy-marker
  17185. (or (org-element-property :contents-end element)
  17186. ;; Fake contents for source blocks.
  17187. (org-with-wide-buffer
  17188. (goto-char element-end)
  17189. (skip-chars-backward " \r\t\n")
  17190. (line-beginning-position)))
  17191. t)))
  17192. ;; Do not change items indentation individually as it
  17193. ;; might break the list as a whole. On the other
  17194. ;; hand, when at a plain list, indent it as a whole.
  17195. (cond ((eq type 'plain-list)
  17196. (let ((offset (- ind (current-indentation))))
  17197. (unless (zerop offset)
  17198. (indent-rigidly (org-element-property :begin element)
  17199. (org-element-property :end element)
  17200. offset))
  17201. (goto-char cbeg)))
  17202. ((eq type 'item) (goto-char cbeg))
  17203. (t (funcall indent-to ind (min cbeg end))))
  17204. (when (< (point) end)
  17205. (cl-case type
  17206. ((example-block verse-block))
  17207. (src-block
  17208. ;; In a source block, indent source code
  17209. ;; according to language major mode, but only if
  17210. ;; `org-src-tab-acts-natively' is non-nil.
  17211. (when (and (< (point) end) org-src-tab-acts-natively)
  17212. (ignore-errors
  17213. (org-babel-do-in-edit-buffer
  17214. (indent-region (point-min) (point-max))))))
  17215. (t (org-indent-region (point) (min cend end))))
  17216. (goto-char (min cend end))
  17217. (when (< (point) end)
  17218. (funcall indent-to ind (min element-end end))))
  17219. (set-marker post nil)
  17220. (set-marker cbeg nil)
  17221. (set-marker cend nil))))
  17222. (set-marker element-end nil))))
  17223. (set-marker end nil))))
  17224. (defun org-indent-drawer ()
  17225. "Indent the drawer at point."
  17226. (interactive)
  17227. (unless (save-excursion
  17228. (beginning-of-line)
  17229. (looking-at-p org-drawer-regexp))
  17230. (user-error "Not at a drawer"))
  17231. (let ((element (org-element-at-point-no-context)))
  17232. (unless (memq (org-element-type element) '(drawer property-drawer))
  17233. (user-error "Not at a drawer"))
  17234. (org-with-wide-buffer
  17235. (org-indent-region (org-element-property :begin element)
  17236. (org-element-property :end element))))
  17237. (message "Drawer at point indented"))
  17238. (defun org-indent-block ()
  17239. "Indent the block at point."
  17240. (interactive)
  17241. (unless (save-excursion
  17242. (beginning-of-line)
  17243. (let ((case-fold-search t))
  17244. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17245. (user-error "Not at a block"))
  17246. (let ((element (org-element-at-point-no-context)))
  17247. (unless (memq (org-element-type element)
  17248. '(comment-block center-block dynamic-block example-block
  17249. export-block quote-block special-block
  17250. src-block verse-block))
  17251. (user-error "Not at a block"))
  17252. (org-with-wide-buffer
  17253. (org-indent-region (org-element-property :begin element)
  17254. (org-element-property :end element))))
  17255. (message "Block at point indented"))
  17256. ;;; Filling
  17257. ;; We use our own fill-paragraph and auto-fill functions.
  17258. ;; `org-fill-paragraph' relies on adaptive filling and context
  17259. ;; checking. Appropriate `fill-prefix' is computed with
  17260. ;; `org-adaptive-fill-function'.
  17261. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17262. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17263. ;; `org-adaptive-fill-function' value. Internally,
  17264. ;; `org-comment-line-break-function' breaks the line.
  17265. ;; `org-setup-filling' installs filling and auto-filling related
  17266. ;; variables during `org-mode' initialization.
  17267. (defvar org--single-lines-list-is-paragraph) ; defined later
  17268. (defun org-setup-filling ()
  17269. (require 'org-element)
  17270. ;; Prevent auto-fill from inserting unwanted new items.
  17271. (setq-local fill-nobreak-predicate
  17272. (org-uniquify
  17273. (append fill-nobreak-predicate
  17274. '(org-fill-line-break-nobreak-p
  17275. org-fill-n-macro-as-item-nobreak-p
  17276. org-fill-paragraph-with-timestamp-nobreak-p))))
  17277. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17278. (setq-local paragraph-start paragraph-ending)
  17279. (setq-local paragraph-separate paragraph-ending))
  17280. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17281. (setq-local fill-forward-paragraph-function
  17282. (lambda (&optional arg)
  17283. (let ((org--single-lines-list-is-paragraph nil))
  17284. (org-forward-paragraph arg))))
  17285. (setq-local auto-fill-inhibit-regexp nil)
  17286. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17287. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17288. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17289. (defun org-fill-line-break-nobreak-p ()
  17290. "Non-nil when a new line at point would create an Org line break."
  17291. (save-excursion
  17292. (skip-chars-backward " \t")
  17293. (skip-chars-backward "\\\\")
  17294. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17295. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17296. "Non-nil when a new line at point would split a timestamp."
  17297. (and (org-at-timestamp-p 'lax)
  17298. (not (looking-at org-ts-regexp-both))))
  17299. (defun org-fill-n-macro-as-item-nobreak-p ()
  17300. "Non-nil when a new line at point would create a new list."
  17301. ;; During export, a "n" macro followed by a dot or a closing
  17302. ;; parenthesis can end up being parsed as a new list item.
  17303. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17304. (defun org-adaptive-fill-function ()
  17305. "Compute a fill prefix for the current line.
  17306. Return fill prefix, as a string, or nil if current line isn't
  17307. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17308. matches in paragraphs or comments, use it."
  17309. (org-with-wide-buffer
  17310. (unless (org-at-heading-p)
  17311. (let* ((p (line-beginning-position))
  17312. (element (save-excursion
  17313. (beginning-of-line)
  17314. (org-element-at-point)))
  17315. (type (org-element-type element))
  17316. (post-affiliated (org-element-property :post-affiliated element)))
  17317. (unless (< p post-affiliated)
  17318. (cl-case type
  17319. (comment
  17320. (save-excursion
  17321. (beginning-of-line)
  17322. (looking-at "[ \t]*")
  17323. (concat (match-string 0) "# ")))
  17324. (footnote-definition "")
  17325. ((item plain-list)
  17326. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17327. (paragraph
  17328. ;; Fill prefix is usually the same as the current line,
  17329. ;; unless the paragraph is at the beginning of an item.
  17330. (let ((parent (org-element-property :parent element)))
  17331. (save-excursion
  17332. (beginning-of-line)
  17333. (cond ((eq (org-element-type parent) 'item)
  17334. (make-string (org-list-item-body-column
  17335. (org-element-property :begin parent))
  17336. ?\s))
  17337. ((and adaptive-fill-regexp
  17338. ;; Locally disable
  17339. ;; `adaptive-fill-function' to let
  17340. ;; `fill-context-prefix' handle
  17341. ;; `adaptive-fill-regexp' variable.
  17342. (let (adaptive-fill-function)
  17343. (fill-context-prefix
  17344. post-affiliated
  17345. (org-element-property :end element)))))
  17346. ((looking-at "[ \t]+") (match-string 0))
  17347. (t "")))))
  17348. (comment-block
  17349. ;; Only fill contents if P is within block boundaries.
  17350. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17351. (forward-line)
  17352. (point)))
  17353. (cend (save-excursion
  17354. (goto-char (org-element-property :end element))
  17355. (skip-chars-backward " \r\t\n")
  17356. (line-beginning-position))))
  17357. (when (and (>= p cbeg) (< p cend))
  17358. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17359. (match-string 0)
  17360. ""))))))))))
  17361. (defun org-fill-element (&optional justify)
  17362. "Fill element at point, when applicable.
  17363. This function only applies to comment blocks, comments, example
  17364. blocks and paragraphs. Also, as a special case, re-align table
  17365. when point is at one.
  17366. If JUSTIFY is non-nil (interactively, with prefix argument),
  17367. justify as well. If `sentence-end-double-space' is non-nil, then
  17368. period followed by one space does not end a sentence, so don't
  17369. break a line there. The variable `fill-column' controls the
  17370. width for filling.
  17371. For convenience, when point is at a plain list, an item or
  17372. a footnote definition, try to fill the first paragraph within."
  17373. (with-syntax-table org-mode-transpose-word-syntax-table
  17374. ;; Move to end of line in order to get the first paragraph within
  17375. ;; a plain list or a footnote definition.
  17376. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17377. ;; First check if point is in a blank line at the beginning of
  17378. ;; the buffer. In that case, ignore filling.
  17379. (cl-case (org-element-type element)
  17380. ;; Use major mode filling function is source blocks.
  17381. (src-block (org-babel-do-in-edit-buffer
  17382. (push-mark (point-min))
  17383. (goto-char (point-max))
  17384. (setq mark-active t)
  17385. (funcall-interactively #'fill-paragraph justify 'region)))
  17386. ;; Align Org tables, leave table.el tables as-is.
  17387. (table-row (org-table-align) t)
  17388. (table
  17389. (when (eq (org-element-property :type element) 'org)
  17390. (save-excursion
  17391. (goto-char (org-element-property :post-affiliated element))
  17392. (org-table-align)))
  17393. t)
  17394. (paragraph
  17395. ;; Paragraphs may contain `line-break' type objects.
  17396. (let ((beg (max (point-min)
  17397. (org-element-property :contents-begin element)))
  17398. (end (min (point-max)
  17399. (org-element-property :contents-end element))))
  17400. ;; Do nothing if point is at an affiliated keyword.
  17401. (if (< (line-end-position) beg) t
  17402. ;; Fill paragraph, taking line breaks into account.
  17403. (save-excursion
  17404. (goto-char beg)
  17405. (let ((cuts (list beg)))
  17406. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17407. (when (eq 'line-break
  17408. (org-element-type
  17409. (save-excursion (backward-char)
  17410. (org-element-context))))
  17411. (push (point) cuts)))
  17412. (dolist (c (delq end cuts))
  17413. (fill-region-as-paragraph c end justify)
  17414. (setq end c))))
  17415. t)))
  17416. ;; Contents of `comment-block' type elements should be
  17417. ;; filled as plain text, but only if point is within block
  17418. ;; markers.
  17419. (comment-block
  17420. (let* ((case-fold-search t)
  17421. (beg (save-excursion
  17422. (goto-char (org-element-property :begin element))
  17423. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17424. (forward-line)
  17425. (point)))
  17426. (end (save-excursion
  17427. (goto-char (org-element-property :end element))
  17428. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17429. (line-beginning-position))))
  17430. (if (or (< (point) beg) (> (point) end)) t
  17431. (fill-region-as-paragraph
  17432. (save-excursion (end-of-line)
  17433. (re-search-backward "^[ \t]*$" beg 'move)
  17434. (line-beginning-position))
  17435. (save-excursion (beginning-of-line)
  17436. (re-search-forward "^[ \t]*$" end 'move)
  17437. (line-beginning-position))
  17438. justify))))
  17439. ;; Fill comments.
  17440. (comment
  17441. (let ((begin (org-element-property :post-affiliated element))
  17442. (end (org-element-property :end element)))
  17443. (when (and (>= (point) begin) (<= (point) end))
  17444. (let ((begin (save-excursion
  17445. (end-of-line)
  17446. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17447. (progn (forward-line) (point))
  17448. begin)))
  17449. (end (save-excursion
  17450. (end-of-line)
  17451. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17452. (1- (line-beginning-position))
  17453. (skip-chars-backward " \r\t\n")
  17454. (line-end-position)))))
  17455. ;; Do not fill comments when at a blank line.
  17456. (when (> end begin)
  17457. (let ((fill-prefix
  17458. (save-excursion
  17459. (beginning-of-line)
  17460. (looking-at "[ \t]*#")
  17461. (let ((comment-prefix (match-string 0)))
  17462. (goto-char (match-end 0))
  17463. (if (looking-at adaptive-fill-regexp)
  17464. (concat comment-prefix (match-string 0))
  17465. (concat comment-prefix " "))))))
  17466. (save-excursion
  17467. (fill-region-as-paragraph begin end justify))))))
  17468. t))
  17469. ;; Ignore every other element.
  17470. (otherwise t)))))
  17471. (defun org-fill-paragraph (&optional justify region)
  17472. "Fill element at point, when applicable.
  17473. This function only applies to comment blocks, comments, example
  17474. blocks and paragraphs. Also, as a special case, re-align table
  17475. when point is at one.
  17476. For convenience, when point is at a plain list, an item or
  17477. a footnote definition, try to fill the first paragraph within.
  17478. If JUSTIFY is non-nil (interactively, with prefix argument),
  17479. justify as well. If `sentence-end-double-space' is non-nil, then
  17480. period followed by one space does not end a sentence, so don't
  17481. break a line there. The variable `fill-column' controls the
  17482. width for filling.
  17483. The REGION argument is non-nil if called interactively; in that
  17484. case, if Transient Mark mode is enabled and the mark is active,
  17485. fill each of the elements in the active region, instead of just
  17486. filling the current element."
  17487. (interactive (progn
  17488. (barf-if-buffer-read-only)
  17489. (list (when current-prefix-arg 'full) t)))
  17490. (let ((hash (and (not (buffer-modified-p))
  17491. (org-buffer-hash))))
  17492. (cond
  17493. ((and region transient-mark-mode mark-active
  17494. (not (eq (region-beginning) (region-end))))
  17495. (let ((origin (point-marker))
  17496. (start (region-beginning)))
  17497. (unwind-protect
  17498. (progn
  17499. (goto-char (region-end))
  17500. (skip-chars-backward " \t\n")
  17501. (let ((org--single-lines-list-is-paragraph nil))
  17502. (while (> (point) start)
  17503. (org-fill-element justify)
  17504. (org-backward-paragraph)
  17505. (skip-chars-backward " \t\n"))))
  17506. (goto-char origin)
  17507. (set-marker origin nil))))
  17508. (t
  17509. (save-excursion
  17510. (when (org-match-line "[ \t]*$")
  17511. (skip-chars-forward " \t\n"))
  17512. (org-fill-element justify))))
  17513. ;; If we didn't change anything in the buffer (and the buffer was
  17514. ;; previously unmodified), then flip the modification status back
  17515. ;; to "unchanged".
  17516. (when (and hash (equal hash (org-buffer-hash)))
  17517. (set-buffer-modified-p nil))
  17518. ;; Return non-nil.
  17519. t))
  17520. (defun org-auto-fill-function ()
  17521. "Auto-fill function."
  17522. ;; Check if auto-filling is meaningful.
  17523. (let ((fc (current-fill-column)))
  17524. (when (and fc (> (current-column) fc))
  17525. (let* ((fill-prefix (org-adaptive-fill-function))
  17526. ;; Enforce empty fill prefix, if required. Otherwise, it
  17527. ;; will be computed again.
  17528. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17529. (when fill-prefix (do-auto-fill))))))
  17530. (defun org-comment-line-break-function (&optional soft)
  17531. "Break line at point and indent, continuing comment if within one.
  17532. The inserted newline is marked hard if variable
  17533. `use-hard-newlines' is true, unless optional argument SOFT is
  17534. non-nil."
  17535. (if soft (insert-and-inherit ?\n) (newline 1))
  17536. (save-excursion (forward-char -1) (delete-horizontal-space))
  17537. (delete-horizontal-space)
  17538. (indent-to-left-margin)
  17539. (insert-before-markers-and-inherit fill-prefix))
  17540. ;;; Fixed Width Areas
  17541. (defun org-toggle-fixed-width ()
  17542. "Toggle fixed-width markup.
  17543. Add or remove fixed-width markup on current line, whenever it
  17544. makes sense. Return an error otherwise.
  17545. If a region is active and if it contains only fixed-width areas
  17546. or blank lines, remove all fixed-width markup in it. If the
  17547. region contains anything else, convert all non-fixed-width lines
  17548. to fixed-width ones.
  17549. Blank lines at the end of the region are ignored unless the
  17550. region only contains such lines."
  17551. (interactive)
  17552. (if (not (org-region-active-p))
  17553. ;; No region:
  17554. ;;
  17555. ;; Remove fixed width marker only in a fixed-with element.
  17556. ;;
  17557. ;; Add fixed width maker in paragraphs, in blank lines after
  17558. ;; elements or at the beginning of a headline or an inlinetask,
  17559. ;; and before any one-line elements (e.g., a clock).
  17560. (progn
  17561. (beginning-of-line)
  17562. (let* ((element (org-element-at-point))
  17563. (type (org-element-type element)))
  17564. (cond
  17565. ((and (eq type 'fixed-width)
  17566. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17567. (replace-match
  17568. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17569. ((and (memq type '(babel-call clock comment diary-sexp headline
  17570. horizontal-rule keyword paragraph
  17571. planning))
  17572. (<= (org-element-property :post-affiliated element) (point)))
  17573. (skip-chars-forward " \t")
  17574. (insert ": "))
  17575. ((and (looking-at-p "[ \t]*$")
  17576. (or (eq type 'inlinetask)
  17577. (save-excursion
  17578. (skip-chars-forward " \r\t\n")
  17579. (<= (org-element-property :end element) (point)))))
  17580. (delete-region (point) (line-end-position))
  17581. (org-indent-line)
  17582. (insert ": "))
  17583. (t (user-error "Cannot insert a fixed-width line here")))))
  17584. ;; Region active.
  17585. (let* ((begin (save-excursion
  17586. (goto-char (region-beginning))
  17587. (line-beginning-position)))
  17588. (end (copy-marker
  17589. (save-excursion
  17590. (goto-char (region-end))
  17591. (unless (eolp) (beginning-of-line))
  17592. (if (save-excursion (re-search-backward "\\S-" begin t))
  17593. (progn (skip-chars-backward " \r\t\n") (point))
  17594. (point)))))
  17595. (all-fixed-width-p
  17596. (catch 'not-all-p
  17597. (save-excursion
  17598. (goto-char begin)
  17599. (skip-chars-forward " \r\t\n")
  17600. (when (eobp) (throw 'not-all-p nil))
  17601. (while (< (point) end)
  17602. (let ((element (org-element-at-point)))
  17603. (if (eq (org-element-type element) 'fixed-width)
  17604. (goto-char (org-element-property :end element))
  17605. (throw 'not-all-p nil))))
  17606. t))))
  17607. (if all-fixed-width-p
  17608. (save-excursion
  17609. (goto-char begin)
  17610. (while (< (point) end)
  17611. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17612. (replace-match
  17613. "" nil nil nil
  17614. (if (= (line-end-position) (match-end 0)) 0 1)))
  17615. (forward-line)))
  17616. (let ((min-ind (point-max)))
  17617. ;; Find minimum indentation across all lines.
  17618. (save-excursion
  17619. (goto-char begin)
  17620. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17621. (setq min-ind 0)
  17622. (catch 'zerop
  17623. (while (< (point) end)
  17624. (unless (looking-at-p "[ \t]*$")
  17625. (let ((ind (current-indentation)))
  17626. (setq min-ind (min min-ind ind))
  17627. (when (zerop ind) (throw 'zerop t))))
  17628. (forward-line)))))
  17629. ;; Loop over all lines and add fixed-width markup everywhere
  17630. ;; but in fixed-width lines.
  17631. (save-excursion
  17632. (goto-char begin)
  17633. (while (< (point) end)
  17634. (cond
  17635. ((org-at-heading-p)
  17636. (insert ": ")
  17637. (forward-line)
  17638. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17639. (insert ":")
  17640. (forward-line)))
  17641. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17642. (let* ((element (org-element-at-point))
  17643. (element-end (org-element-property :end element)))
  17644. (if (eq (org-element-type element) 'fixed-width)
  17645. (progn (goto-char element-end)
  17646. (skip-chars-backward " \r\t\n")
  17647. (forward-line))
  17648. (let ((limit (min end element-end)))
  17649. (while (< (point) limit)
  17650. (org-move-to-column min-ind t)
  17651. (insert ": ")
  17652. (forward-line))))))
  17653. (t
  17654. (org-move-to-column min-ind t)
  17655. (insert ": ")
  17656. (forward-line)))))))
  17657. (set-marker end nil))))
  17658. ;;; Blocks
  17659. (defun org-block-map (function &optional start end)
  17660. "Call FUNCTION at the head of all source blocks in the current buffer.
  17661. Optional arguments START and END can be used to limit the range."
  17662. (let ((start (or start (point-min)))
  17663. (end (or end (point-max))))
  17664. (save-excursion
  17665. (goto-char start)
  17666. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17667. (save-excursion
  17668. (save-match-data
  17669. (goto-char (match-beginning 0))
  17670. (funcall function)))))))
  17671. (defun org-next-block (arg &optional backward block-regexp)
  17672. "Jump to the next block.
  17673. With a prefix argument ARG, jump forward ARG many blocks.
  17674. When BACKWARD is non-nil, jump to the previous block.
  17675. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17676. Match data is set according to this regexp when the function
  17677. returns.
  17678. Return point at beginning of the opening line of found block.
  17679. Throw an error if no block is found."
  17680. (interactive "p")
  17681. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17682. (case-fold-search t)
  17683. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17684. (count (or arg 1))
  17685. (origin (point))
  17686. last-element)
  17687. (if backward (beginning-of-line) (end-of-line))
  17688. (while (and (> count 0) (funcall search-fn re nil t))
  17689. (let ((element (save-excursion
  17690. (goto-char (match-beginning 0))
  17691. (save-match-data (org-element-at-point)))))
  17692. (when (and (memq (org-element-type element)
  17693. '(center-block comment-block dynamic-block
  17694. example-block export-block quote-block
  17695. special-block src-block verse-block))
  17696. (<= (match-beginning 0)
  17697. (org-element-property :post-affiliated element)))
  17698. (setq last-element element)
  17699. (cl-decf count))))
  17700. (if (= count 0)
  17701. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17702. (save-match-data (org-fold-show-context)))
  17703. (goto-char origin)
  17704. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17705. (defun org-previous-block (arg &optional block-regexp)
  17706. "Jump to the previous block.
  17707. With a prefix argument ARG, jump backward ARG many source blocks.
  17708. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17709. (interactive "p")
  17710. (org-next-block arg t block-regexp))
  17711. ;;; Comments
  17712. ;; Org comments syntax is quite complex. It requires the entire line
  17713. ;; to be just a comment. Also, even with the right syntax at the
  17714. ;; beginning of line, some elements (e.g., verse-block or
  17715. ;; example-block) don't accept comments. Usual Emacs comment commands
  17716. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17717. ;; Org still relies on 'comment-dwim', but cannot trust
  17718. ;; 'comment-only-p'. So, 'comment-region-function' and
  17719. ;; 'uncomment-region-function' both point
  17720. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17721. ;; 'org-insert-comment' takes care of insertion of comments at the
  17722. ;; beginning of line.
  17723. ;; 'org-setup-comments-handling' install comments related variables
  17724. ;; during 'org-mode' initialization.
  17725. (defun org-setup-comments-handling ()
  17726. (interactive)
  17727. (setq-local comment-use-syntax nil)
  17728. (setq-local comment-start "# ")
  17729. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17730. (setq-local comment-insert-comment-function 'org-insert-comment)
  17731. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17732. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17733. (defun org-insert-comment ()
  17734. "Insert an empty comment above current line.
  17735. If the line is empty, insert comment at its beginning. When
  17736. point is within a source block, comment according to the related
  17737. major mode."
  17738. (if (let ((element (org-element-at-point)))
  17739. (and (eq (org-element-type element) 'src-block)
  17740. (< (save-excursion
  17741. (goto-char (org-element-property :post-affiliated element))
  17742. (line-end-position))
  17743. (point))
  17744. (> (save-excursion
  17745. (goto-char (org-element-property :end element))
  17746. (skip-chars-backward " \r\t\n")
  17747. (line-beginning-position))
  17748. (point))))
  17749. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17750. (beginning-of-line)
  17751. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17752. (open-line 1))
  17753. (org-indent-line)
  17754. (insert "# ")))
  17755. (defvar comment-empty-lines) ; From newcomment.el.
  17756. (defun org-comment-or-uncomment-region (beg end &rest _)
  17757. "Comment or uncomment each non-blank line in the region.
  17758. Uncomment each non-blank line between BEG and END if it only
  17759. contains commented lines. Otherwise, comment them. If region is
  17760. strictly within a source block, use appropriate comment syntax."
  17761. (if (let ((element (org-element-at-point)))
  17762. (and (eq (org-element-type element) 'src-block)
  17763. (< (save-excursion
  17764. (goto-char (org-element-property :post-affiliated element))
  17765. (line-end-position))
  17766. beg)
  17767. (>= (save-excursion
  17768. (goto-char (org-element-property :end element))
  17769. (skip-chars-backward " \r\t\n")
  17770. (line-beginning-position))
  17771. end)))
  17772. ;; Translate region boundaries for the Org buffer to the source
  17773. ;; buffer.
  17774. (let ((offset (- end beg)))
  17775. (save-excursion
  17776. (goto-char beg)
  17777. (org-babel-do-in-edit-buffer
  17778. (comment-or-uncomment-region (point) (+ offset (point))))))
  17779. (save-restriction
  17780. ;; Restrict region
  17781. (narrow-to-region (save-excursion (goto-char beg)
  17782. (skip-chars-forward " \r\t\n" end)
  17783. (line-beginning-position))
  17784. (save-excursion (goto-char end)
  17785. (skip-chars-backward " \r\t\n" beg)
  17786. (line-end-position)))
  17787. (let ((uncommentp
  17788. ;; UNCOMMENTP is non-nil when every non blank line between
  17789. ;; BEG and END is a comment.
  17790. (save-excursion
  17791. (goto-char (point-min))
  17792. (while (and (not (eobp))
  17793. (let ((element (org-element-at-point)))
  17794. (and (eq (org-element-type element) 'comment)
  17795. (goto-char (min (point-max)
  17796. (org-element-property
  17797. :end element)))))))
  17798. (eobp))))
  17799. (if uncommentp
  17800. ;; Only blank lines and comments in region: uncomment it.
  17801. (save-excursion
  17802. (goto-char (point-min))
  17803. (while (not (eobp))
  17804. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17805. (replace-match "" nil nil nil 1))
  17806. (forward-line)))
  17807. ;; Comment each line in region.
  17808. (let ((min-indent (point-max)))
  17809. ;; First find the minimum indentation across all lines.
  17810. (save-excursion
  17811. (goto-char (point-min))
  17812. (while (and (not (eobp)) (not (zerop min-indent)))
  17813. (unless (looking-at "[ \t]*$")
  17814. (setq min-indent (min min-indent (current-indentation))))
  17815. (forward-line)))
  17816. ;; Then loop over all lines.
  17817. (save-excursion
  17818. (goto-char (point-min))
  17819. (while (not (eobp))
  17820. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17821. ;; Don't get fooled by invisible text (e.g. link path)
  17822. ;; when moving to column MIN-INDENT.
  17823. (let ((buffer-invisibility-spec nil))
  17824. (org-move-to-column min-indent t))
  17825. (insert comment-start))
  17826. (forward-line)))))))))
  17827. (defun org-comment-dwim (_arg)
  17828. "Call the comment command you mean.
  17829. Call `org-toggle-comment' if on a heading, otherwise call
  17830. `comment-dwim', within a source edit buffer if needed."
  17831. (interactive "*P")
  17832. (cond ((org-at-heading-p)
  17833. (call-interactively #'org-toggle-comment))
  17834. ((org-in-src-block-p)
  17835. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17836. (t (call-interactively #'comment-dwim))))
  17837. ;;; Timestamps API
  17838. ;; This section contains tools to operate on, or create, timestamp
  17839. ;; objects, as returned by, e.g. `org-element-context'.
  17840. (defun org-timestamp-from-string (s)
  17841. "Convert Org timestamp S, as a string, into a timestamp object.
  17842. Return nil if S is not a valid timestamp string."
  17843. (when (org-string-nw-p s)
  17844. (with-temp-buffer
  17845. (save-excursion (insert s))
  17846. (org-element-timestamp-parser))))
  17847. (defun org-timestamp-from-time (time &optional with-time inactive)
  17848. "Convert a time value into a timestamp object.
  17849. TIME is an Emacs internal time representation, as returned, e.g.,
  17850. by `current-time'.
  17851. When optional argument WITH-TIME is non-nil, return a timestamp
  17852. object with a time part, i.e., with hours and minutes.
  17853. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17854. return an active timestamp."
  17855. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17856. (org-element-create 'timestamp
  17857. (list :type (if inactive 'inactive 'active)
  17858. :year-start year
  17859. :month-start month
  17860. :day-start day
  17861. :hour-start (and with-time hour)
  17862. :minute-start (and with-time minute)))))
  17863. (defun org-timestamp-to-time (timestamp &optional end)
  17864. "Convert TIMESTAMP object into an Emacs internal time value.
  17865. Use end of date range or time range when END is non-nil.
  17866. Otherwise, use its start."
  17867. (org-encode-time
  17868. (append '(0)
  17869. (mapcar
  17870. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17871. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17872. '(:minute-start :hour-start :day-start :month-start
  17873. :year-start)))
  17874. '(nil -1 nil))))
  17875. (defun org-timestamp-has-time-p (timestamp)
  17876. "Non-nil when TIMESTAMP has a time specified."
  17877. (org-element-property :hour-start timestamp))
  17878. (defun org-timestamp-format (timestamp format &optional end utc)
  17879. "Format a TIMESTAMP object into a string.
  17880. FORMAT is a format specifier to be passed to
  17881. `format-time-string'.
  17882. When optional argument END is non-nil, use end of date-range or
  17883. time-range, if possible.
  17884. When optional argument UTC is non-nil, time is be expressed as
  17885. Universal Time."
  17886. (format-time-string format (org-timestamp-to-time timestamp end)
  17887. (and utc t)))
  17888. (defun org-timestamp-split-range (timestamp &optional end)
  17889. "Extract a TIMESTAMP object from a date or time range.
  17890. END, when non-nil, means extract the end of the range.
  17891. Otherwise, extract its start.
  17892. Return a new timestamp object."
  17893. (let ((type (org-element-property :type timestamp)))
  17894. (if (memq type '(active inactive diary)) timestamp
  17895. (let ((split-ts (org-element-copy timestamp)))
  17896. ;; Set new type.
  17897. (org-element-put-property
  17898. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17899. ;; Copy start properties over end properties if END is
  17900. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17901. (let ((p-alist '((:minute-start . :minute-end)
  17902. (:hour-start . :hour-end)
  17903. (:day-start . :day-end)
  17904. (:month-start . :month-end)
  17905. (:year-start . :year-end))))
  17906. (dolist (p-cell p-alist)
  17907. (org-element-put-property
  17908. split-ts
  17909. (funcall (if end #'car #'cdr) p-cell)
  17910. (org-element-property
  17911. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17912. ;; Eventually refresh `:raw-value'.
  17913. (org-element-put-property split-ts :raw-value nil)
  17914. (org-element-put-property
  17915. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17916. (defun org-timestamp-translate (timestamp &optional boundary)
  17917. "Translate TIMESTAMP object to custom format.
  17918. Format string is defined in `org-time-stamp-custom-formats',
  17919. which see.
  17920. When optional argument BOUNDARY is non-nil, it is either the
  17921. symbol `start' or `end'. In this case, only translate the
  17922. starting or ending part of TIMESTAMP if it is a date or time
  17923. range. Otherwise, translate both parts.
  17924. Return timestamp as-is if `org-display-custom-times' is nil or if
  17925. it has a `diary' type."
  17926. (let ((type (org-element-property :type timestamp)))
  17927. (if (or (not org-display-custom-times) (eq type 'diary))
  17928. (org-element-interpret-data timestamp)
  17929. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17930. org-time-stamp-custom-formats)))
  17931. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17932. (concat (org-timestamp-format timestamp fmt)
  17933. "--"
  17934. (org-timestamp-format timestamp fmt t))
  17935. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17936. ;;; Other stuff
  17937. (defvar reftex-docstruct-symbol)
  17938. (defvar org--rds)
  17939. (defun org-reftex-citation ()
  17940. "Use `reftex-citation' to insert a citation into the buffer.
  17941. This looks for a line like
  17942. #+BIBLIOGRAPHY: foo plain option:-d
  17943. and derives from it that foo.bib is the bibliography file relevant
  17944. for this document. It then installs the necessary environment for RefTeX
  17945. to work in this buffer and calls `reftex-citation' to insert a citation
  17946. into the buffer.
  17947. Export of such citations to both LaTeX and HTML is handled by the contributed
  17948. package ox-bibtex by Taru Karttunen."
  17949. (interactive)
  17950. (let ((reftex-docstruct-symbol 'org--rds)
  17951. org--rds bib)
  17952. (org-with-wide-buffer
  17953. (let ((case-fold-search t)
  17954. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17955. (if (not (save-excursion
  17956. (or (re-search-forward re nil t)
  17957. (re-search-backward re nil t))))
  17958. (user-error "No bibliography defined in file")
  17959. (setq bib (concat (match-string 1) ".bib")
  17960. org--rds (list (list 'bib bib))))))
  17961. (call-interactively 'reftex-citation)))
  17962. ;;;; Functions extending outline functionality
  17963. (defun org-beginning-of-line (&optional n)
  17964. "Go to the beginning of the current visible line.
  17965. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17966. symbol `reversed', on the first attempt move to where the
  17967. headline text starts, and only move to beginning of line when the
  17968. cursor is already before the start of the text of the headline.
  17969. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17970. start of the text on the second attempt.
  17971. With argument N not nil or 1, move forward N - 1 lines first."
  17972. (interactive "^p")
  17973. (let ((origin (point))
  17974. (special (pcase org-special-ctrl-a/e
  17975. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17976. deactivate-mark)
  17977. ;; First move to a visible line.
  17978. (if (bound-and-true-p visual-line-mode)
  17979. (beginning-of-visual-line n)
  17980. (move-beginning-of-line n)
  17981. ;; `move-beginning-of-line' may leave point after invisible
  17982. ;; characters if line starts with such of these (e.g., with
  17983. ;; a link at column 0). Really move to the beginning of the
  17984. ;; current visible line.
  17985. (beginning-of-line))
  17986. (cond
  17987. ;; No special behavior. Point is already at the beginning of
  17988. ;; a line, logical or visual.
  17989. ((not special))
  17990. ;; `beginning-of-visual-line' left point before logical beginning
  17991. ;; of line: point is at the beginning of a visual line. Bail
  17992. ;; out.
  17993. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17994. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17995. ;; At a headline, special position is before the title, but
  17996. ;; after any TODO keyword or priority cookie.
  17997. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17998. (line-end-position)))
  17999. (bol (point)))
  18000. (if (eq special 'reversed)
  18001. (when (and (= origin bol) (eq last-command this-command))
  18002. (goto-char refpos))
  18003. (when (or (> origin refpos) (= origin bol))
  18004. (goto-char refpos)))))
  18005. ((and (looking-at org-list-full-item-re)
  18006. (memq (org-element-type (save-match-data (org-element-at-point)))
  18007. '(item plain-list)))
  18008. ;; Set special position at first white space character after
  18009. ;; bullet, and check-box, if any.
  18010. (let ((after-bullet
  18011. (let ((box (match-end 3)))
  18012. (cond ((not box) (match-end 1))
  18013. ((eq (char-after box) ?\s) (1+ box))
  18014. (t box)))))
  18015. (if (eq special 'reversed)
  18016. (when (and (= (point) origin) (eq last-command this-command))
  18017. (goto-char after-bullet))
  18018. (when (or (> origin after-bullet) (= (point) origin))
  18019. (goto-char after-bullet)))))
  18020. ;; No special context. Point is already at beginning of line.
  18021. (t nil))))
  18022. (defun org-end-of-line (&optional n)
  18023. "Go to the end of the line, but before ellipsis, if any.
  18024. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18025. symbol `reversed', ignore tags on the first attempt, and only
  18026. move to after the tags when the cursor is already beyond the end
  18027. of the headline.
  18028. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18029. on the second attempt.
  18030. With argument N not nil or 1, move forward N - 1 lines first."
  18031. (interactive "^p")
  18032. (let ((origin (point))
  18033. (special (pcase org-special-ctrl-a/e
  18034. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18035. deactivate-mark)
  18036. ;; First move to a visible line.
  18037. (if (bound-and-true-p visual-line-mode)
  18038. (beginning-of-visual-line n)
  18039. (move-beginning-of-line n))
  18040. (cond
  18041. ;; At a headline, with tags.
  18042. ((and special
  18043. (save-excursion
  18044. (beginning-of-line)
  18045. (let ((case-fold-search nil))
  18046. (looking-at org-complex-heading-regexp)))
  18047. (match-end 5))
  18048. (let ((tags (save-excursion
  18049. (goto-char (match-beginning 5))
  18050. (skip-chars-backward " \t")
  18051. (point)))
  18052. (visual-end (and (bound-and-true-p visual-line-mode)
  18053. (save-excursion
  18054. (end-of-visual-line)
  18055. (point)))))
  18056. ;; If `end-of-visual-line' brings us before end of line or
  18057. ;; even tags, i.e., the headline spans over multiple visual
  18058. ;; lines, move there.
  18059. (cond ((and visual-end
  18060. (< visual-end tags)
  18061. (<= origin visual-end))
  18062. (goto-char visual-end))
  18063. ((eq special 'reversed)
  18064. (if (and (= origin (line-end-position))
  18065. (eq this-command last-command))
  18066. (goto-char tags)
  18067. (end-of-line)))
  18068. (t
  18069. (if (or (< origin tags) (= origin (line-end-position)))
  18070. (goto-char tags)
  18071. (end-of-line))))))
  18072. ((bound-and-true-p visual-line-mode)
  18073. (let ((bol (line-beginning-position)))
  18074. (end-of-visual-line)
  18075. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18076. ;; end of a line, backtrack and use `end-of-line' instead.
  18077. (when (/= bol (line-beginning-position))
  18078. (goto-char bol)
  18079. (end-of-line))))
  18080. (t (end-of-line)))))
  18081. (defun org-backward-sentence (&optional _arg)
  18082. "Go to beginning of sentence, or beginning of table field.
  18083. This will call `backward-sentence' or `org-table-beginning-of-field',
  18084. depending on context."
  18085. (interactive)
  18086. (let* ((element (org-element-at-point))
  18087. (contents-begin (org-element-property :contents-begin element))
  18088. (table (org-element-lineage element '(table) t)))
  18089. (if (and table
  18090. (> (point) contents-begin)
  18091. (<= (point) (org-element-property :contents-end table)))
  18092. (call-interactively #'org-table-beginning-of-field)
  18093. (save-restriction
  18094. (when (and contents-begin
  18095. (< (point-min) contents-begin)
  18096. (> (point) contents-begin))
  18097. (narrow-to-region contents-begin
  18098. (org-element-property :contents-end element)))
  18099. (call-interactively #'backward-sentence)))))
  18100. (defun org-forward-sentence (&optional _arg)
  18101. "Go to end of sentence, or end of table field.
  18102. This will call `forward-sentence' or `org-table-end-of-field',
  18103. depending on context."
  18104. (interactive)
  18105. (if (and (org-at-heading-p)
  18106. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18107. (save-restriction
  18108. (narrow-to-region (line-beginning-position) (line-end-position))
  18109. (call-interactively #'forward-sentence))
  18110. (let* ((element (org-element-at-point))
  18111. (contents-end (org-element-property :contents-end element))
  18112. (table (org-element-lineage element '(table) t)))
  18113. (if (and table
  18114. (>= (point) (org-element-property :contents-begin table))
  18115. (< (point) contents-end))
  18116. (call-interactively #'org-table-end-of-field)
  18117. (save-restriction
  18118. (when (and contents-end
  18119. (> (point-max) contents-end)
  18120. ;; Skip blank lines between elements.
  18121. (< (org-element-property :end element)
  18122. (save-excursion (goto-char contents-end)
  18123. (skip-chars-forward " \r\t\n"))))
  18124. (narrow-to-region (org-element-property :contents-begin element)
  18125. contents-end))
  18126. ;; End of heading is considered as the end of a sentence.
  18127. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18128. (call-interactively #'forward-sentence)))))))
  18129. (defun org-kill-line (&optional _arg)
  18130. "Kill line, to tags or end of line."
  18131. (interactive)
  18132. (cond
  18133. ((or (not org-special-ctrl-k)
  18134. (bolp)
  18135. (not (org-at-heading-p)))
  18136. (when (and (org-invisible-p (line-end-position))
  18137. org-ctrl-k-protect-subtree
  18138. (or (eq org-ctrl-k-protect-subtree 'error)
  18139. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18140. (user-error
  18141. (substitute-command-keys
  18142. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18143. (call-interactively
  18144. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18145. ((org-match-line org-tag-line-re)
  18146. (let ((end (save-excursion
  18147. (goto-char (match-beginning 1))
  18148. (skip-chars-backward " \t")
  18149. (point))))
  18150. (if (<= end (point)) ;on tags part
  18151. (kill-region (point) (line-end-position))
  18152. (kill-region (point) end)))
  18153. ;; Only align tags when we are still on a heading:
  18154. (if (org-at-heading-p) (org-align-tags)))
  18155. (t (kill-region (point) (line-end-position)))))
  18156. (defun org-yank (&optional arg)
  18157. "Yank. If the kill is a subtree, treat it specially.
  18158. This command will look at the current kill and check if is a single
  18159. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18160. cursor is at the beginning of a line or after the stars of a currently
  18161. empty headline, then the yank is handled specially. How exactly depends
  18162. on the value of the following variables.
  18163. `org-yank-folded-subtrees'
  18164. By default, this variable is non-nil, which results in
  18165. subtree(s) being folded after insertion, except if doing so
  18166. would swallow text after the yanked text.
  18167. `org-yank-adjusted-subtrees'
  18168. When non-nil (the default value is nil), the subtree will be
  18169. promoted or demoted in order to fit into the local outline tree
  18170. structure, which means that the level will be adjusted so that it
  18171. becomes the smaller one of the two *visible* surrounding headings.
  18172. Any prefix to this command will cause `yank' to be called directly with
  18173. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18174. will just
  18175. plainly yank the text as it is.
  18176. \[1] The test checks if the first non-white line is a heading
  18177. and if there are no other headings with fewer stars."
  18178. (interactive "P")
  18179. (org-yank-generic 'yank arg))
  18180. (defun org-yank-generic (command arg)
  18181. "Perform some yank-like command.
  18182. This function implements the behavior described in the `org-yank'
  18183. documentation. However, it has been generalized to work for any
  18184. interactive command with similar behavior."
  18185. ;; pretend to be command COMMAND
  18186. (setq this-command command)
  18187. (if arg
  18188. (call-interactively command)
  18189. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18190. (and (org-kill-is-subtree-p)
  18191. (or (bolp)
  18192. (and (looking-at "[ \t]*$")
  18193. (string-match
  18194. "\\`\\*+\\'"
  18195. (buffer-substring (point-at-bol) (point)))))))
  18196. swallowp)
  18197. (cond
  18198. ((and subtreep org-yank-folded-subtrees)
  18199. (let ((beg (point))
  18200. end)
  18201. (if (and subtreep org-yank-adjusted-subtrees)
  18202. (org-paste-subtree nil nil 'for-yank)
  18203. (call-interactively command))
  18204. (setq end (point))
  18205. (goto-char beg)
  18206. (when (and (bolp) subtreep
  18207. (not (setq swallowp
  18208. (org-yank-folding-would-swallow-text beg end))))
  18209. (org-with-limited-levels
  18210. (or (looking-at org-outline-regexp)
  18211. (re-search-forward org-outline-regexp-bol end t))
  18212. (while (and (< (point) end) (looking-at org-outline-regexp))
  18213. (org-fold-subtree t)
  18214. (org-cycle-show-empty-lines 'folded)
  18215. (condition-case nil
  18216. (outline-forward-same-level 1)
  18217. (error (goto-char end))))))
  18218. (when swallowp
  18219. (message
  18220. "Inserted text not folded because that would swallow text"))
  18221. (goto-char end)
  18222. (skip-chars-forward " \t\n\r")
  18223. (beginning-of-line 1)
  18224. (push-mark beg 'nomsg)))
  18225. ((and subtreep org-yank-adjusted-subtrees)
  18226. (let ((beg (point-at-bol)))
  18227. (org-paste-subtree nil nil 'for-yank)
  18228. (push-mark beg 'nomsg)))
  18229. (t
  18230. (call-interactively command))))))
  18231. (defun org-yank-folding-would-swallow-text (beg end)
  18232. "Would `hide-subtree' at BEG swallow any text after END?"
  18233. (let (level)
  18234. (org-with-limited-levels
  18235. (save-excursion
  18236. (goto-char beg)
  18237. (when (or (looking-at org-outline-regexp)
  18238. (re-search-forward org-outline-regexp-bol end t))
  18239. (setq level (org-outline-level)))
  18240. (goto-char end)
  18241. (skip-chars-forward " \t\r\n\v\f")
  18242. (not (or (eobp)
  18243. (and (bolp) (looking-at-p org-outline-regexp)
  18244. (<= (org-outline-level) level))))))))
  18245. (defun org-back-to-heading (&optional invisible-ok)
  18246. "Go back to beginning of heading."
  18247. (beginning-of-line)
  18248. (or (org-at-heading-p (not invisible-ok))
  18249. (let (found)
  18250. (save-excursion
  18251. ;; At inlinetask end. Move to bol, so that the following
  18252. ;; search goes to the beginning of the inlinetask.
  18253. (when (and (featurep 'org-inlinetask)
  18254. (fboundp 'org-inlinetask-end-p)
  18255. (org-inlinetask-end-p))
  18256. (goto-char (line-beginning-position)))
  18257. (while (not found)
  18258. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18259. nil t)
  18260. (user-error "Before first headline at position %d in buffer %s"
  18261. (point) (current-buffer)))
  18262. ;; Skip inlinetask end.
  18263. (if (and (featurep 'org-inlinetask)
  18264. (fboundp 'org-inlinetask-end-p)
  18265. (org-inlinetask-end-p))
  18266. (org-inlinetask-goto-beginning)
  18267. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18268. (point))))))
  18269. (goto-char found)
  18270. found)))
  18271. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18272. "Go back to heading or first point in buffer.
  18273. If point is before first heading go to first point in buffer
  18274. instead of back to heading."
  18275. (if (org-before-first-heading-p)
  18276. (goto-char (point-min))
  18277. (org-back-to-heading invisible-ok)))
  18278. (defun org-before-first-heading-p ()
  18279. "Before first heading?
  18280. Respect narrowing."
  18281. (let ((cached (org-element-at-point nil 'cached)))
  18282. (if cached
  18283. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18284. (or (not cached-headline)
  18285. (< (org-element-property :begin cached-headline) (point-min))))
  18286. (org-with-limited-levels
  18287. (save-excursion
  18288. (end-of-line)
  18289. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18290. (defun org-at-heading-p (&optional invisible-not-ok)
  18291. "Return t if point is on a (possibly invisible) heading line.
  18292. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18293. (save-excursion
  18294. (beginning-of-line)
  18295. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18296. (looking-at outline-regexp))))
  18297. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18298. "Non-nil if point is under a commented heading.
  18299. This function also checks ancestors of the current headline,
  18300. unless optional argument NO-INHERITANCE is non-nil.
  18301. Optional argument ELEMENT contains element at point."
  18302. (save-match-data
  18303. (let ((el (or element
  18304. (org-element-at-point nil 'cached)
  18305. (org-with-wide-buffer
  18306. (org-back-to-heading-or-point-min t)
  18307. (org-element-at-point)))))
  18308. (catch :found
  18309. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18310. (if no-inheritance
  18311. (org-element-property :commentedp el)
  18312. (while el
  18313. (when (org-element-property :commentedp el)
  18314. (throw :found t))
  18315. (setq el (org-element-property :parent el))))))))
  18316. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18317. "Non-nil if point is under an archived heading.
  18318. This function also checks ancestors of the current headline,
  18319. unless optional argument NO-INHERITANCE is non-nil.
  18320. Optional argument ELEMENT contains element at point."
  18321. (cond
  18322. ((and (not element) (org-before-first-heading-p)) nil)
  18323. ((if element
  18324. (org-element-property :archivedp element)
  18325. (let ((tags (org-get-tags element 'local)))
  18326. (and tags
  18327. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18328. (no-inheritance nil)
  18329. (t
  18330. (if (org-element--cache-active-p)
  18331. (cl-some (lambda (el) (org-element-property :archivedp el))
  18332. (org-element-lineage (or element (org-element-at-point)) nil t))
  18333. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18334. (defun org-at-comment-p nil
  18335. "Return t if cursor is in a commented line."
  18336. (save-excursion
  18337. (save-match-data
  18338. (beginning-of-line)
  18339. (looking-at org-comment-regexp))))
  18340. (defun org-at-keyword-p nil
  18341. "Return t if cursor is at a keyword-line."
  18342. (save-excursion
  18343. (move-beginning-of-line 1)
  18344. (looking-at org-keyword-regexp)))
  18345. (defun org-at-drawer-p nil
  18346. "Return t if cursor is at a drawer keyword."
  18347. (save-excursion
  18348. (move-beginning-of-line 1)
  18349. (looking-at org-drawer-regexp)))
  18350. (defun org-at-block-p nil
  18351. "Return t if cursor is at a block keyword."
  18352. (save-excursion
  18353. (move-beginning-of-line 1)
  18354. (looking-at org-block-regexp)))
  18355. (defun org-point-at-end-of-empty-headline ()
  18356. "If point is at the end of an empty headline, return t, else nil.
  18357. If the heading only contains a TODO keyword, it is still considered
  18358. empty."
  18359. (let ((case-fold-search nil))
  18360. (and (looking-at "[ \t]*$")
  18361. org-todo-line-regexp
  18362. (save-excursion
  18363. (beginning-of-line)
  18364. (looking-at org-todo-line-regexp)
  18365. (string= (match-string 3) "")))))
  18366. (defun org-at-heading-or-item-p ()
  18367. (or (org-at-heading-p) (org-at-item-p)))
  18368. (defun org-up-heading-all (arg)
  18369. "Move to the heading line of which the present line is a subheading.
  18370. This function considers both visible and invisible heading lines.
  18371. With argument, move up ARG levels."
  18372. (outline-up-heading arg t))
  18373. (defvar-local org--up-heading-cache nil
  18374. "Buffer-local `org-up-heading-safe' cache.")
  18375. (defvar-local org--up-heading-cache-tick nil
  18376. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18377. (defun org-up-heading-safe ()
  18378. "Move to the heading line of which the present line is a subheading.
  18379. This version will not throw an error. It will return the level of the
  18380. headline found, or nil if no higher level is found.
  18381. Also, this function will be a lot faster than `outline-up-heading',
  18382. because it relies on stars being the outline starters. This can really
  18383. make a significant difference in outlines with very many siblings."
  18384. (let ((element (and (org-element--cache-active-p)
  18385. (org-element-at-point nil t))))
  18386. (if element
  18387. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  18388. (parent (org-element-lineage current-heading '(headline))))
  18389. (if (and parent
  18390. (<= (point-min) (org-element-property :begin parent)))
  18391. (progn
  18392. (goto-char (org-element-property :begin parent))
  18393. (org-element-property :level parent))
  18394. (when (and current-heading
  18395. (<= (point-min) (org-element-property :begin current-heading)))
  18396. (goto-char (org-element-property :begin current-heading))
  18397. nil)))
  18398. (when (ignore-errors (org-back-to-heading t))
  18399. (let (level-cache)
  18400. (unless org--up-heading-cache
  18401. (setq org--up-heading-cache (make-hash-table)))
  18402. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18403. (setq level-cache (gethash (point) org--up-heading-cache)))
  18404. (when (<= (point-min) (car level-cache) (point-max))
  18405. ;; Parent is inside accessible part of the buffer.
  18406. (progn (goto-char (car level-cache))
  18407. (cdr level-cache)))
  18408. ;; Buffer modified. Invalidate cache.
  18409. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18410. (setq-local org--up-heading-cache-tick
  18411. (buffer-chars-modified-tick))
  18412. (clrhash org--up-heading-cache))
  18413. (let* ((level-up (1- (funcall outline-level)))
  18414. (pos (point))
  18415. (result (and (> level-up 0)
  18416. (re-search-backward
  18417. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18418. (funcall outline-level))))
  18419. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18420. result)))))))
  18421. (defun org-up-heading-or-point-min ()
  18422. "Move to the heading line of which the present is a subheading, or point-min.
  18423. This version is needed to make point-min behave like a virtual
  18424. heading of level 0 for property-inheritance. It will return the
  18425. level of the headline found (down to 0) or nil if already at a
  18426. point before the first headline or at point-min."
  18427. (when (ignore-errors (org-back-to-heading t))
  18428. (if (< 1 (funcall outline-level))
  18429. (or (org-up-heading-safe)
  18430. ;; The first heading may not be level 1 heading.
  18431. (goto-char (point-min)))
  18432. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18433. (defun org-first-sibling-p ()
  18434. "Is this heading the first child of its parents?"
  18435. (interactive)
  18436. (let ((re org-outline-regexp-bol)
  18437. level l)
  18438. (unless (org-at-heading-p t)
  18439. (user-error "Not at a heading"))
  18440. (setq level (funcall outline-level))
  18441. (save-excursion
  18442. (if (not (re-search-backward re nil t))
  18443. t
  18444. (setq l (funcall outline-level))
  18445. (< l level)))))
  18446. (defun org-goto-sibling (&optional previous)
  18447. "Goto the next sibling, even if it is invisible.
  18448. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18449. when a sibling was found. When none is found, return nil and don't
  18450. move point."
  18451. (let ((fun (if previous 're-search-backward 're-search-forward))
  18452. (pos (point))
  18453. (re org-outline-regexp-bol)
  18454. level l)
  18455. (when (ignore-errors (org-back-to-heading t))
  18456. (setq level (funcall outline-level))
  18457. (catch 'exit
  18458. (or previous (forward-char 1))
  18459. (while (funcall fun re nil t)
  18460. (setq l (funcall outline-level))
  18461. (when (< l level) (goto-char pos) (throw 'exit nil))
  18462. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18463. (goto-char pos)
  18464. nil))))
  18465. (defun org-goto-first-child (&optional element)
  18466. "Goto the first child, even if it is invisible.
  18467. Return t when a child was found. Otherwise don't move point and
  18468. return nil."
  18469. (if (org-element--cache-active-p)
  18470. (let ((heading (org-element-lineage
  18471. (or element (org-element-at-point))
  18472. '(headline inlinetask org-data)
  18473. t)))
  18474. (when heading
  18475. (unless (or (eq 'inlinetask (org-element-type heading))
  18476. (not (org-element-property :contents-begin heading)))
  18477. (let ((pos (point)))
  18478. (goto-char (org-element-property :contents-begin heading))
  18479. (if (re-search-forward
  18480. org-outline-regexp-bol
  18481. (org-element-property :end heading)
  18482. t)
  18483. (progn (goto-char (match-beginning 0)) t)
  18484. (goto-char pos) nil)))))
  18485. (let (level (pos (point)) (re org-outline-regexp-bol))
  18486. (when (org-back-to-heading-or-point-min t)
  18487. (setq level (org-outline-level))
  18488. (forward-char 1)
  18489. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18490. (progn (goto-char (match-beginning 0)) t)
  18491. (goto-char pos) nil)))))
  18492. (defun org-get-next-sibling ()
  18493. "Move to next heading of the same level, and return point.
  18494. If there is no such heading, return nil.
  18495. This is like outline-next-sibling, but invisible headings are ok."
  18496. (let ((level (funcall outline-level)))
  18497. (outline-next-heading)
  18498. (while (and (not (eobp)) (> (funcall outline-level) level))
  18499. (outline-next-heading))
  18500. (unless (or (eobp) (< (funcall outline-level) level))
  18501. (point))))
  18502. (defun org-get-previous-sibling ()
  18503. "Move to previous heading of the same level, and return point.
  18504. If there is no such heading, return nil."
  18505. (let ((opoint (point))
  18506. (level (funcall outline-level)))
  18507. (outline-previous-heading)
  18508. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18509. (while (and (> (funcall outline-level) level)
  18510. (not (bobp)))
  18511. (outline-previous-heading))
  18512. (unless (< (funcall outline-level) level)
  18513. (point)))))
  18514. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18515. "Goto to the end of a subtree at point or for ELEMENT heading."
  18516. ;; This contains an exact copy of the original function, but it uses
  18517. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18518. ;; trees and before first headline. And is uses an invisible-ok argument.
  18519. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18520. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18521. ;; with many children and grandchildren etc, this can be much faster
  18522. ;; than the outline version.
  18523. (org-back-to-heading-or-point-min invisible-ok)
  18524. (unless (and (org-element--cache-active-p)
  18525. (let ((cached (or element (org-element-at-point nil t))))
  18526. (and cached
  18527. (eq 'headline (org-element-type cached))
  18528. (goto-char (org-element-property
  18529. :end cached)))))
  18530. (let ((first t)
  18531. (level (funcall outline-level)))
  18532. (cond ((= level 0)
  18533. (goto-char (point-max)))
  18534. ((and (derived-mode-p 'org-mode) (< level 1000))
  18535. ;; A true heading (not a plain list item), in Org
  18536. ;; This means we can easily find the end by looking
  18537. ;; only for the right number of stars. Using a regexp to do
  18538. ;; this is so much faster than using a Lisp loop.
  18539. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18540. (forward-char 1)
  18541. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18542. (t
  18543. ;; something else, do it the slow way
  18544. (while (and (not (eobp))
  18545. (or first (> (funcall outline-level) level)))
  18546. (setq first nil)
  18547. (outline-next-heading))))))
  18548. (unless to-heading
  18549. (when (memq (preceding-char) '(?\n ?\^M))
  18550. ;; Go to end of line before heading
  18551. (forward-char -1)
  18552. (when (memq (preceding-char) '(?\n ?\^M))
  18553. ;; leave blank line before heading
  18554. (forward-char -1))))
  18555. (point))
  18556. (defun org-end-of-meta-data (&optional full)
  18557. "Skip planning line and properties drawer in current entry.
  18558. When optional argument FULL is t, also skip planning information,
  18559. clocking lines and any kind of drawer.
  18560. When FULL is non-nil but not t, skip planning information,
  18561. properties, clocking lines and logbook drawers."
  18562. (org-back-to-heading t)
  18563. (forward-line)
  18564. ;; Skip planning information.
  18565. (when (looking-at-p org-planning-line-re) (forward-line))
  18566. ;; Skip property drawer.
  18567. (when (looking-at org-property-drawer-re)
  18568. (goto-char (match-end 0))
  18569. (forward-line))
  18570. ;; When FULL is not nil, skip more.
  18571. (when (and full (not (org-at-heading-p)))
  18572. (catch 'exit
  18573. (let ((end (save-excursion (outline-next-heading) (point)))
  18574. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18575. (while (not (eobp))
  18576. (cond ;; Skip clock lines.
  18577. ((looking-at-p re) (forward-line))
  18578. ;; Skip logbook drawer.
  18579. ((looking-at-p org-logbook-drawer-re)
  18580. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18581. (forward-line)
  18582. (throw 'exit t)))
  18583. ;; When FULL is t, skip regular drawer too.
  18584. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18585. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18586. (forward-line)
  18587. (throw 'exit t)))
  18588. (t (throw 'exit t))))))))
  18589. (defun org--line-fully-invisible-p ()
  18590. "Return non-nil if the current line is fully invisible."
  18591. (let ((line-beg (line-beginning-position))
  18592. (line-pos (1- (line-end-position)))
  18593. (is-invisible t))
  18594. (while (and (< line-beg line-pos) is-invisible)
  18595. (setq is-invisible (org-invisible-p line-pos))
  18596. (setq line-pos (1- line-pos)))
  18597. is-invisible))
  18598. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18599. "Move forward to the ARG'th subheading at same level as this one.
  18600. Stop at the first and last subheadings of a superior heading.
  18601. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18602. non-nil it will also look at invisible ones."
  18603. (interactive "p")
  18604. (let ((backward? (and arg (< arg 0))))
  18605. (if (org-before-first-heading-p)
  18606. (if backward? (goto-char (point-min)) (outline-next-heading))
  18607. (org-back-to-heading invisible-ok)
  18608. (unless backward? (end-of-line)) ;do not match current headline
  18609. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18610. (f (if backward? #'re-search-backward #'re-search-forward))
  18611. (count (if arg (abs arg) 1))
  18612. (result (point)))
  18613. (while (and (> count 0)
  18614. (funcall f org-outline-regexp-bol nil 'move))
  18615. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18616. (cond ((< l level) (setq count 0))
  18617. ((and (= l level)
  18618. (or invisible-ok
  18619. ;; FIXME: See commit a700fadd72 and the
  18620. ;; related discussion on why using
  18621. ;; `org--line-fully-invisible-p' is needed
  18622. ;; here, which is to serve the needs of an
  18623. ;; external package. If the change is
  18624. ;; wrong regarding Org itself, it should
  18625. ;; be removed.
  18626. (not (org--line-fully-invisible-p))))
  18627. (cl-decf count)
  18628. (when (= l level) (setq result (point)))))))
  18629. (goto-char result))
  18630. (beginning-of-line))))
  18631. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18632. "Move backward to the ARG'th subheading at same level as this one.
  18633. Stop at the first and last subheadings of a superior heading."
  18634. (interactive "p")
  18635. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18636. (defun org-next-visible-heading--overlays (arg)
  18637. "Move to the next visible heading line.
  18638. With ARG, repeats or can move backward if negative."
  18639. (interactive "p")
  18640. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18641. (if (< arg 0)
  18642. (beginning-of-line)
  18643. (end-of-line))
  18644. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18645. (unless (bobp)
  18646. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18647. (`(outline . ,o)
  18648. (goto-char (overlay-start o))
  18649. (re-search-backward regexp nil :move))
  18650. (_ nil))))
  18651. (cl-incf arg))
  18652. (while (and (> arg 0) (re-search-forward regexp nil t))
  18653. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18654. (`(outline . ,o)
  18655. (goto-char (overlay-end o))
  18656. (re-search-forward regexp nil :move))
  18657. (_
  18658. (end-of-line)
  18659. nil))) ;leave the loop
  18660. (cl-decf arg))
  18661. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18662. (defun org-next-visible-heading--text-properties (arg)
  18663. "Move to the next visible heading line.
  18664. With ARG, repeats or can move backward if negative."
  18665. (interactive "p")
  18666. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18667. (if (< arg 0)
  18668. (beginning-of-line)
  18669. (end-of-line))
  18670. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18671. (unless (bobp)
  18672. (when (org-fold-folded-p)
  18673. (goto-char (org-fold-previous-visibility-change))
  18674. (unless (looking-at-p regexp)
  18675. (re-search-backward regexp nil :mode))))
  18676. (cl-incf arg))
  18677. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18678. (when (org-fold-folded-p)
  18679. (goto-char (org-fold-next-visibility-change))
  18680. (skip-chars-forward " \t\n")
  18681. (end-of-line))
  18682. (cl-decf arg))
  18683. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18684. (defun org-next-visible-heading (arg)
  18685. "Move to the next visible heading line.
  18686. With ARG, repeats or can move backward if negative."
  18687. (interactive "p")
  18688. (if (eq org-fold-core-style 'text-properties)
  18689. (org-next-visible-heading--text-properties arg)
  18690. (org-next-visible-heading--overlays arg)))
  18691. (defun org-previous-visible-heading (arg)
  18692. "Move to the previous visible heading.
  18693. With ARG, repeats or can move forward if negative."
  18694. (interactive "p")
  18695. (org-next-visible-heading (- arg)))
  18696. (defun org-forward-paragraph (&optional arg)
  18697. "Move forward by a paragraph, or equivalent, unit.
  18698. With argument ARG, do it ARG times;
  18699. a negative argument ARG = -N means move backward N paragraphs.
  18700. The function moves point between two structural
  18701. elements (paragraphs, tables, lists, etc.).
  18702. It also provides the following special moves for convenience:
  18703. - on a table or a property drawer, move to its beginning;
  18704. - on comment, example, export, source and verse blocks, stop
  18705. at blank lines;
  18706. - skip consecutive clocks, diary S-exps, and keywords."
  18707. (interactive "^p")
  18708. (unless arg (setq arg 1))
  18709. (if (< arg 0) (org-backward-paragraph (- arg))
  18710. (while (and (> arg 0) (not (eobp)))
  18711. (org--forward-paragraph-once)
  18712. (cl-decf arg))
  18713. ;; Return moves left.
  18714. arg))
  18715. (defun org-backward-paragraph (&optional arg)
  18716. "Move backward by a paragraph, or equivalent, unit.
  18717. With argument ARG, do it ARG times;
  18718. a negative argument ARG = -N means move forward N paragraphs.
  18719. The function moves point between two structural
  18720. elements (paragraphs, tables, lists, etc.).
  18721. It also provides the following special moves for convenience:
  18722. - on a table or a property drawer, move to its beginning;
  18723. - on comment, example, export, source and verse blocks, stop
  18724. at blank lines;
  18725. - skip consecutive clocks, diary S-exps, and keywords."
  18726. (interactive "^p")
  18727. (unless arg (setq arg 1))
  18728. (if (< arg 0) (org-forward-paragraph (- arg))
  18729. (while (and (> arg 0) (not (bobp)))
  18730. (org--backward-paragraph-once)
  18731. (cl-decf arg))
  18732. ;; Return moves left.
  18733. arg))
  18734. (defvar org--single-lines-list-is-paragraph t
  18735. "Treat plain lists with single line items as a whole paragraph")
  18736. (defun org--paragraph-at-point ()
  18737. "Return paragraph, or equivalent, element at point.
  18738. Paragraph element at point is the element at point, with the
  18739. following special cases:
  18740. - treat table rows (resp. node properties) as the table
  18741. \(resp. property drawer) containing them.
  18742. - treat plain lists with an item every line as a whole.
  18743. - treat consecutive keywords, clocks, and diary-sexps as a single
  18744. block.
  18745. Function may return a real element, or a pseudo-element with type
  18746. `pseudo-paragraph'."
  18747. (let* ((e (org-element-at-point))
  18748. (type (org-element-type e))
  18749. ;; If we need to fake a new pseudo-element, triplet is
  18750. ;;
  18751. ;; (BEG END PARENT)
  18752. ;;
  18753. ;; where BEG and END are element boundaries, and PARENT the
  18754. ;; element containing it, or nil.
  18755. (triplet
  18756. (cond
  18757. ((memq type '(table property-drawer))
  18758. (list (org-element-property :begin e)
  18759. (org-element-property :end e)
  18760. (org-element-property :parent e)))
  18761. ((memq type '(node-property table-row))
  18762. (let ((e (org-element-property :parent e)))
  18763. (list (org-element-property :begin e)
  18764. (org-element-property :end e)
  18765. (org-element-property :parent e))))
  18766. ((memq type '(clock diary-sexp keyword))
  18767. (let* ((regexp (pcase type
  18768. (`clock org-clock-line-re)
  18769. (`diary-sexp "%%(")
  18770. (_ org-keyword-regexp)))
  18771. (end (if (< 0 (org-element-property :post-blank e))
  18772. (org-element-property :end e)
  18773. (org-with-wide-buffer
  18774. (forward-line)
  18775. (while (looking-at regexp) (forward-line))
  18776. (skip-chars-forward " \t\n")
  18777. (line-beginning-position))))
  18778. (begin (org-with-point-at (org-element-property :begin e)
  18779. (while (and (not (bobp)) (looking-at regexp))
  18780. (forward-line -1))
  18781. ;; We may have gotten one line too far.
  18782. (if (looking-at regexp)
  18783. (point)
  18784. (line-beginning-position 2)))))
  18785. (list begin end (org-element-property :parent e))))
  18786. ;; Find the full plain list containing point, the check it
  18787. ;; contains exactly one line per item.
  18788. ((let ((l (org-element-lineage e '(plain-list) t)))
  18789. (while (memq (org-element-type (org-element-property :parent l))
  18790. '(item plain-list))
  18791. (setq l (org-element-property :parent l)))
  18792. (and l org--single-lines-list-is-paragraph
  18793. (org-with-point-at (org-element-property :post-affiliated l)
  18794. (forward-line (length (org-element-property :structure l)))
  18795. (= (point) (org-element-property :contents-end l)))
  18796. ;; Return value.
  18797. (list (org-element-property :begin l)
  18798. (org-element-property :end l)
  18799. (org-element-property :parent l)))))
  18800. (t nil)))) ;no triplet: return element
  18801. (pcase triplet
  18802. (`(,b ,e ,p)
  18803. (org-element-create
  18804. 'pseudo-paragraph
  18805. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18806. (_ e))))
  18807. (defun org--forward-paragraph-once--overlays ()
  18808. "Move forward to end of paragraph or equivalent, once.
  18809. See `org-forward-paragraph'."
  18810. (interactive)
  18811. (save-restriction
  18812. (widen)
  18813. (skip-chars-forward " \t\n")
  18814. (cond
  18815. ((eobp) nil)
  18816. ;; When inside a folded part, move out of it.
  18817. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18818. (`(,(or `outline `org-hide-block) . ,o)
  18819. (goto-char (overlay-end o))
  18820. (forward-line)
  18821. t)
  18822. (_ nil)))
  18823. (t
  18824. (let* ((element (org--paragraph-at-point))
  18825. (type (org-element-type element))
  18826. (contents-begin (org-element-property :contents-begin element))
  18827. (end (org-element-property :end element))
  18828. (post-affiliated (org-element-property :post-affiliated element)))
  18829. (cond
  18830. ((eq type 'plain-list)
  18831. (forward-char)
  18832. (org--forward-paragraph-once))
  18833. ;; If the element is folded, skip it altogether.
  18834. ((pcase (org-with-point-at post-affiliated
  18835. (get-char-property-and-overlay (line-end-position)
  18836. 'invisible))
  18837. (`(,(or `outline `org-hide-block) . ,o)
  18838. (goto-char (overlay-end o))
  18839. (forward-line)
  18840. t)
  18841. (_ nil)))
  18842. ;; At a greater element, move inside.
  18843. ((and contents-begin
  18844. (> contents-begin (point))
  18845. (not (eq type 'paragraph)))
  18846. (goto-char contents-begin)
  18847. ;; Items and footnote definitions contents may not start at
  18848. ;; the beginning of the line. In this case, skip until the
  18849. ;; next paragraph.
  18850. (cond
  18851. ((not (bolp)) (org--forward-paragraph-once))
  18852. ((org-previous-line-empty-p) (forward-line -1))
  18853. (t nil)))
  18854. ;; Move between empty lines in some blocks.
  18855. ((memq type '(comment-block example-block export-block src-block
  18856. verse-block))
  18857. (let ((contents-start
  18858. (org-with-point-at post-affiliated
  18859. (line-beginning-position 2))))
  18860. (if (< (point) contents-start)
  18861. (goto-char contents-start)
  18862. (let ((contents-end
  18863. (org-with-point-at end
  18864. (skip-chars-backward " \t\n")
  18865. (line-beginning-position))))
  18866. (cond
  18867. ((>= (point) contents-end)
  18868. (goto-char end)
  18869. (skip-chars-backward " \t\n")
  18870. (forward-line))
  18871. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18872. (forward-line -1))
  18873. (t nil))))))
  18874. (t
  18875. ;; Move to element's end.
  18876. (goto-char end)
  18877. (skip-chars-backward " \t\n")
  18878. (forward-line))))))))
  18879. (defun org--forward-paragraph-once--text-properties ()
  18880. "Move forward to end of paragraph or equivalent, once.
  18881. See `org-forward-paragraph'."
  18882. (interactive)
  18883. (save-restriction
  18884. (widen)
  18885. (skip-chars-forward " \t\n")
  18886. (cond
  18887. ((eobp) nil)
  18888. ;; When inside a folded part, move out of it.
  18889. ((when (org-invisible-p nil t)
  18890. (goto-char (cdr (org-fold-get-region-at-point)))
  18891. (forward-line)
  18892. t))
  18893. (t
  18894. (let* ((element (org--paragraph-at-point))
  18895. (type (org-element-type element))
  18896. (contents-begin (org-element-property :contents-begin element))
  18897. (end (org-element-property :end element))
  18898. (post-affiliated (org-element-property :post-affiliated element)))
  18899. (cond
  18900. ((eq type 'plain-list)
  18901. (forward-char)
  18902. (org--forward-paragraph-once))
  18903. ;; If the element is folded, skip it altogether.
  18904. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18905. (goto-char (cdr (org-fold-get-region-at-point
  18906. nil
  18907. (org-with-point-at post-affiliated
  18908. (line-end-position)))))
  18909. (forward-line)
  18910. t))
  18911. ;; At a greater element, move inside.
  18912. ((and contents-begin
  18913. (> contents-begin (point))
  18914. (not (eq type 'paragraph)))
  18915. (goto-char contents-begin)
  18916. ;; Items and footnote definitions contents may not start at
  18917. ;; the beginning of the line. In this case, skip until the
  18918. ;; next paragraph.
  18919. (cond
  18920. ((not (bolp)) (org--forward-paragraph-once))
  18921. ((org-previous-line-empty-p) (forward-line -1))
  18922. (t nil)))
  18923. ;; Move between empty lines in some blocks.
  18924. ((memq type '(comment-block example-block export-block src-block
  18925. verse-block))
  18926. (let ((contents-start
  18927. (org-with-point-at post-affiliated
  18928. (line-beginning-position 2))))
  18929. (if (< (point) contents-start)
  18930. (goto-char contents-start)
  18931. (let ((contents-end
  18932. (org-with-point-at end
  18933. (skip-chars-backward " \t\n")
  18934. (line-beginning-position))))
  18935. (cond
  18936. ((>= (point) contents-end)
  18937. (goto-char end)
  18938. (skip-chars-backward " \t\n")
  18939. (forward-line))
  18940. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18941. (forward-line -1))
  18942. (t nil))))))
  18943. (t
  18944. ;; Move to element's end.
  18945. (goto-char end)
  18946. (skip-chars-backward " \t\n")
  18947. (forward-line))))))))
  18948. (defun org--forward-paragraph-once ()
  18949. "Move forward to end of paragraph or equivalent, once.
  18950. See `org-forward-paragraph'."
  18951. (interactive)
  18952. (if (eq org-fold-core-style 'text-properties)
  18953. (org--forward-paragraph-once--text-properties)
  18954. (org--forward-paragraph-once--overlays)))
  18955. (defun org--backward-paragraph-once--overlays ()
  18956. "Move backward to start of paragraph or equivalent, once.
  18957. See `org-backward-paragraph'."
  18958. (interactive)
  18959. (save-restriction
  18960. (widen)
  18961. (cond
  18962. ((bobp) nil)
  18963. ;; Blank lines at the beginning of the buffer.
  18964. ((and (org-match-line "^[ \t]*$")
  18965. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18966. (goto-char (point-min)))
  18967. ;; When inside a folded part, move out of it.
  18968. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18969. (`(,(or `outline `org-hide-block) . ,o)
  18970. (goto-char (1- (overlay-start o)))
  18971. (org--backward-paragraph-once)
  18972. t)
  18973. (_ nil)))
  18974. (t
  18975. (let* ((element (org--paragraph-at-point))
  18976. (type (org-element-type element))
  18977. (begin (org-element-property :begin element))
  18978. (post-affiliated (org-element-property :post-affiliated element))
  18979. (contents-end (org-element-property :contents-end element))
  18980. (end (org-element-property :end element))
  18981. (parent (org-element-property :parent element))
  18982. (reach
  18983. ;; Move to the visible empty line above position P, or
  18984. ;; to position P. Return t.
  18985. (lambda (p)
  18986. (goto-char p)
  18987. (when (and (org-previous-line-empty-p)
  18988. (let ((end (line-end-position 0)))
  18989. (or (= end (point-min))
  18990. (not (org-invisible-p (1- end))))))
  18991. (forward-line -1))
  18992. t)))
  18993. (cond
  18994. ;; Already at the beginning of an element.
  18995. ((= begin (point))
  18996. (cond
  18997. ;; There is a blank line above. Move there.
  18998. ((and (org-previous-line-empty-p)
  18999. (let ((lep (line-end-position 0)))
  19000. ;; When the first headline start at point 2, don't choke while
  19001. ;; checking with `org-invisible-p'.
  19002. (or (= lep 1)
  19003. (not (org-invisible-p (1- (line-end-position 0)))))))
  19004. (forward-line -1))
  19005. ;; At the beginning of the first element within a greater
  19006. ;; element. Move to the beginning of the greater element.
  19007. ((and parent
  19008. (not (eq 'section (org-element-type parent)))
  19009. (= begin (org-element-property :contents-begin parent)))
  19010. (funcall reach (org-element-property :begin parent)))
  19011. ;; Since we have to move anyway, find the beginning
  19012. ;; position of the element above.
  19013. (t
  19014. (forward-char -1)
  19015. (org--backward-paragraph-once))))
  19016. ;; Skip paragraphs at the very beginning of footnote
  19017. ;; definitions or items.
  19018. ((and (eq type 'paragraph)
  19019. (org-with-point-at begin (not (bolp))))
  19020. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19021. ;; If the element is folded, skip it altogether.
  19022. ((org-with-point-at post-affiliated
  19023. (org-invisible-p (line-end-position) t))
  19024. (funcall reach begin))
  19025. ;; At the end of a greater element, move inside.
  19026. ((and contents-end
  19027. (<= contents-end (point))
  19028. (not (eq type 'paragraph)))
  19029. (cond
  19030. ((memq type '(footnote-definition plain-list))
  19031. (skip-chars-backward " \t\n")
  19032. (org--backward-paragraph-once))
  19033. ((= contents-end (point))
  19034. (forward-char -1)
  19035. (org--backward-paragraph-once))
  19036. (t
  19037. (goto-char contents-end))))
  19038. ;; Move between empty lines in some blocks.
  19039. ((and (memq type '(comment-block example-block export-block src-block
  19040. verse-block))
  19041. (let ((contents-start
  19042. (org-with-point-at post-affiliated
  19043. (line-beginning-position 2))))
  19044. (when (> (point) contents-start)
  19045. (let ((contents-end
  19046. (org-with-point-at end
  19047. (skip-chars-backward " \t\n")
  19048. (line-beginning-position))))
  19049. (if (> (point) contents-end)
  19050. (progn (goto-char contents-end) t)
  19051. (skip-chars-backward " \t\n" begin)
  19052. (re-search-backward "^[ \t]*\n" contents-start :move)
  19053. t))))))
  19054. ;; Move to element's start.
  19055. (t
  19056. (funcall reach begin))))))))
  19057. (defun org--backward-paragraph-once--text-properties ()
  19058. "Move backward to start of paragraph or equivalent, once.
  19059. See `org-backward-paragraph'."
  19060. (interactive)
  19061. (save-restriction
  19062. (widen)
  19063. (cond
  19064. ((bobp) nil)
  19065. ;; Blank lines at the beginning of the buffer.
  19066. ((and (org-match-line "^[ \t]*$")
  19067. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19068. (goto-char (point-min)))
  19069. ;; When inside a folded part, move out of it.
  19070. ((when (org-invisible-p (1- (point)) t)
  19071. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  19072. (org--backward-paragraph-once)
  19073. t))
  19074. (t
  19075. (let* ((element (org--paragraph-at-point))
  19076. (type (org-element-type element))
  19077. (begin (org-element-property :begin element))
  19078. (post-affiliated (org-element-property :post-affiliated element))
  19079. (contents-end (org-element-property :contents-end element))
  19080. (end (org-element-property :end element))
  19081. (parent (org-element-property :parent element))
  19082. (reach
  19083. ;; Move to the visible empty line above position P, or
  19084. ;; to position P. Return t.
  19085. (lambda (p)
  19086. (goto-char p)
  19087. (when (and (org-previous-line-empty-p)
  19088. (let ((end (line-end-position 0)))
  19089. (or (= end (point-min))
  19090. (not (org-invisible-p (1- end))))))
  19091. (forward-line -1))
  19092. t)))
  19093. (cond
  19094. ;; Already at the beginning of an element.
  19095. ((= begin (point))
  19096. (cond
  19097. ;; There is a blank line above. Move there.
  19098. ((and (org-previous-line-empty-p)
  19099. (not (org-invisible-p (1- (line-end-position 0)))))
  19100. (forward-line -1))
  19101. ;; At the beginning of the first element within a greater
  19102. ;; element. Move to the beginning of the greater element.
  19103. ((and parent
  19104. (not (eq 'section (org-element-type parent)))
  19105. (= begin (org-element-property :contents-begin parent)))
  19106. (funcall reach (org-element-property :begin parent)))
  19107. ;; Since we have to move anyway, find the beginning
  19108. ;; position of the element above.
  19109. (t
  19110. (forward-char -1)
  19111. (org--backward-paragraph-once))))
  19112. ;; Skip paragraphs at the very beginning of footnote
  19113. ;; definitions or items.
  19114. ((and (eq type 'paragraph)
  19115. (org-with-point-at begin (not (bolp))))
  19116. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19117. ;; If the element is folded, skip it altogether.
  19118. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  19119. (funcall reach begin))
  19120. ;; At the end of a greater element, move inside.
  19121. ((and contents-end
  19122. (<= contents-end (point))
  19123. (not (eq type 'paragraph)))
  19124. (cond
  19125. ((memq type '(footnote-definition plain-list))
  19126. (skip-chars-backward " \t\n")
  19127. (org--backward-paragraph-once))
  19128. ((= contents-end (point))
  19129. (forward-char -1)
  19130. (org--backward-paragraph-once))
  19131. (t
  19132. (goto-char contents-end))))
  19133. ;; Move between empty lines in some blocks.
  19134. ((and (memq type '(comment-block example-block export-block src-block
  19135. verse-block))
  19136. (let ((contents-start
  19137. (org-with-point-at post-affiliated
  19138. (line-beginning-position 2))))
  19139. (when (> (point) contents-start)
  19140. (let ((contents-end
  19141. (org-with-point-at end
  19142. (skip-chars-backward " \t\n")
  19143. (line-beginning-position))))
  19144. (if (> (point) contents-end)
  19145. (progn (goto-char contents-end) t)
  19146. (skip-chars-backward " \t\n" begin)
  19147. (re-search-backward "^[ \t]*\n" contents-start :move)
  19148. t))))))
  19149. ;; Move to element's start.
  19150. (t
  19151. (funcall reach begin))))))))
  19152. (defun org--backward-paragraph-once ()
  19153. "Move backward to start of paragraph or equivalent, once.
  19154. See `org-backward-paragraph'."
  19155. (interactive)
  19156. (if (eq org-fold-core-style 'text-properties)
  19157. (org--backward-paragraph-once--text-properties)
  19158. (org--backward-paragraph-once--overlays)))
  19159. (defun org-forward-element ()
  19160. "Move forward by one element.
  19161. Move to the next element at the same level, when possible."
  19162. (interactive)
  19163. (cond ((eobp) (user-error "Cannot move further down"))
  19164. ((org-with-limited-levels (org-at-heading-p))
  19165. (let ((origin (point)))
  19166. (goto-char (org-end-of-subtree nil t))
  19167. (unless (org-with-limited-levels (org-at-heading-p))
  19168. (goto-char origin)
  19169. (user-error "Cannot move further down"))))
  19170. (t
  19171. (let* ((elem (org-element-at-point))
  19172. (end (org-element-property :end elem))
  19173. (parent (org-element-property :parent elem)))
  19174. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19175. (goto-char (org-element-property :end parent)))
  19176. ((integer-or-marker-p end) (goto-char end))
  19177. (t (message "No element at point")))))))
  19178. (defun org-backward-element ()
  19179. "Move backward by one element.
  19180. Move to the previous element at the same level, when possible."
  19181. (interactive)
  19182. (cond ((bobp) (user-error "Cannot move further up"))
  19183. ((org-with-limited-levels (org-at-heading-p))
  19184. ;; At a headline, move to the previous one, if any, or stay
  19185. ;; here.
  19186. (let ((origin (point)))
  19187. (org-with-limited-levels (org-backward-heading-same-level 1))
  19188. ;; When current headline has no sibling above, move to its
  19189. ;; parent.
  19190. (when (= (point) origin)
  19191. (or (org-with-limited-levels (org-up-heading-safe))
  19192. (progn (goto-char origin)
  19193. (user-error "Cannot move further up"))))))
  19194. (t
  19195. (let* ((elem (org-element-at-point))
  19196. (beg (org-element-property :begin elem)))
  19197. (cond
  19198. ;; Move to beginning of current element if point isn't
  19199. ;; there already.
  19200. ((null beg) (message "No element at point"))
  19201. ((/= (point) beg) (goto-char beg))
  19202. (t (goto-char beg)
  19203. (skip-chars-backward " \r\t\n")
  19204. (unless (bobp)
  19205. (let ((prev (org-element-at-point)))
  19206. (goto-char (org-element-property :begin prev))
  19207. (while (and (setq prev (org-element-property :parent prev))
  19208. (<= (org-element-property :end prev) beg))
  19209. (goto-char (org-element-property :begin prev)))))))))))
  19210. (defun org-up-element ()
  19211. "Move to upper element."
  19212. (interactive)
  19213. (if (org-with-limited-levels (org-at-heading-p))
  19214. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19215. (let* ((elem (org-element-at-point))
  19216. (parent (org-element-property :parent elem)))
  19217. (if (and parent
  19218. (not (memq (org-element-type parent) '(section org-data))))
  19219. (goto-char (org-element-property :begin parent))
  19220. (if (org-with-limited-levels (org-before-first-heading-p))
  19221. (user-error "No surrounding element")
  19222. (org-with-limited-levels (org-back-to-heading)))))))
  19223. (defun org-down-element ()
  19224. "Move to inner element."
  19225. (interactive)
  19226. (let ((element (org-element-at-point)))
  19227. (cond
  19228. ((memq (org-element-type element) '(plain-list table))
  19229. (goto-char (org-element-property :contents-begin element))
  19230. (forward-char))
  19231. ((memq (org-element-type element) org-element-greater-elements)
  19232. ;; If contents are hidden, first disclose them.
  19233. (when (org-invisible-p (line-end-position)) (org-cycle))
  19234. (goto-char (or (org-element-property :contents-begin element)
  19235. (user-error "No content for this element"))))
  19236. (t (user-error "No inner element")))))
  19237. (defun org-drag-element-backward ()
  19238. "Move backward element at point."
  19239. (interactive)
  19240. (let ((elem (or (org-element-at-point)
  19241. (user-error "No element at point"))))
  19242. (if (eq (org-element-type elem) 'headline)
  19243. ;; Preserve point when moving a whole tree, even if point was
  19244. ;; on blank lines below the headline.
  19245. (let ((offset (skip-chars-backward " \t\n")))
  19246. (unwind-protect (org-move-subtree-up)
  19247. (forward-char (- offset))))
  19248. (let ((prev-elem
  19249. (save-excursion
  19250. (goto-char (org-element-property :begin elem))
  19251. (skip-chars-backward " \r\t\n")
  19252. (unless (bobp)
  19253. (let* ((beg (org-element-property :begin elem))
  19254. (prev (org-element-at-point))
  19255. (up prev))
  19256. (while (and (setq up (org-element-property :parent up))
  19257. (<= (org-element-property :end up) beg))
  19258. (setq prev up))
  19259. prev)))))
  19260. ;; Error out if no previous element or previous element is
  19261. ;; a parent of the current one.
  19262. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19263. (user-error "Cannot drag element backward")
  19264. (let ((pos (point)))
  19265. (org-element-swap-A-B prev-elem elem)
  19266. (goto-char (+ (org-element-property :begin prev-elem)
  19267. (- pos (org-element-property :begin elem))))))))))
  19268. (defun org-drag-element-forward ()
  19269. "Move forward element at point."
  19270. (interactive)
  19271. (let* ((pos (point))
  19272. (elem (or (org-element-at-point)
  19273. (user-error "No element at point"))))
  19274. (when (= (point-max) (org-element-property :end elem))
  19275. (user-error "Cannot drag element forward"))
  19276. (goto-char (org-element-property :end elem))
  19277. (let ((next-elem (org-element-at-point)))
  19278. (when (or (org-element-nested-p elem next-elem)
  19279. (and (eq (org-element-type next-elem) 'headline)
  19280. (not (eq (org-element-type elem) 'headline))))
  19281. (goto-char pos)
  19282. (user-error "Cannot drag element forward"))
  19283. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19284. ;; body's length (without final blanks) and by the length of
  19285. ;; blanks between ELEM and NEXT-ELEM.
  19286. (let ((size-next (- (save-excursion
  19287. (goto-char (org-element-property :end next-elem))
  19288. (skip-chars-backward " \r\t\n")
  19289. (forward-line)
  19290. ;; Small correction if buffer doesn't end
  19291. ;; with a newline character.
  19292. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19293. (org-element-property :begin next-elem)))
  19294. (size-blank (- (org-element-property :end elem)
  19295. (save-excursion
  19296. (goto-char (org-element-property :end elem))
  19297. (skip-chars-backward " \r\t\n")
  19298. (forward-line)
  19299. (point)))))
  19300. (org-element-swap-A-B elem next-elem)
  19301. (goto-char (+ pos size-next size-blank))))))
  19302. (defun org-drag-line-forward (arg)
  19303. "Drag the line at point ARG lines forward."
  19304. (interactive "p")
  19305. (dotimes (_ (abs arg))
  19306. (let ((c (current-column)))
  19307. (if (< 0 arg)
  19308. (progn
  19309. (beginning-of-line 2)
  19310. (transpose-lines 1)
  19311. (beginning-of-line 0))
  19312. (transpose-lines 1)
  19313. (beginning-of-line -1))
  19314. (org-move-to-column c))))
  19315. (defun org-drag-line-backward (arg)
  19316. "Drag the line at point ARG lines backward."
  19317. (interactive "p")
  19318. (org-drag-line-forward (- arg)))
  19319. (defun org-mark-element ()
  19320. "Put point at beginning of this element, mark at end.
  19321. Interactively, if this command is repeated or (in Transient Mark
  19322. mode) if the mark is active, it marks the next element after the
  19323. ones already marked."
  19324. (interactive)
  19325. (let (deactivate-mark)
  19326. (if (and (called-interactively-p 'any)
  19327. (or (and (eq last-command this-command) (mark t))
  19328. (and transient-mark-mode mark-active)))
  19329. (set-mark
  19330. (save-excursion
  19331. (goto-char (mark))
  19332. (goto-char (org-element-property :end (org-element-at-point)))
  19333. (point)))
  19334. (let ((element (org-element-at-point)))
  19335. (end-of-line)
  19336. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19337. (goto-char (org-element-property :begin element))))))
  19338. (defun org-narrow-to-element ()
  19339. "Narrow buffer to current element."
  19340. (interactive)
  19341. (let ((elem (org-element-at-point)))
  19342. (cond
  19343. ((eq (car elem) 'headline)
  19344. (narrow-to-region
  19345. (org-element-property :begin elem)
  19346. (org-element-property :end elem)))
  19347. ((memq (car elem) org-element-greater-elements)
  19348. (narrow-to-region
  19349. (org-element-property :contents-begin elem)
  19350. (org-element-property :contents-end elem)))
  19351. (t
  19352. (narrow-to-region
  19353. (org-element-property :begin elem)
  19354. (org-element-property :end elem))))))
  19355. (defun org-transpose-element ()
  19356. "Transpose current and previous elements, keeping blank lines between.
  19357. Point is moved after both elements."
  19358. (interactive)
  19359. (org-skip-whitespace)
  19360. (let ((end (org-element-property :end (org-element-at-point))))
  19361. (org-drag-element-backward)
  19362. (goto-char end)))
  19363. (defun org-unindent-buffer ()
  19364. "Un-indent the visible part of the buffer.
  19365. Relative indentation (between items, inside blocks, etc.) isn't
  19366. modified."
  19367. (interactive)
  19368. (unless (eq major-mode 'org-mode)
  19369. (user-error "Cannot un-indent a buffer not in Org mode"))
  19370. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19371. (unindent-tree
  19372. (lambda (contents)
  19373. (dolist (element (reverse contents))
  19374. (if (memq (org-element-type element) '(headline section))
  19375. (funcall unindent-tree (org-element-contents element))
  19376. (save-excursion
  19377. (save-restriction
  19378. (narrow-to-region
  19379. (org-element-property :begin element)
  19380. (org-element-property :end element))
  19381. (org-do-remove-indentation))))))))
  19382. (funcall unindent-tree (org-element-contents parse-tree))))
  19383. (defun org-make-options-regexp (kwds &optional extra)
  19384. "Make a regular expression for keyword lines.
  19385. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19386. when non-nil, is a regexp matching keywords names."
  19387. (concat "^[ \t]*#\\+\\("
  19388. (regexp-opt kwds)
  19389. (and extra (concat (and kwds "\\|") extra))
  19390. "\\):[ \t]*\\(.*\\)"))
  19391. ;;; Conveniently switch to Info nodes
  19392. (defun org-info-find-node (&optional nodename)
  19393. "Find Info documentation NODENAME or Org documentation according context.
  19394. Started from `gnus-info-find-node'."
  19395. (interactive)
  19396. (Info-goto-node
  19397. (or nodename
  19398. (let ((default-org-info-node "(org) Top"))
  19399. (cond
  19400. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19401. ((eq 'org-mode major-mode)
  19402. (let* ((context (org-element-at-point))
  19403. (element-info-nodes ; compare to `org-element-all-elements'.
  19404. `((babel-call . "(org) Evaluating Code Blocks")
  19405. (center-block . "(org) Paragraphs")
  19406. (clock . ,default-org-info-node)
  19407. (comment . "(org) Comment Lines")
  19408. (comment-block . "(org) Comment Lines")
  19409. (diary-sexp . ,default-org-info-node)
  19410. (drawer . "(org) Drawers")
  19411. (dynamic-block . "(org) Dynamic Blocks")
  19412. (example-block . "(org) Literal Examples")
  19413. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19414. (fixed-width . ,default-org-info-node)
  19415. (footnote-definition . "(org) Creating Footnotes")
  19416. (headline . "(org) Document Structure")
  19417. (horizontal-rule . "(org) Built-in Table Editor")
  19418. (inlinetask . ,default-org-info-node)
  19419. (item . "(org) Plain Lists")
  19420. (keyword . "(org) Per-file keywords")
  19421. (latex-environment . "(org) LaTeX Export")
  19422. (node-property . "(org) Properties and Columns")
  19423. (paragraph . "(org) Paragraphs")
  19424. (plain-list . "(org) Plain Lists")
  19425. (planning . "(org) Deadlines and Scheduling")
  19426. (property-drawer . "(org) Properties and Columns")
  19427. (quote-block . "(org) Paragraphs")
  19428. (section . ,default-org-info-node)
  19429. (special-block . ,default-org-info-node)
  19430. (src-block . "(org) Working with Source Code")
  19431. (table . "(org) Tables")
  19432. (table-row . "(org) Tables")
  19433. (verse-block . "(org) Paragraphs"))))
  19434. (or (cdr (assoc (car context) element-info-nodes))
  19435. default-org-info-node)))
  19436. (t default-org-info-node))))))
  19437. ;;; Finish up
  19438. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19439. (lambda () (add-hook 'change-major-mode-hook
  19440. 'org-fold-show-all 'append 'local)))
  19441. (provide 'org)
  19442. (run-hooks 'org-load-hook)
  19443. ;;; org.el ends here