org.el 806 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029
  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. ;; Homepage: 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 homepage of
  55. ;; Org mode, you can read the same text online as HTML. There is also an
  56. ;; excellent reference card made by Philip Rooke. This card can be found
  57. ;; in the 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 (when (boundp '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-open-non-existing-files nil
  1176. "Non-nil means `org-open-file' opens non-existing files.
  1177. When nil, an error is thrown.
  1178. This variable applies only to external applications because they
  1179. might choke on non-existing files. If the link is to a file that
  1180. will be opened in Emacs, the variable is ignored."
  1181. :group 'org
  1182. :type 'boolean
  1183. :safe #'booleanp)
  1184. (defcustom org-open-directory-means-index-dot-org nil
  1185. "When non-nil a link to a directory really means to \"index.org\".
  1186. When nil, following a directory link runs Dired or opens
  1187. a finder/explorer window on that directory."
  1188. :group 'org
  1189. :type 'boolean
  1190. :safe #'booleanp)
  1191. (defcustom org-bookmark-names-plist
  1192. '(:last-capture "org-capture-last-stored"
  1193. :last-refile "org-refile-last-stored"
  1194. :last-capture-marker "org-capture-last-stored-marker")
  1195. "Names for bookmarks automatically set by some Org commands.
  1196. This can provide strings as names for a number of bookmarks Org sets
  1197. automatically. The following keys are currently implemented:
  1198. :last-capture
  1199. :last-capture-marker
  1200. :last-refile
  1201. When a key does not show up in the property list, the corresponding bookmark
  1202. is not set."
  1203. :group 'org-structure
  1204. :type 'plist)
  1205. (defgroup org-edit-structure nil
  1206. "Options concerning structure editing in Org mode."
  1207. :tag "Org Edit Structure"
  1208. :group 'org-structure)
  1209. (defcustom org-odd-levels-only nil
  1210. "Non-nil means skip even levels and only use odd levels for the outline.
  1211. This has the effect that two stars are being added/taken away in
  1212. promotion/demotion commands. It also influences how levels are
  1213. handled by the exporters.
  1214. Changing it requires restart of `font-lock-mode' to become effective
  1215. for fontification also in regions already fontified.
  1216. You may also set this on a per-file basis by adding one of the following
  1217. lines to the buffer:
  1218. #+STARTUP: odd
  1219. #+STARTUP: oddeven"
  1220. :group 'org-edit-structure
  1221. :group 'org-appearance
  1222. :type 'boolean)
  1223. (defcustom org-adapt-indentation nil
  1224. "Non-nil means adapt indentation to outline node level.
  1225. When set to t, Org assumes that you write outlines by indenting
  1226. text in each node to align with the headline, after the stars.
  1227. When this variable is set to `headline-data', Org only adapts the
  1228. indentation of the data lines right below the headline, such as
  1229. planning/clock lines and property/logbook drawers.
  1230. The following issues are influenced by this variable:
  1231. - The indentation is increased by one space in a demotion
  1232. command, and decreased by one in a promotion command. However,
  1233. in the latter case, if shifting some line in the entry body
  1234. would alter document structure (e.g., insert a new headline),
  1235. indentation is not changed at all.
  1236. - Property drawers and planning information is inserted indented
  1237. when this variable is set. When nil, they will not be indented.
  1238. - TAB indents a line relative to current level. The lines below
  1239. a headline will be indented when this variable is set to t.
  1240. Note that this is all about true indentation, by adding and
  1241. removing space characters. See also \"org-indent.el\" which does
  1242. level-dependent indentation in a virtual way, i.e. at display
  1243. time in Emacs."
  1244. :group 'org-edit-structure
  1245. :type '(choice
  1246. (const :tag "Adapt indentation for all lines" t)
  1247. (const :tag "Adapt indentation for headline data lines"
  1248. headline-data)
  1249. (const :tag "Do not adapt indentation at all" nil))
  1250. :safe (lambda (x) (memq x '(t nil headline-data))))
  1251. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1252. (defcustom org-special-ctrl-a/e nil
  1253. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1254. When t, `C-a' will bring back the cursor to the beginning of the
  1255. headline text, i.e. after the stars and after a possible TODO
  1256. keyword. In an item, this will be the position after bullet and
  1257. check-box, if any. When the cursor is already at that position,
  1258. another `C-a' will bring it to the beginning of the line.
  1259. `C-e' will jump to the end of the headline, ignoring the presence
  1260. of tags in the headline. A second `C-e' will then jump to the
  1261. true end of the line, after any tags. This also means that, when
  1262. this variable is non-nil, `C-e' also will never jump beyond the
  1263. end of the heading of a folded section, i.e. not after the
  1264. ellipses.
  1265. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1266. normally, going to the true line boundary first. Only a directly
  1267. following, identical keypress will bring the cursor to the
  1268. special positions.
  1269. This may also be a cons cell where the behavior for `C-a' and
  1270. `C-e' is set separately."
  1271. :group 'org-edit-structure
  1272. :type '(choice
  1273. (const :tag "off" nil)
  1274. (const :tag "on: after stars/bullet and before tags first" t)
  1275. (const :tag "reversed: true line boundary first" reversed)
  1276. (cons :tag "Set C-a and C-e separately"
  1277. (choice :tag "Special C-a"
  1278. (const :tag "off" nil)
  1279. (const :tag "on: after stars/bullet first" t)
  1280. (const :tag "reversed: before stars/bullet first" reversed))
  1281. (choice :tag "Special C-e"
  1282. (const :tag "off" nil)
  1283. (const :tag "on: before tags first" t)
  1284. (const :tag "reversed: after tags first" reversed)))))
  1285. (defcustom org-special-ctrl-k nil
  1286. "Non-nil means `C-k' will behave specially in headlines.
  1287. When nil, `C-k' will call the default `kill-line' command.
  1288. When t, the following will happen while the cursor is in the headline:
  1289. - When at the beginning of a headline, kill the entire subtree.
  1290. - When in the middle of the headline text, kill the text up to the tags.
  1291. - When after the headline text and before the tags, kill all the tags."
  1292. :group 'org-edit-structure
  1293. :type 'boolean)
  1294. (defcustom org-ctrl-k-protect-subtree nil
  1295. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1296. When set to the symbol `error', simply throw an error when `C-k' is
  1297. used to kill (part-of) a headline that has hidden text behind it.
  1298. Any other non-nil value will result in a query to the user, if it is
  1299. OK to kill that hidden subtree. When nil, kill without remorse."
  1300. :group 'org-edit-structure
  1301. :version "24.1"
  1302. :type '(choice
  1303. (const :tag "Do not protect hidden subtrees" nil)
  1304. (const :tag "Protect hidden subtrees with a security query" t)
  1305. (const :tag "Never kill a hidden subtree with C-k" error)))
  1306. (defcustom org-special-ctrl-o t
  1307. "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
  1308. :group 'org-edit-structure
  1309. :type 'boolean)
  1310. (defcustom org-yank-folded-subtrees t
  1311. "Non-nil means when yanking subtrees, fold them.
  1312. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1313. it starts with a heading and all other headings in it are either children
  1314. or siblings, then fold all the subtrees. However, do this only if no
  1315. text after the yank would be swallowed into a folded tree by this action."
  1316. :group 'org-edit-structure
  1317. :type 'boolean)
  1318. (defcustom org-yank-adjusted-subtrees nil
  1319. "Non-nil means when yanking subtrees, adjust the level.
  1320. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1321. this function for details."
  1322. :group 'org-edit-structure
  1323. :type 'boolean)
  1324. (defcustom org-M-RET-may-split-line '((default . t))
  1325. "Non-nil means M-RET will split the line at the cursor position.
  1326. When nil, it will go to the end of the line before making a
  1327. new line.
  1328. You may also set this option in a different way for different
  1329. contexts. Valid contexts are:
  1330. headline when creating a new headline
  1331. item when creating a new item
  1332. table in a table field
  1333. default the value to be used for all contexts not explicitly
  1334. customized"
  1335. :group 'org-structure
  1336. :group 'org-table
  1337. :type '(choice
  1338. (const :tag "Always" t)
  1339. (const :tag "Never" nil)
  1340. (repeat :greedy t :tag "Individual contexts"
  1341. (cons
  1342. (choice :tag "Context"
  1343. (const headline)
  1344. (const item)
  1345. (const table)
  1346. (const default))
  1347. (boolean)))))
  1348. (defcustom org-insert-heading-respect-content nil
  1349. "Non-nil means insert new headings after the current subtree.
  1350. \\<org-mode-map>
  1351. When nil, the new heading is created directly after the current line.
  1352. The commands `\\[org-insert-heading-respect-content]' and \
  1353. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1354. for the duration of the command."
  1355. :group 'org-structure
  1356. :type 'boolean)
  1357. (defcustom org-blank-before-new-entry '((heading . auto)
  1358. (plain-list-item . auto))
  1359. "Should `org-insert-heading' leave a blank line before new heading/item?
  1360. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1361. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1362. which case Org will look at the surrounding headings/items and try to
  1363. make an intelligent decision whether to insert a blank line or not."
  1364. :group 'org-edit-structure
  1365. :type '(list
  1366. (cons (const heading)
  1367. (choice (const :tag "Never" nil)
  1368. (const :tag "Always" t)
  1369. (const :tag "Auto" auto)))
  1370. (cons (const plain-list-item)
  1371. (choice (const :tag "Never" nil)
  1372. (const :tag "Always" t)
  1373. (const :tag "Auto" auto)))))
  1374. (defcustom org-insert-heading-hook nil
  1375. "Hook being run after inserting a new heading."
  1376. :group 'org-edit-structure
  1377. :type 'hook)
  1378. (defgroup org-sparse-trees nil
  1379. "Options concerning sparse trees in Org mode."
  1380. :tag "Org Sparse Trees"
  1381. :group 'org-structure)
  1382. (defcustom org-highlight-sparse-tree-matches t
  1383. "Non-nil means highlight all matches that define a sparse tree.
  1384. The highlights will automatically disappear the next time the buffer is
  1385. changed by an edit command."
  1386. :group 'org-sparse-trees
  1387. :type 'boolean)
  1388. (defcustom org-remove-highlights-with-change t
  1389. "Non-nil means any change to the buffer will remove temporary highlights.
  1390. \\<org-mode-map>\
  1391. Such highlights are created by `org-occur' and `org-clock-display'.
  1392. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1393. to get rid of the highlights.
  1394. The highlights created by `org-latex-preview' always need
  1395. `\\[org-latex-preview]' to be removed."
  1396. :group 'org-sparse-trees
  1397. :group 'org-time
  1398. :type 'boolean)
  1399. (defcustom org-occur-case-fold-search t
  1400. "Non-nil means `org-occur' should be case-insensitive.
  1401. If set to `smart' the search will be case-insensitive only if it
  1402. doesn't specify any upper case character."
  1403. :group 'org-sparse-trees
  1404. :version "26.1"
  1405. :type '(choice
  1406. (const :tag "Case-sensitive" nil)
  1407. (const :tag "Case-insensitive" t)
  1408. (const :tag "Case-insensitive for lower case searches only" smart)))
  1409. (defcustom org-occur-hook '(org-first-headline-recenter)
  1410. "Hook that is run after `org-occur' has constructed a sparse tree.
  1411. This can be used to recenter the window to show as much of the structure
  1412. as possible."
  1413. :group 'org-sparse-trees
  1414. :type 'hook)
  1415. (defcustom org-self-insert-cluster-for-undo nil
  1416. "Non-nil means cluster self-insert commands for undo when possible.
  1417. If this is set, then, like in the Emacs command loop, 20 consecutive
  1418. characters will be undone together.
  1419. This is configurable, because there is some impact on typing performance."
  1420. :group 'org-table
  1421. :type 'boolean)
  1422. (defvaralias 'org-activate-links 'org-highlight-links)
  1423. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1424. "Types of links that should be highlighted in Org files.
  1425. This is a list of symbols, each one of them leading to the
  1426. highlighting of a certain link type.
  1427. You can still open links that are not highlighted.
  1428. In principle, it does not hurt to turn on highlighting for all
  1429. link types. There may be a small gain when turning off unused
  1430. link types. The types are:
  1431. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1432. angle Links in angular brackets that may contain whitespace like
  1433. <bbdb:Carsten Dominik>.
  1434. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1435. radio Text that is matched by a radio target, see manual for details.
  1436. tag Tag settings in a headline (link to tag search).
  1437. date Time stamps (link to calendar).
  1438. footnote Footnote labels.
  1439. If you set this variable during an Emacs session, use `org-mode-restart'
  1440. in the Org buffer so that the change takes effect."
  1441. :group 'org-appearance
  1442. :type '(set :greedy t
  1443. (const :tag "Double bracket links" bracket)
  1444. (const :tag "Angular bracket links" angle)
  1445. (const :tag "Plain text links" plain)
  1446. (const :tag "Radio target matches" radio)
  1447. (const :tag "Tags" tag)
  1448. (const :tag "Timestamps" date)
  1449. (const :tag "Footnotes" footnote)))
  1450. (defcustom org-mark-ring-length 4
  1451. "Number of different positions to be recorded in the ring.
  1452. Changing this requires a restart of Emacs to work correctly."
  1453. :group 'org-link-follow
  1454. :type 'integer)
  1455. (defgroup org-todo nil
  1456. "Options concerning TODO items in Org mode."
  1457. :tag "Org TODO"
  1458. :group 'org)
  1459. (defgroup org-progress nil
  1460. "Options concerning Progress logging in Org mode."
  1461. :tag "Org Progress"
  1462. :group 'org-time)
  1463. (defvar org-todo-interpretation-widgets
  1464. '((:tag "Sequence (cycling hits every state)" sequence)
  1465. (:tag "Type (cycling directly to DONE)" type))
  1466. "The available interpretation symbols for customizing `org-todo-keywords'.
  1467. Interested libraries should add to this list.")
  1468. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1469. "List of TODO entry keyword sequences and their interpretation.
  1470. \\<org-mode-map>This is a list of sequences.
  1471. Each sequence starts with a symbol, either `sequence' or `type',
  1472. indicating if the keywords should be interpreted as a sequence of
  1473. action steps, or as different types of TODO items. The first
  1474. keywords are states requiring action - these states will select a headline
  1475. for inclusion into the global TODO list Org produces. If one of the
  1476. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1477. signify that no further action is necessary. If \"|\" is not found,
  1478. the last keyword is treated as the only DONE state of the sequence.
  1479. The command `\\[org-todo]' cycles an entry through these states, and one
  1480. additional state where no keyword is present. For details about this
  1481. cycling, see the manual.
  1482. TODO keywords and interpretation can also be set on a per-file basis with
  1483. the special #+SEQ_TODO and #+TYP_TODO lines.
  1484. Each keyword can optionally specify a character for fast state selection
  1485. \(in combination with the variable `org-use-fast-todo-selection')
  1486. and specifiers for state change logging, using the same syntax that
  1487. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1488. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1489. indicates to record a time stamp each time this state is selected.
  1490. Each keyword may also specify if a timestamp or a note should be
  1491. recorded when entering or leaving the state, by adding additional
  1492. characters in the parenthesis after the keyword. This looks like this:
  1493. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1494. record only the time of the state change. With X and Y being either
  1495. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1496. Y when leaving the state if and only if the *target* state does not
  1497. define X. You may omit any of the fast-selection key or X or /Y,
  1498. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1499. For backward compatibility, this variable may also be just a list
  1500. of keywords. In this case the interpretation (sequence or type) will be
  1501. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1502. :group 'org-todo
  1503. :group 'org-keywords
  1504. :type '(choice
  1505. (repeat :tag "Old syntax, just keywords"
  1506. (string :tag "Keyword"))
  1507. (repeat :tag "New syntax"
  1508. (cons
  1509. (choice
  1510. :tag "Interpretation"
  1511. ;;Quick and dirty way to see
  1512. ;;`org-todo-interpretation'. This takes the
  1513. ;;place of item arguments
  1514. :convert-widget
  1515. (lambda (widget)
  1516. (widget-put widget
  1517. :args (mapcar
  1518. (lambda (x)
  1519. (widget-convert
  1520. (cons 'const x)))
  1521. org-todo-interpretation-widgets))
  1522. widget))
  1523. (repeat
  1524. (string :tag "Keyword"))))))
  1525. (defvar-local org-todo-keywords-1 nil
  1526. "All TODO and DONE keywords active in a buffer.")
  1527. (defvar org-todo-keywords-for-agenda nil)
  1528. (defvar org-done-keywords-for-agenda nil)
  1529. (defvar org-todo-keyword-alist-for-agenda nil)
  1530. (defvar org-tag-alist-for-agenda nil
  1531. "Alist of all tags from all agenda files.")
  1532. (defvar org-tag-groups-alist-for-agenda nil
  1533. "Alist of all groups tags from all current agenda files.")
  1534. (defvar-local org-tag-groups-alist nil)
  1535. (defvar org-agenda-contributing-files nil)
  1536. (defvar-local org-current-tag-alist nil
  1537. "Alist of all tag groups in current buffer.
  1538. This variable takes into consideration `org-tag-alist',
  1539. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1540. (defvar-local org-not-done-keywords nil)
  1541. (defvar-local org-done-keywords nil)
  1542. (defvar-local org-todo-heads nil)
  1543. (defvar-local org-todo-sets nil)
  1544. (defvar-local org-todo-log-states nil)
  1545. (defvar-local org-todo-kwd-alist nil)
  1546. (defvar-local org-todo-key-alist nil)
  1547. (defvar-local org-todo-key-trigger nil)
  1548. (defcustom org-todo-interpretation 'sequence
  1549. "Controls how TODO keywords are interpreted.
  1550. This variable is in principle obsolete and is only used for
  1551. backward compatibility, if the interpretation of todo keywords is
  1552. not given already in `org-todo-keywords'. See that variable for
  1553. more information."
  1554. :group 'org-todo
  1555. :group 'org-keywords
  1556. :type '(choice (const sequence)
  1557. (const type)))
  1558. (defcustom org-use-fast-todo-selection 'auto
  1559. "\\<org-mode-map>\
  1560. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1561. This variable describes if and under what circumstances the cycling
  1562. mechanism for TODO keywords will be replaced by a single-key, direct
  1563. selection scheme, where the choices are displayed in a little window.
  1564. When nil, fast selection is never used. This means that the command
  1565. will always switch to the next state.
  1566. When it is the symbol `auto', fast selection is whenever selection
  1567. keys have been defined.
  1568. `expert' is like `auto', but no special window with the keyword
  1569. will be shown, choices will only be listed in the prompt.
  1570. In all cases, the special interface is only used if access keys have
  1571. actually been assigned by the user, i.e. if keywords in the configuration
  1572. are followed by a letter in parenthesis, like TODO(t)."
  1573. :group 'org-todo
  1574. :set (lambda (var val)
  1575. (cond
  1576. ((eq var t) (set-default-toplevel-value var 'auto))
  1577. ((eq var 'prefix) (set-default-toplevel-value var nil))
  1578. (t (set-default-toplevel-value var val))))
  1579. :type '(choice
  1580. (const :tag "Never" nil)
  1581. (const :tag "Automatically, when key letter have been defined" auto)
  1582. (const :tag "Automatically, but don't show the selection window" expert)))
  1583. (defcustom org-provide-todo-statistics t
  1584. "Non-nil means update todo statistics after insert and toggle.
  1585. ALL-HEADLINES means update todo statistics by including headlines
  1586. with no TODO keyword as well, counting them as not done.
  1587. A list of TODO keywords means the same, but skip keywords that are
  1588. not in this list.
  1589. When set to a list of two lists, the first list contains keywords
  1590. to consider as TODO keywords, the second list contains keywords
  1591. to consider as DONE keywords.
  1592. When this is set, todo statistics is updated in the parent of the
  1593. current entry each time a todo state is changed."
  1594. :group 'org-todo
  1595. :type '(choice
  1596. (const :tag "Yes, only for TODO entries" t)
  1597. (const :tag "Yes, including all entries" all-headlines)
  1598. (repeat :tag "Yes, for TODOs in this list"
  1599. (string :tag "TODO keyword"))
  1600. (list :tag "Yes, for TODOs and DONEs in these lists"
  1601. (repeat (string :tag "TODO keyword"))
  1602. (repeat (string :tag "DONE keyword")))
  1603. (other :tag "No TODO statistics" nil)))
  1604. (defcustom org-hierarchical-todo-statistics t
  1605. "Non-nil means TODO statistics covers just direct children.
  1606. When nil, all entries in the subtree are considered.
  1607. This has only an effect if `org-provide-todo-statistics' is set.
  1608. To set this to nil for only a single subtree, use a COOKIE_DATA
  1609. property and include the word \"recursive\" into the value."
  1610. :group 'org-todo
  1611. :type 'boolean)
  1612. (defcustom org-after-todo-state-change-hook nil
  1613. "Hook which is run after the state of a TODO item was changed.
  1614. The new state (a string with a TODO keyword, or nil) is available in the
  1615. Lisp variable `org-state'."
  1616. :group 'org-todo
  1617. :type 'hook)
  1618. (defvar org-blocker-hook nil
  1619. "Hook for functions that are allowed to block a state change.
  1620. Functions in this hook should not modify the buffer.
  1621. Each function gets as its single argument a property list,
  1622. see `org-trigger-hook' for more information about this list.
  1623. If any of the functions in this hook returns nil, the state change
  1624. is blocked.")
  1625. (defvar org-trigger-hook nil
  1626. "Hook for functions that are triggered by a state change.
  1627. Each function gets as its single argument a property list with at
  1628. least the following elements:
  1629. (:type type-of-change :position pos-at-entry-start
  1630. :from old-state :to new-state)
  1631. Depending on the type, more properties may be present.
  1632. This mechanism is currently implemented for:
  1633. TODO state changes
  1634. ------------------
  1635. :type todo-state-change
  1636. :from previous state (keyword as a string), or nil, or a symbol
  1637. `todo' or `done', to indicate the general type of state.
  1638. :to new state, like in :from")
  1639. (defcustom org-enforce-todo-dependencies nil
  1640. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1641. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1642. be blocked if any prior sibling is not yet done.
  1643. Finally, if the parent is blocked because of ordered siblings of its own,
  1644. the child will also be blocked."
  1645. :set (lambda (var val)
  1646. (set-default-toplevel-value var val)
  1647. (if val
  1648. (add-hook 'org-blocker-hook
  1649. 'org-block-todo-from-children-or-siblings-or-parent)
  1650. (remove-hook 'org-blocker-hook
  1651. 'org-block-todo-from-children-or-siblings-or-parent)))
  1652. :group 'org-todo
  1653. :type 'boolean)
  1654. (defcustom org-enforce-todo-checkbox-dependencies nil
  1655. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1656. When this is nil, checkboxes have no influence on switching TODO states.
  1657. When non-nil, you first need to check off all check boxes before the TODO
  1658. entry can be switched to DONE.
  1659. This variable needs to be set before org.el is loaded, and you need to
  1660. restart Emacs after a change to make the change effective. The only way
  1661. to change it while Emacs is running is through the customize interface."
  1662. :set (lambda (var val)
  1663. (set-default-toplevel-value var val)
  1664. (if val
  1665. (add-hook 'org-blocker-hook
  1666. 'org-block-todo-from-checkboxes)
  1667. (remove-hook 'org-blocker-hook
  1668. 'org-block-todo-from-checkboxes)))
  1669. :group 'org-todo
  1670. :type 'boolean)
  1671. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1672. "Non-nil means inserting a TODO heading is treated as state change.
  1673. So when the command `\\[org-insert-todo-heading]' is used, state change
  1674. logging will apply if appropriate. When nil, the new TODO item will
  1675. be inserted directly, and no logging will take place."
  1676. :group 'org-todo
  1677. :type 'boolean)
  1678. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1679. "Non-nil means switching TODO states with S-cursor counts as state change.
  1680. This is the default behavior. However, setting this to nil allows a
  1681. convenient way to select a TODO state and bypass any logging associated
  1682. with that."
  1683. :group 'org-todo
  1684. :type 'boolean)
  1685. (defcustom org-todo-state-tags-triggers nil
  1686. "Tag changes that should be triggered by TODO state changes.
  1687. This is a list. Each entry is
  1688. (state-change (tag . flag) .......)
  1689. State-change can be a string with a state, and empty string to indicate the
  1690. state that has no TODO keyword, or it can be one of the symbols `todo'
  1691. or `done', meaning any not-done or done state, respectively."
  1692. :group 'org-todo
  1693. :group 'org-tags
  1694. :type '(repeat
  1695. (cons (choice :tag "When changing to"
  1696. (const :tag "Not-done state" todo)
  1697. (const :tag "Done state" done)
  1698. (string :tag "State"))
  1699. (repeat
  1700. (cons :tag "Tag action"
  1701. (string :tag "Tag")
  1702. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1703. (defcustom org-log-done nil
  1704. "Information to record when a task moves to the DONE state.
  1705. Possible values are:
  1706. nil Don't add anything, just change the keyword
  1707. time Add a time stamp to the task
  1708. note Prompt for a note and add it with template `org-log-note-headings'
  1709. This option can also be set with on a per-file-basis with
  1710. #+STARTUP: nologdone
  1711. #+STARTUP: logdone
  1712. #+STARTUP: lognotedone
  1713. You can have local logging settings for a subtree by setting the LOGGING
  1714. property to one or more of these keywords."
  1715. :group 'org-todo
  1716. :group 'org-progress
  1717. :type '(choice
  1718. (const :tag "No logging" nil)
  1719. (const :tag "Record CLOSED timestamp" time)
  1720. (const :tag "Record CLOSED timestamp with note." note)))
  1721. ;; Normalize old uses of org-log-done.
  1722. (cond
  1723. ((eq org-log-done t) (setq org-log-done 'time))
  1724. ((and (listp org-log-done) (memq 'done org-log-done))
  1725. (setq org-log-done 'note)))
  1726. (defcustom org-log-reschedule nil
  1727. "Information to record when the scheduling date of a task is modified.
  1728. Possible values are:
  1729. nil Don't add anything, just change the date
  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: nologreschedule
  1734. #+STARTUP: logreschedule
  1735. #+STARTUP: lognotereschedule
  1736. You can have local logging settings for a subtree by setting the LOGGING
  1737. property to one or more of these keywords.
  1738. This variable has an effect when calling `org-schedule' or
  1739. `org-agenda-schedule' only."
  1740. :group 'org-todo
  1741. :group 'org-progress
  1742. :type '(choice
  1743. (const :tag "No logging" nil)
  1744. (const :tag "Record timestamp" time)
  1745. (const :tag "Record timestamp with note" note)))
  1746. (defcustom org-log-redeadline nil
  1747. "Information to record when the deadline date of a task is modified.
  1748. Possible values are:
  1749. nil Don't add anything, just change the date
  1750. time Add a time stamp to the task
  1751. note Prompt for a note and add it with template `org-log-note-headings'
  1752. This option can also be set with on a per-file-basis with
  1753. #+STARTUP: nologredeadline
  1754. #+STARTUP: logredeadline
  1755. #+STARTUP: lognoteredeadline
  1756. You can have local logging settings for a subtree by setting the LOGGING
  1757. property to one or more of these keywords.
  1758. This variable has an effect when calling `org-deadline' or
  1759. `org-agenda-deadline' only."
  1760. :group 'org-todo
  1761. :group 'org-progress
  1762. :type '(choice
  1763. (const :tag "No logging" nil)
  1764. (const :tag "Record timestamp" time)
  1765. (const :tag "Record timestamp with note." note)))
  1766. (defcustom org-log-note-clock-out nil
  1767. "Non-nil means record a note when clocking out of an item.
  1768. This can also be configured on a per-file basis by adding one of
  1769. the following lines anywhere in the buffer:
  1770. #+STARTUP: lognoteclock-out
  1771. #+STARTUP: nolognoteclock-out"
  1772. :group 'org-todo
  1773. :group 'org-progress
  1774. :type 'boolean)
  1775. (defcustom org-log-done-with-time t
  1776. "Non-nil means the CLOSED time stamp will contain date and time.
  1777. When nil, only the date will be recorded."
  1778. :group 'org-progress
  1779. :type 'boolean)
  1780. (defcustom org-log-note-headings
  1781. '((done . "CLOSING NOTE %t")
  1782. (state . "State %-12s from %-12S %t")
  1783. (note . "Note taken on %t")
  1784. (reschedule . "Rescheduled from %S on %t")
  1785. (delschedule . "Not scheduled, was %S on %t")
  1786. (redeadline . "New deadline from %S on %t")
  1787. (deldeadline . "Removed deadline, was %S on %t")
  1788. (refile . "Refiled on %t")
  1789. (clock-out . ""))
  1790. "Headings for notes added to entries.
  1791. The value is an alist, with the car being a symbol indicating the
  1792. note context, and the cdr is the heading to be used. The heading
  1793. may also be the empty string. The following placeholders can be
  1794. used:
  1795. %t a time stamp.
  1796. %T an active time stamp instead the default inactive one
  1797. %d a short-format time stamp.
  1798. %D an active short-format time stamp.
  1799. %s the new TODO state or time stamp (inactive), in double quotes.
  1800. %S the old TODO state or time stamp (inactive), in double quotes.
  1801. %u the user name.
  1802. %U full user name.
  1803. In fact, it is not a good idea to change the `state' entry,
  1804. because Agenda Log mode depends on the format of these entries."
  1805. :group 'org-todo
  1806. :group 'org-progress
  1807. :type '(list :greedy t
  1808. (cons (const :tag "Heading when closing an item" done) string)
  1809. (cons (const :tag
  1810. "Heading when changing todo state (todo sequence only)"
  1811. state) string)
  1812. (cons (const :tag "Heading when just taking a note" note) string)
  1813. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1814. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1815. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1816. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1817. (cons (const :tag "Heading when refiling" refile) string)
  1818. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1819. (unless (assq 'note org-log-note-headings)
  1820. (push '(note . "%t") org-log-note-headings))
  1821. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1822. (defcustom org-log-into-drawer nil
  1823. "Non-nil means insert state change notes and time stamps into a drawer.
  1824. When nil, state changes notes will be inserted after the headline and
  1825. any scheduling and clock lines, but not inside a drawer.
  1826. The value of this variable should be the name of the drawer to use.
  1827. LOGBOOK is proposed as the default drawer for this purpose, you can
  1828. also set this to a string to define the drawer of your choice.
  1829. A value of t is also allowed, representing \"LOGBOOK\".
  1830. A value of t or nil can also be set with on a per-file-basis with
  1831. #+STARTUP: logdrawer
  1832. #+STARTUP: nologdrawer
  1833. If this variable is set, `org-log-state-notes-insert-after-drawers'
  1834. will be ignored.
  1835. You can set the property LOG_INTO_DRAWER to overrule this setting for
  1836. a subtree.
  1837. Do not check directly this variable in a Lisp program. Call
  1838. function `org-log-into-drawer' instead."
  1839. :group 'org-todo
  1840. :group 'org-progress
  1841. :type '(choice
  1842. (const :tag "Not into a drawer" nil)
  1843. (const :tag "LOGBOOK" t)
  1844. (string :tag "Other")))
  1845. (defun org-log-into-drawer ()
  1846. "Name of the log drawer, as a string, or nil.
  1847. This is the value of `org-log-into-drawer'. However, if the
  1848. current entry has or inherits a LOG_INTO_DRAWER property, it will
  1849. be used instead of the default value."
  1850. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  1851. (cond ((equal p "nil") nil)
  1852. ((equal p "t") "LOGBOOK")
  1853. ((stringp p) p)
  1854. (p "LOGBOOK")
  1855. ((stringp org-log-into-drawer) org-log-into-drawer)
  1856. (org-log-into-drawer "LOGBOOK"))))
  1857. (defcustom org-log-state-notes-insert-after-drawers nil
  1858. "Non-nil means insert state change notes after any drawers in entry.
  1859. Only the drawers that *immediately* follow the headline and the
  1860. deadline/scheduled line are skipped.
  1861. When nil, insert notes right after the heading and perhaps the line
  1862. with deadline/scheduling if present.
  1863. This variable will have no effect if `org-log-into-drawer' is
  1864. set."
  1865. :group 'org-todo
  1866. :group 'org-progress
  1867. :type 'boolean)
  1868. (defcustom org-log-states-order-reversed t
  1869. "Non-nil means the latest state note will be directly after heading.
  1870. When nil, the state change notes will be ordered according to time.
  1871. This option can also be set with on a per-file-basis with
  1872. #+STARTUP: logstatesreversed
  1873. #+STARTUP: nologstatesreversed"
  1874. :group 'org-todo
  1875. :group 'org-progress
  1876. :type 'boolean)
  1877. (defcustom org-todo-repeat-to-state nil
  1878. "The TODO state to which a repeater should return the repeating task.
  1879. By default this is the first task of a TODO sequence or the
  1880. previous state of a TYPE_TODO set. But you can specify to use
  1881. the previous state in a TODO sequence or a string.
  1882. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  1883. entry, which has precedence over this option."
  1884. :group 'org-todo
  1885. :version "24.1"
  1886. :type '(choice (const :tag "Use the previous TODO state" t)
  1887. (const :tag "Use the head of the TODO sequence" nil)
  1888. (string :tag "Use a specific TODO state")))
  1889. (defcustom org-log-repeat 'time
  1890. "Non-nil means record moving through the DONE state when triggering repeat.
  1891. An auto-repeating task is immediately switched back to TODO when
  1892. marked DONE. If you are not logging state changes (by adding \"@\"
  1893. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  1894. record a closing note, there will be no record of the task moving
  1895. through DONE. This variable forces taking a note anyway.
  1896. nil Don't force a record
  1897. time Record a time stamp
  1898. note Prompt for a note and add it with template `org-log-note-headings'
  1899. This option can also be set with on a per-file-basis with
  1900. #+STARTUP: nologrepeat
  1901. #+STARTUP: logrepeat
  1902. #+STARTUP: lognoterepeat
  1903. You can have local logging settings for a subtree by setting the LOGGING
  1904. property to one or more of these keywords."
  1905. :group 'org-todo
  1906. :group 'org-progress
  1907. :type '(choice
  1908. (const :tag "Don't force a record" nil)
  1909. (const :tag "Force recording the DONE state" time)
  1910. (const :tag "Force recording a note with the DONE state" note)))
  1911. (defcustom org-todo-repeat-hook nil
  1912. "Hook that is run after a task has been repeated."
  1913. :package-version '(Org . "9.2")
  1914. :group 'org-todo
  1915. :type 'hook)
  1916. (defgroup org-priorities nil
  1917. "Priorities in Org mode."
  1918. :tag "Org Priorities"
  1919. :group 'org-todo)
  1920. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  1921. (defcustom org-priority-enable-commands t
  1922. "Non-nil means priority commands are active.
  1923. When nil, these commands will be disabled, so that you never accidentally
  1924. set a priority."
  1925. :group 'org-priorities
  1926. :type 'boolean)
  1927. (defvaralias 'org-highest-priority 'org-priority-highest)
  1928. (defcustom org-priority-highest ?A
  1929. "The highest priority of TODO items.
  1930. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  1931. The default is the character ?A, which is 65 as a numeric value.
  1932. If you set `org-priority-highest' to a numeric value inferior to
  1933. 65, Org assumes you want to use digits for the priority cookie.
  1934. If you set it to >=65, Org assumes you want to use alphabetical
  1935. characters.
  1936. In both cases, the value of `org-priority-highest' must be
  1937. smaller than `org-priority-lowest': for example, if \"A\" is the
  1938. highest priority, it is smaller than the lowest \"C\" priority:
  1939. 65 < 67."
  1940. :group 'org-priorities
  1941. :type '(choice
  1942. (character :tag "Character")
  1943. (integer :tag "Integer (< 65)")))
  1944. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  1945. (defcustom org-priority-lowest ?C
  1946. "The lowest priority of TODO items.
  1947. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  1948. The default is the character ?C, which is 67 as a numeric value.
  1949. If you set `org-priority-lowest' to a numeric value inferior to
  1950. 65, Org assumes you want to use digits for the priority cookie.
  1951. If you set it to >=65, Org assumes you want to use alphabetical
  1952. characters.
  1953. In both cases, the value of `org-priority-lowest' must be greater
  1954. than `org-priority-highest': for example, if \"C\" is the lowest
  1955. priority, it is greater than the highest \"A\" priority: 67 >
  1956. 65."
  1957. :group 'org-priorities
  1958. :type '(choice
  1959. (character :tag "Character")
  1960. (integer :tag "Integer (< 65)")))
  1961. (defvaralias 'org-default-priority 'org-priority-default)
  1962. (defcustom org-priority-default ?B
  1963. "The default priority of TODO items.
  1964. This is the priority an item gets if no explicit priority is given.
  1965. When starting to cycle on an empty priority the first step in the cycle
  1966. depends on `org-priority-start-cycle-with-default'. The resulting first
  1967. step priority must not exceed the range from `org-priority-highest' to
  1968. `org-priority-lowest' which means that `org-priority-default' has to be
  1969. in this range exclusive or inclusive to the range boundaries. Else the
  1970. first step refuses to set the default and the second will fall back on
  1971. \(depending on the command used) the highest or lowest priority."
  1972. :group 'org-priorities
  1973. :type '(choice
  1974. (character :tag "Character")
  1975. (integer :tag "Integer (< 65)")))
  1976. (defcustom org-priority-start-cycle-with-default t
  1977. "Non-nil means start with default priority when starting to cycle.
  1978. When this is nil, the first step in the cycle will be (depending on the
  1979. command used) one higher or lower than the default priority.
  1980. See also `org-priority-default'."
  1981. :group 'org-priorities
  1982. :type 'boolean)
  1983. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  1984. (defcustom org-priority-get-priority-function nil
  1985. "Function to extract the priority from a string.
  1986. The string is normally the headline. If this is nil, Org
  1987. computes the priority from the priority cookie like [#A] in the
  1988. headline. It returns an integer, increasing by 1000 for each
  1989. priority level.
  1990. The user can set a different function here, which should take a
  1991. string as an argument and return the numeric priority."
  1992. :group 'org-priorities
  1993. :version "24.1"
  1994. :type '(choice
  1995. (const nil)
  1996. (function)))
  1997. (defgroup org-time nil
  1998. "Options concerning time stamps and deadlines in Org mode."
  1999. :tag "Org Time"
  2000. :group 'org)
  2001. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2002. "Number of minutes to round time stamps to.
  2003. \\<org-mode-map>\
  2004. These are two values, the first applies when first creating a time stamp.
  2005. The second applies when changing it with the commands `S-up' and `S-down'.
  2006. When changing the time stamp, this means that it will change in steps
  2007. of N minutes, as given by the second value.
  2008. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2009. numbers should be factors of 60, so for example 5, 10, 15.
  2010. When this is larger than 1, you can still force an exact time stamp by using
  2011. a double prefix argument to a time stamp command like \
  2012. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2013. and by using a prefix arg to `S-up/down' to specify the exact number
  2014. of minutes to shift."
  2015. :group 'org-time
  2016. :get (lambda (var) ; Make sure both elements are there
  2017. (if (integerp (default-value var))
  2018. (list (default-value var) 5)
  2019. (default-value var)))
  2020. :type '(list
  2021. (integer :tag "when inserting times")
  2022. (integer :tag "when modifying times")))
  2023. ;; Normalize old customizations of this variable.
  2024. (when (integerp org-time-stamp-rounding-minutes)
  2025. (setq org-time-stamp-rounding-minutes
  2026. (list org-time-stamp-rounding-minutes
  2027. org-time-stamp-rounding-minutes)))
  2028. (defcustom org-display-custom-times nil
  2029. "Non-nil means overlay custom formats over all time stamps.
  2030. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2031. To turn this on on a per-file basis, insert anywhere in the file:
  2032. #+STARTUP: customtime"
  2033. :group 'org-time
  2034. :type 'sexp)
  2035. (make-variable-buffer-local 'org-display-custom-times)
  2036. (defcustom org-time-stamp-custom-formats
  2037. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2038. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2039. These are overlaid over the default ISO format if the variable
  2040. `org-display-custom-times' is set. Time like %H:%M should be at the
  2041. end of the second format. The custom formats are also honored by export
  2042. commands, if custom time display is turned on at the time of export."
  2043. :group 'org-time
  2044. :type 'sexp)
  2045. (defun org-time-stamp-format (&optional long inactive)
  2046. "Get the right format for a time string."
  2047. (let ((f (if long (cdr org-time-stamp-formats)
  2048. (car org-time-stamp-formats))))
  2049. (if inactive
  2050. (concat "[" (substring f 1 -1) "]")
  2051. f)))
  2052. (defcustom org-deadline-warning-days 14
  2053. "Number of days before expiration during which a deadline becomes active.
  2054. This variable governs the display in sparse trees and in the agenda.
  2055. When 0 or negative, it means use this number (the absolute value of it)
  2056. even if a deadline has a different individual lead time specified.
  2057. Custom commands can set this variable in the options section."
  2058. :group 'org-time
  2059. :group 'org-agenda-daily/weekly
  2060. :type 'integer)
  2061. (defcustom org-scheduled-delay-days 0
  2062. "Number of days before a scheduled item becomes active.
  2063. This variable governs the display in sparse trees and in the agenda.
  2064. The default value (i.e. 0) means: don't delay scheduled item.
  2065. When negative, it means use this number (the absolute value of it)
  2066. even if a scheduled item has a different individual delay time
  2067. specified.
  2068. Custom commands can set this variable in the options section."
  2069. :group 'org-time
  2070. :group 'org-agenda-daily/weekly
  2071. :version "24.4"
  2072. :package-version '(Org . "8.0")
  2073. :type 'integer)
  2074. (defcustom org-read-date-prefer-future t
  2075. "Non-nil means assume future for incomplete date input from user.
  2076. This affects the following situations:
  2077. 1. The user gives a month but not a year.
  2078. For example, if it is April and you enter \"feb 2\", this will be read
  2079. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2080. 2. The user gives a day, but no month.
  2081. For example, if today is the 15th, and you enter \"3\", Org will read
  2082. this as the third of *next* month. However, if you enter \"17\",
  2083. it will be considered as *this* month.
  2084. If you set this variable to the symbol `time', then also the following
  2085. will work:
  2086. 3. If the user gives a time.
  2087. If the time is before now, it will be interpreted as tomorrow.
  2088. Currently none of this works for ISO week specifications.
  2089. When this option is nil, the current day, month and year will always be
  2090. used as defaults.
  2091. See also `org-agenda-jump-prefer-future'."
  2092. :group 'org-time
  2093. :type '(choice
  2094. (const :tag "Never" nil)
  2095. (const :tag "Check month and day" t)
  2096. (const :tag "Check month, day, and time" time)))
  2097. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2098. "Should the agenda jump command prefer the future for incomplete dates?
  2099. The default is to do the same as configured in `org-read-date-prefer-future'.
  2100. But you can also set a deviating value here.
  2101. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2102. :group 'org-agenda
  2103. :group 'org-time
  2104. :version "24.1"
  2105. :type '(choice
  2106. (const :tag "Use org-read-date-prefer-future"
  2107. org-read-date-prefer-future)
  2108. (const :tag "Never" nil)
  2109. (const :tag "Always" t)))
  2110. (defcustom org-read-date-force-compatible-dates t
  2111. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2112. Depending on the system Emacs is running on, certain dates cannot
  2113. be represented with the type used internally to represent time.
  2114. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2115. correctly. Some systems allow for earlier dates, some for later,
  2116. some for both. One way to find out is to insert any date into an
  2117. Org buffer, putting the cursor on the year and hitting S-up and
  2118. S-down to test the range.
  2119. When this variable is set to t, the date/time prompt will not let
  2120. you specify dates outside the 1970-2037 range, so it is certain that
  2121. these dates will work in whatever version of Emacs you are
  2122. running, and also that you can move a file from one Emacs implementation
  2123. to another. Whenever Org is forcing the year for you, it will display
  2124. a message and beep.
  2125. When this variable is nil, Org will check if the date is
  2126. representable in the specific Emacs implementation you are using.
  2127. If not, it will force a year, usually the current year, and beep
  2128. to remind you. Currently this setting is not recommended because
  2129. the likelihood that you will open your Org files in an Emacs that
  2130. has limited date range is not negligible.
  2131. A workaround for this problem is to use diary sexp dates for time
  2132. stamps outside of this range."
  2133. :group 'org-time
  2134. :version "24.1"
  2135. :type 'boolean)
  2136. (defcustom org-read-date-display-live t
  2137. "Non-nil means display current interpretation of date prompt live.
  2138. This display will be in an overlay, in the minibuffer. Note that
  2139. live display is only active when `org-read-date-popup-calendar'
  2140. is non-nil."
  2141. :group 'org-time
  2142. :type 'boolean)
  2143. (defvaralias 'org-popup-calendar-for-date-prompt
  2144. 'org-read-date-popup-calendar)
  2145. (defcustom org-read-date-popup-calendar t
  2146. "Non-nil means pop up a calendar when prompting for a date.
  2147. In the calendar, the date can be selected with mouse-1. However, the
  2148. minibuffer will also be active, and you can simply enter the date as well.
  2149. When nil, only the minibuffer will be available."
  2150. :group 'org-time
  2151. :type 'boolean)
  2152. (defcustom org-extend-today-until 0
  2153. "The hour when your day really ends. Must be an integer.
  2154. This has influence for the following applications:
  2155. - When switching the agenda to \"today\". If it is still earlier than
  2156. the time given here, the day recognized as TODAY is actually yesterday.
  2157. - When a date is read from the user and it is still before the time given
  2158. here, the current date and time will be assumed to be yesterday, 23:59.
  2159. Also, timestamps inserted in capture templates follow this rule.
  2160. IMPORTANT: This is a feature whose implementation is and likely will
  2161. remain incomplete. Really, it is only here because past midnight seems to
  2162. be the favorite working time of John Wiegley :-)"
  2163. :group 'org-time
  2164. :type 'integer)
  2165. (defcustom org-use-effective-time nil
  2166. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2167. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2168. \"effective time\" of any timestamps between midnight and 8am will be
  2169. 23:59 of the previous day."
  2170. :group 'org-time
  2171. :version "24.1"
  2172. :type 'boolean)
  2173. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2174. "When non-nil, use the last clock out time for `org-todo'.
  2175. Note that this option has precedence over the combined use of
  2176. `org-use-effective-time' and `org-extend-today-until'."
  2177. :group 'org-time
  2178. :version "24.4"
  2179. :package-version '(Org . "8.0")
  2180. :type 'boolean)
  2181. (defcustom org-edit-timestamp-down-means-later nil
  2182. "Non-nil means S-down will increase the time in a time stamp.
  2183. When nil, S-up will increase."
  2184. :group 'org-time
  2185. :type 'boolean)
  2186. (defcustom org-calendar-follow-timestamp-change t
  2187. "Non-nil means make the calendar window follow timestamp changes.
  2188. When a timestamp is modified and the calendar window is visible, it will be
  2189. moved to the new date."
  2190. :group 'org-time
  2191. :type 'boolean)
  2192. (defgroup org-tags nil
  2193. "Options concerning tags in Org mode."
  2194. :tag "Org Tags"
  2195. :group 'org)
  2196. (defcustom org-tag-alist nil
  2197. "Default tags available in Org files.
  2198. The value of this variable is an alist. Associations either:
  2199. (TAG)
  2200. (TAG . SELECT)
  2201. (SPECIAL)
  2202. where TAG is a tag as a string, SELECT is character, used to
  2203. select that tag through the fast tag selection interface, and
  2204. SPECIAL is one of the following keywords: `:startgroup',
  2205. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2206. `:newline'. These keywords are used to define a hierarchy of
  2207. tags. See manual for details.
  2208. When this variable is nil, Org mode bases tag input on what is
  2209. already in the buffer. The value can be overridden locally by
  2210. using a TAGS keyword, e.g.,
  2211. #+TAGS: tag1 tag2
  2212. See also `org-tag-persistent-alist' to sidestep this behavior."
  2213. :group 'org-tags
  2214. :type '(repeat
  2215. (choice
  2216. (cons :tag "Tag with key"
  2217. (string :tag "Tag name")
  2218. (character :tag "Access char"))
  2219. (list :tag "Tag" (string :tag "Tag name"))
  2220. (const :tag "Start radio group" (:startgroup))
  2221. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2222. (const :tag "Group tags delimiter" (:grouptags))
  2223. (const :tag "End radio group" (:endgroup))
  2224. (const :tag "End tag group, non distinct" (:endgrouptag))
  2225. (const :tag "New line" (:newline)))))
  2226. (defcustom org-tag-persistent-alist nil
  2227. "Tags always available in Org files.
  2228. The value of this variable is an alist. Associations either:
  2229. (TAG)
  2230. (TAG . SELECT)
  2231. (SPECIAL)
  2232. where TAG is a tag as a string, SELECT is a character, used to
  2233. select that tag through the fast tag selection interface, and
  2234. SPECIAL is one of the following keywords: `:startgroup',
  2235. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2236. `:newline'. These keywords are used to define a hierarchy of
  2237. tags. See manual for details.
  2238. Unlike to `org-tag-alist', tags defined in this variable do not
  2239. depend on a local TAGS keyword. Instead, to disable these tags
  2240. on a per-file basis, insert anywhere in the file:
  2241. #+STARTUP: noptag"
  2242. :group 'org-tags
  2243. :type '(repeat
  2244. (choice
  2245. (cons :tag "Tag with key"
  2246. (string :tag "Tag name")
  2247. (character :tag "Access char"))
  2248. (list :tag "Tag" (string :tag "Tag name"))
  2249. (const :tag "Start radio group" (:startgroup))
  2250. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2251. (const :tag "Group tags delimiter" (:grouptags))
  2252. (const :tag "End radio group" (:endgroup))
  2253. (const :tag "End tag group, non distinct" (:endgrouptag))
  2254. (const :tag "New line" (:newline)))))
  2255. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2256. "If non-nil, always offer completion for all tags of all agenda files.
  2257. Setting this variable locally allows for dynamic generation of tag
  2258. completions in capture buffers.
  2259. (add-hook \\='org-capture-mode-hook
  2260. (lambda ()
  2261. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2262. :group 'org-tags
  2263. :version "24.1"
  2264. :type 'boolean)
  2265. (defvar org-file-tags nil
  2266. "List of tags that can be inherited by all entries in the file.
  2267. The tags will be inherited if the variable `org-use-tag-inheritance'
  2268. says they should be.
  2269. This variable is populated from #+FILETAGS lines.")
  2270. (defcustom org-use-fast-tag-selection 'auto
  2271. "Non-nil means use fast tag selection scheme.
  2272. This is a special interface to select and deselect tags with single keys.
  2273. When nil, fast selection is never used.
  2274. When the symbol `auto', fast selection is used if and only if selection
  2275. characters for tags have been configured, either through the variable
  2276. `org-tag-alist' or through a #+TAGS line in the buffer.
  2277. When t, fast selection is always used and selection keys are assigned
  2278. automatically if necessary."
  2279. :group 'org-tags
  2280. :type '(choice
  2281. (const :tag "Always" t)
  2282. (const :tag "Never" nil)
  2283. (const :tag "When selection characters are configured" auto)))
  2284. (defcustom org-fast-tag-selection-single-key nil
  2285. "Non-nil means fast tag selection exits after first change.
  2286. When nil, you have to press RET to exit it.
  2287. During fast tag selection, you can toggle this flag with `C-c'.
  2288. This variable can also have the value `expert'. In this case, the window
  2289. displaying the tags menu is not even shown, until you press `C-c' again."
  2290. :group 'org-tags
  2291. :type '(choice
  2292. (const :tag "No" nil)
  2293. (const :tag "Yes" t)
  2294. (const :tag "Expert" expert)))
  2295. (defvar org-fast-tag-selection-include-todo nil
  2296. "Non-nil means fast tags selection interface will also offer TODO states.
  2297. This is an undocumented feature, you should not rely on it.")
  2298. (defcustom org-tags-column -77
  2299. "The column to which tags should be indented in a headline.
  2300. If this number is positive, it specifies the column. If it is negative,
  2301. it means that the tags should be flushright to that column. For example,
  2302. -80 works well for a normal 80 character screen.
  2303. When 0, place tags directly after headline text, with only one space in
  2304. between."
  2305. :group 'org-tags
  2306. :type 'integer)
  2307. (defcustom org-auto-align-tags t
  2308. "Non-nil keeps tags aligned when modifying headlines.
  2309. Some operations (i.e. demoting) change the length of a headline and
  2310. therefore shift the tags around. With this option turned on, after
  2311. each such operation the tags are again aligned to `org-tags-column'."
  2312. :group 'org-tags
  2313. :type 'boolean)
  2314. (defcustom org-use-tag-inheritance t
  2315. "Non-nil means tags in levels apply also for sublevels.
  2316. When nil, only the tags directly given in a specific line apply there.
  2317. This may also be a list of tags that should be inherited, or a regexp that
  2318. matches tags that should be inherited. Additional control is possible
  2319. with the variable `org-tags-exclude-from-inheritance' which gives an
  2320. explicit list of tags to be excluded from inheritance, even if the value of
  2321. `org-use-tag-inheritance' would select it for inheritance.
  2322. If this option is t, a match early-on in a tree can lead to a large
  2323. number of matches in the subtree when constructing the agenda or creating
  2324. a sparse tree. If you only want to see the first match in a tree during
  2325. a search, check out the variable `org-tags-match-list-sublevels'."
  2326. :group 'org-tags
  2327. :type '(choice
  2328. (const :tag "Not" nil)
  2329. (const :tag "Always" t)
  2330. (repeat :tag "Specific tags" (string :tag "Tag"))
  2331. (regexp :tag "Tags matched by regexp")))
  2332. (defcustom org-tags-exclude-from-inheritance nil
  2333. "List of tags that should never be inherited.
  2334. This is a way to exclude a few tags from inheritance. For way to do
  2335. the opposite, to actively allow inheritance for selected tags,
  2336. see the variable `org-use-tag-inheritance'."
  2337. :group 'org-tags
  2338. :type '(repeat (string :tag "Tag")))
  2339. (defun org-tag-inherit-p (tag)
  2340. "Check if TAG is one that should be inherited."
  2341. (cond
  2342. ((member tag org-tags-exclude-from-inheritance) nil)
  2343. ((eq org-use-tag-inheritance t) t)
  2344. ((not org-use-tag-inheritance) nil)
  2345. ((stringp org-use-tag-inheritance)
  2346. (string-match org-use-tag-inheritance tag))
  2347. ((listp org-use-tag-inheritance)
  2348. (member tag org-use-tag-inheritance))
  2349. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2350. (defcustom org-tags-match-list-sublevels t
  2351. "Non-nil means list also sublevels of headlines matching a search.
  2352. This variable applies to tags/property searches, and also to stuck
  2353. projects because this search is based on a tags match as well.
  2354. When set to the symbol `indented', sublevels are indented with
  2355. leading dots.
  2356. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2357. the sublevels of a headline matching a tag search often also match
  2358. the same search. Listing all of them can create very long lists.
  2359. Setting this variable to nil causes subtrees of a match to be skipped.
  2360. This variable is semi-obsolete and probably should always be true. It
  2361. is better to limit inheritance to certain tags using the variables
  2362. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2363. :group 'org-tags
  2364. :type '(choice
  2365. (const :tag "No, don't list them" nil)
  2366. (const :tag "Yes, do list them" t)
  2367. (const :tag "List them, indented with leading dots" indented)))
  2368. (defcustom org-tags-sort-function nil
  2369. "When set, tags are sorted using this function as a comparator."
  2370. :group 'org-tags
  2371. :type '(choice
  2372. (const :tag "No sorting" nil)
  2373. (const :tag "Alphabetical" string-collate-lessp)
  2374. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2375. (function :tag "Custom function" nil)))
  2376. (defvar org-tags-history nil
  2377. "History of minibuffer reads for tags.")
  2378. (defvar org-last-tags-completion-table nil
  2379. "The last used completion table for tags.")
  2380. (defvar org-after-tags-change-hook nil
  2381. "Hook that is run after the tags in a line have changed.")
  2382. (defgroup org-properties nil
  2383. "Options concerning properties in Org mode."
  2384. :tag "Org Properties"
  2385. :group 'org)
  2386. (defcustom org-property-format "%-10s %s"
  2387. "How property key/value pairs should be formatted by `indent-line'.
  2388. When `indent-line' hits a property definition, it will format the line
  2389. according to this format, mainly to make sure that the values are
  2390. lined-up with respect to each other."
  2391. :group 'org-properties
  2392. :type 'string)
  2393. (defcustom org-properties-postprocess-alist nil
  2394. "Alist of properties and functions to adjust inserted values.
  2395. Elements of this alist must be of the form
  2396. ([string] [function])
  2397. where [string] must be a property name and [function] must be a
  2398. lambda expression: this lambda expression must take one argument,
  2399. the value to adjust, and return the new value as a string.
  2400. For example, this element will allow the property \"Remaining\"
  2401. to be updated wrt the relation between the \"Effort\" property
  2402. and the clock summary:
  2403. ((\"Remaining\" (lambda(value)
  2404. (let ((clocksum (org-clock-sum-current-item))
  2405. (effort (org-duration-to-minutes
  2406. (org-entry-get (point) \"Effort\"))))
  2407. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2408. :group 'org-properties
  2409. :version "24.1"
  2410. :type '(alist :key-type (string :tag "Property")
  2411. :value-type (function :tag "Function")))
  2412. (defcustom org-use-property-inheritance nil
  2413. "Non-nil means properties apply also for sublevels.
  2414. This setting is chiefly used during property searches. Turning it on can
  2415. cause significant overhead when doing a search, which is why it is not
  2416. on by default.
  2417. When nil, only the properties directly given in the current entry count.
  2418. When t, every property is inherited. The value may also be a list of
  2419. properties that should have inheritance, or a regular expression matching
  2420. properties that should be inherited.
  2421. However, note that some special properties use inheritance under special
  2422. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2423. and the properties ending in \"_ALL\" when they are used as descriptor
  2424. for valid values of a property.
  2425. Note for programmers:
  2426. When querying an entry with `org-entry-get', you can control if inheritance
  2427. should be used. By default, `org-entry-get' looks only at the local
  2428. properties. You can request inheritance by setting the inherit argument
  2429. to t (to force inheritance) or to `selective' (to respect the setting
  2430. in this variable)."
  2431. :group 'org-properties
  2432. :type '(choice
  2433. (const :tag "Not" nil)
  2434. (const :tag "Always" t)
  2435. (repeat :tag "Specific properties" (string :tag "Property"))
  2436. (regexp :tag "Properties matched by regexp")))
  2437. (defun org-property-inherit-p (property)
  2438. "Return a non-nil value if PROPERTY should be inherited."
  2439. (cond
  2440. ((eq org-use-property-inheritance t) t)
  2441. ((not org-use-property-inheritance) nil)
  2442. ((stringp org-use-property-inheritance)
  2443. (string-match org-use-property-inheritance property))
  2444. ((listp org-use-property-inheritance)
  2445. (member-ignore-case property org-use-property-inheritance))
  2446. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2447. (defcustom org-property-separators nil
  2448. "An alist to control how properties are combined.
  2449. The car of each item should be either a list of property names or
  2450. a regular expression, while the cdr should be the separator to
  2451. use when combining that property.
  2452. If an alist item cannot be found that matches a given property, a
  2453. single space will be used as the separator."
  2454. :group 'org-properties
  2455. :type '(alist :key-type (choice (repeat :tag "Properties" string)
  2456. (string :tag "Regular Expression"))
  2457. :value-type (restricted-sexp :tag "Separator"
  2458. :match-alternatives (stringp)
  2459. :value " ")))
  2460. (defun org--property-get-separator (property)
  2461. "Get the separator to use for combining PROPERTY."
  2462. (or
  2463. (catch 'separator
  2464. (dolist (spec org-property-separators)
  2465. (if (listp (car spec))
  2466. (if (member property (car spec))
  2467. (throw 'separator (cdr spec)))
  2468. (if (string-match-p (car spec) property)
  2469. (throw 'separator (cdr spec))))))
  2470. " "))
  2471. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2472. "The default column format, if no other format has been defined.
  2473. This variable can be set on the per-file basis by inserting a line
  2474. #+COLUMNS: %25ITEM ....."
  2475. :group 'org-properties
  2476. :type 'string)
  2477. (defcustom org-columns-default-format-for-agenda nil
  2478. "The default column format in an agenda buffer.
  2479. This will be used for column view in the agenda unless a format has
  2480. been set by adding `org-overriding-columns-format' to the local
  2481. settings list of a custom agenda view. When nil, the columns format
  2482. for the first item in the agenda list will be used, or as a fall-back,
  2483. `org-columns-default-format'."
  2484. :group 'org-properties
  2485. :type '(choice
  2486. (const :tag "No default" nil)
  2487. (string :tag "Format string")))
  2488. (defcustom org-columns-ellipses ".."
  2489. "The ellipses to be used when a field in column view is truncated.
  2490. When this is the empty string, as many characters as possible are shown,
  2491. but then there will be no visual indication that the field has been truncated.
  2492. When this is a string of length N, the last N characters of a truncated
  2493. field are replaced by this string. If the column is narrower than the
  2494. ellipses string, only part of the ellipses string will be shown."
  2495. :group 'org-properties
  2496. :type 'string)
  2497. (defconst org-global-properties-fixed
  2498. '(("VISIBILITY_ALL" . "folded children content all")
  2499. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2500. "List of property/value pairs that can be inherited by any entry.
  2501. These are fixed values, for the preset properties. The user variable
  2502. that can be used to add to this list is `org-global-properties'.
  2503. The entries in this list are cons cells where the car is a property
  2504. name and cdr is a string with the value. If the value represents
  2505. multiple items like an \"_ALL\" property, separate the items by
  2506. spaces.")
  2507. (defcustom org-global-properties nil
  2508. "List of property/value pairs that can be inherited by any entry.
  2509. This list will be combined with the constant `org-global-properties-fixed'.
  2510. The entries in this list are cons cells where the car is a property
  2511. name and cdr is a string with the value.
  2512. Buffer local properties are added either by a document property drawer
  2513. :PROPERTIES:
  2514. :NAME: VALUE
  2515. :END:
  2516. or by adding lines like
  2517. #+PROPERTY: NAME VALUE"
  2518. :group 'org-properties
  2519. :type '(repeat
  2520. (cons (string :tag "Property")
  2521. (string :tag "Value"))))
  2522. (defvar-local org-keyword-properties nil
  2523. "List of property/value pairs inherited by any entry.
  2524. Valid for the current buffer. This variable is populated from
  2525. PROPERTY keywords.
  2526. Note that properties are defined also in property drawers.
  2527. Properties defined there take precedence over properties defined
  2528. as keywords.")
  2529. (defgroup org-agenda nil
  2530. "Options concerning agenda views in Org mode."
  2531. :tag "Org Agenda"
  2532. :group 'org)
  2533. (defvar-local org-category nil
  2534. "Variable used by Org files to set a category for agenda display.
  2535. There are multiple ways to set the category. One way is to set
  2536. it in the document property drawer. For example:
  2537. :PROPERTIES:
  2538. :CATEGORY: ELisp
  2539. :END:
  2540. Other ways to define it is as an Emacs file variable, for example
  2541. # -*- mode: org; org-category: \"ELisp\"
  2542. or for the file to contain a special line:
  2543. #+CATEGORY: ELisp
  2544. If the file does not specify a category, then file's base name
  2545. is used instead.")
  2546. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2547. (defcustom org-agenda-files nil
  2548. "The files to be used for agenda display.
  2549. If an entry is a directory, all files in that directory that are matched
  2550. by `org-agenda-file-regexp' will be part of the file list.
  2551. If the value of the variable is not a list but a single file name, then
  2552. the list of agenda files is actually stored and maintained in that file,
  2553. one agenda file per line. In this file paths can be given relative to
  2554. `org-directory'. Tilde expansion and environment variable substitution
  2555. are also made.
  2556. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2557. and removed with `\\[org-remove-file]'."
  2558. :group 'org-agenda
  2559. :type '(choice
  2560. (repeat :tag "List of files and directories" file)
  2561. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2562. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2563. "Regular expression to match files for `org-agenda-files'.
  2564. If any element in the list in that variable contains a directory instead
  2565. of a normal file, all files in that directory that are matched by this
  2566. regular expression will be included."
  2567. :group 'org-agenda
  2568. :type 'regexp)
  2569. (defvaralias 'org-agenda-multi-occur-extra-files
  2570. 'org-agenda-text-search-extra-files)
  2571. (defcustom org-agenda-text-search-extra-files nil
  2572. "List of extra files to be searched by text search commands.
  2573. These files will be searched in addition to the agenda files by the
  2574. commands `org-search-view' (`\\[org-agenda] s') \
  2575. and `org-occur-in-agenda-files'.
  2576. Note that these files will only be searched for text search commands,
  2577. not for the other agenda views like todo lists, tag searches or the weekly
  2578. agenda. This variable is intended to list notes and possibly archive files
  2579. that should also be searched by these two commands.
  2580. In fact, if the first element in the list is the symbol `agenda-archives',
  2581. then all archive files of all agenda files will be added to the search
  2582. scope."
  2583. :group 'org-agenda
  2584. :type '(set :greedy t
  2585. (const :tag "Agenda Archives" agenda-archives)
  2586. (repeat :inline t (file))))
  2587. (defcustom org-agenda-skip-unavailable-files nil
  2588. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2589. A nil value means to remove them, after a query, from the list."
  2590. :group 'org-agenda
  2591. :type 'boolean)
  2592. (defgroup org-latex nil
  2593. "Options for embedding LaTeX code into Org mode."
  2594. :tag "Org LaTeX"
  2595. :group 'org)
  2596. (defcustom org-format-latex-options
  2597. '(:foreground default :background default :scale 1.0
  2598. :html-foreground "Black" :html-background "Transparent"
  2599. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2600. "Options for creating images from LaTeX fragments.
  2601. This is a property list with the following properties:
  2602. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2603. `default' means use the foreground of the default face.
  2604. `auto' means use the foreground from the text face.
  2605. :background the background color, or \"Transparent\".
  2606. `default' means use the background of the default face.
  2607. `auto' means use the background from the text face.
  2608. :scale a scaling factor for the size of the images, to get more pixels
  2609. :html-foreground, :html-background, :html-scale
  2610. the same numbers for HTML export.
  2611. :matchers a list indicating which matchers should be used to
  2612. find LaTeX fragments. Valid members of this list are:
  2613. \"begin\" find environments
  2614. \"$1\" find single characters surrounded by $.$
  2615. \"$\" find math expressions surrounded by $...$
  2616. \"$$\" find math expressions surrounded by $$....$$
  2617. \"\\(\" find math expressions surrounded by \\(...\\)
  2618. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2619. :group 'org-latex
  2620. :type 'plist)
  2621. (defcustom org-format-latex-signal-error t
  2622. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2623. When nil, just push out a message."
  2624. :group 'org-latex
  2625. :version "24.1"
  2626. :type 'boolean)
  2627. (defcustom org-latex-to-mathml-jar-file nil
  2628. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2629. Use this to specify additional executable file say a jar file.
  2630. When using MathToWeb as the converter, specify the full-path to
  2631. your mathtoweb.jar file."
  2632. :group 'org-latex
  2633. :version "24.1"
  2634. :type '(choice
  2635. (const :tag "None" nil)
  2636. (file :tag "JAR file" :must-match t)))
  2637. (defcustom org-latex-to-mathml-convert-command nil
  2638. "Command to convert LaTeX fragments to MathML.
  2639. Replace format-specifiers in the command as noted below and use
  2640. `shell-command' to convert LaTeX to MathML.
  2641. %j: Executable file in fully expanded form as specified by
  2642. `org-latex-to-mathml-jar-file'.
  2643. %I: Input LaTeX file in fully expanded form.
  2644. %i: The latex fragment to be converted.
  2645. %o: Output MathML file.
  2646. This command is used by `org-create-math-formula'.
  2647. When using MathToWeb as the converter, set this option to
  2648. \"java -jar %j -unicode -force -df %o %I\".
  2649. When using LaTeXML set this option to
  2650. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2651. :group 'org-latex
  2652. :version "24.1"
  2653. :type '(choice
  2654. (const :tag "None" nil)
  2655. (string :tag "\nShell command")))
  2656. (defcustom org-latex-to-html-convert-command nil
  2657. "Command to convert LaTeX fragments to HTML.
  2658. This command is very open-ended: the output of the command will
  2659. directly replace the LaTeX fragment in the resulting HTML.
  2660. Replace format-specifiers in the command as noted below and use
  2661. `shell-command' to convert LaTeX to HTML.
  2662. %i: The LaTeX fragment to be converted.
  2663. For example, this could be used with LaTeXML as
  2664. \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2665. :group 'org-latex
  2666. :package-version '(Org . "9.4")
  2667. :type '(choice
  2668. (const :tag "None" nil)
  2669. (string :tag "Shell command")))
  2670. (defcustom org-preview-latex-default-process 'dvipng
  2671. "The default process to convert LaTeX fragments to image files.
  2672. All available processes and theirs documents can be found in
  2673. `org-preview-latex-process-alist', which see."
  2674. :group 'org-latex
  2675. :version "26.1"
  2676. :package-version '(Org . "9.0")
  2677. :type 'symbol)
  2678. (defcustom org-preview-latex-process-alist
  2679. '((dvipng
  2680. :programs ("latex" "dvipng")
  2681. :description "dvi > png"
  2682. :message "you need to install the programs: latex and dvipng."
  2683. :image-input-type "dvi"
  2684. :image-output-type "png"
  2685. :image-size-adjust (1.0 . 1.0)
  2686. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2687. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2688. :transparent-image-converter
  2689. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2690. (dvisvgm
  2691. :programs ("latex" "dvisvgm")
  2692. :description "dvi > svg"
  2693. :message "you need to install the programs: latex and dvisvgm."
  2694. :image-input-type "dvi"
  2695. :image-output-type "svg"
  2696. :image-size-adjust (1.7 . 1.5)
  2697. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2698. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2699. (imagemagick
  2700. :programs ("latex" "convert")
  2701. :description "pdf > png"
  2702. :message "you need to install the programs: latex and imagemagick."
  2703. :image-input-type "pdf"
  2704. :image-output-type "png"
  2705. :image-size-adjust (1.0 . 1.0)
  2706. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2707. :image-converter
  2708. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2709. "Definitions of external processes for LaTeX previewing.
  2710. Org mode can use some external commands to generate TeX snippet's images for
  2711. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2712. `org-create-formula-image' how to call them.
  2713. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2714. PROPERTIES accepts the following attributes:
  2715. :programs list of strings, required programs.
  2716. :description string, describe the process.
  2717. :message string, message it when required programs cannot be found.
  2718. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2719. :image-output-type string, output file type of image converter (e.g., \"png\").
  2720. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2721. image size showed in buffer and the cdr element is for
  2722. HTML file. This option is only useful for process
  2723. developers, users should use variable
  2724. `org-format-latex-options' instead.
  2725. :post-clean list of strings, files matched are to be cleaned up once
  2726. the image is generated. When nil, the files with \".dvi\",
  2727. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2728. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2729. be cleaned up.
  2730. :latex-header list of strings, the LaTeX header of the snippet file.
  2731. When nil, the fallback value is used instead, which is
  2732. controlled by `org-format-latex-header',
  2733. `org-latex-default-packages-alist' and
  2734. `org-latex-packages-alist', which see.
  2735. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2736. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2737. replaced with values defined below.
  2738. :image-converter list of image converter commands strings. Each of them is
  2739. given to the shell and supports any of the following
  2740. place-holders defined below.
  2741. If set, :transparent-image-converter is used instead of :image-converter to
  2742. convert an image when the background color is nil or \"Transparent\".
  2743. Place-holders used by `:image-converter' and `:latex-compiler':
  2744. %f input file name
  2745. %b base name of input file
  2746. %o base directory of input file
  2747. %O absolute output file name
  2748. Place-holders only used by `:image-converter':
  2749. %D dpi, which is used to adjust image size by some processing commands.
  2750. %S the image size scale ratio, which is used to adjust image size by some
  2751. processing commands."
  2752. :group 'org-latex
  2753. :version "26.1"
  2754. :package-version '(Org . "9.0")
  2755. :type '(alist :tag "LaTeX to image backends"
  2756. :value-type (plist)))
  2757. (defcustom org-preview-latex-image-directory "ltximg/"
  2758. "Path to store latex preview images.
  2759. A relative path here creates many directories relative to the
  2760. processed Org files paths. An absolute path puts all preview
  2761. images at the same place."
  2762. :group 'org-latex
  2763. :version "26.1"
  2764. :package-version '(Org . "9.0")
  2765. :type 'string)
  2766. (defun org-format-latex-mathml-available-p ()
  2767. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2768. (save-match-data
  2769. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2770. org-latex-to-mathml-convert-command)
  2771. (let ((executable (car (split-string
  2772. org-latex-to-mathml-convert-command))))
  2773. (when (executable-find executable)
  2774. (if (string-match
  2775. "%j" org-latex-to-mathml-convert-command)
  2776. (file-readable-p org-latex-to-mathml-jar-file)
  2777. t))))))
  2778. (defcustom org-format-latex-header "\\documentclass{article}
  2779. \\usepackage[usenames]{color}
  2780. \[PACKAGES]
  2781. \[DEFAULT-PACKAGES]
  2782. \\pagestyle{empty} % do not remove
  2783. % The settings below are copied from fullpage.sty
  2784. \\setlength{\\textwidth}{\\paperwidth}
  2785. \\addtolength{\\textwidth}{-3cm}
  2786. \\setlength{\\oddsidemargin}{1.5cm}
  2787. \\addtolength{\\oddsidemargin}{-2.54cm}
  2788. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2789. \\setlength{\\textheight}{\\paperheight}
  2790. \\addtolength{\\textheight}{-\\headheight}
  2791. \\addtolength{\\textheight}{-\\headsep}
  2792. \\addtolength{\\textheight}{-\\footskip}
  2793. \\addtolength{\\textheight}{-3cm}
  2794. \\setlength{\\topmargin}{1.5cm}
  2795. \\addtolength{\\topmargin}{-2.54cm}"
  2796. "The document header used for processing LaTeX fragments.
  2797. It is imperative that this header make sure that no page number
  2798. appears on the page. The package defined in the variables
  2799. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2800. will either replace the placeholder \"[PACKAGES]\" in this
  2801. header, or they will be appended."
  2802. :group 'org-latex
  2803. :type 'string)
  2804. (defun org-set-packages-alist (var val)
  2805. "Set the packages alist and make sure it has 3 elements per entry."
  2806. (set-default-toplevel-value var (mapcar (lambda (x)
  2807. (if (and (consp x) (= (length x) 2))
  2808. (list (car x) (nth 1 x) t)
  2809. x))
  2810. val)))
  2811. (defun org-get-packages-alist (var)
  2812. "Get the packages alist and make sure it has 3 elements per entry."
  2813. (mapcar (lambda (x)
  2814. (if (and (consp x) (= (length x) 2))
  2815. (list (car x) (nth 1 x) t)
  2816. x))
  2817. (default-value var)))
  2818. (defcustom org-latex-default-packages-alist
  2819. '(("AUTO" "inputenc" t ("pdflatex"))
  2820. ("T1" "fontenc" t ("pdflatex"))
  2821. ("" "graphicx" t)
  2822. ("" "longtable" nil)
  2823. ("" "wrapfig" nil)
  2824. ("" "rotating" nil)
  2825. ("normalem" "ulem" t)
  2826. ("" "amsmath" t)
  2827. ("" "amssymb" t)
  2828. ("" "capt-of" nil)
  2829. ("" "hyperref" nil))
  2830. "Alist of default packages to be inserted in the header.
  2831. Change this only if one of the packages here causes an
  2832. incompatibility with another package you are using.
  2833. The packages in this list are needed by one part or another of
  2834. Org mode to function properly:
  2835. - inputenc, fontenc: for basic font and character selection
  2836. - graphicx: for including images
  2837. - longtable: For multipage tables
  2838. - wrapfig: for figure placement
  2839. - rotating: for sideways figures and tables
  2840. - ulem: for underline and strike-through
  2841. - amsmath: for subscript and superscript and math environments
  2842. - amssymb: for various symbols used for interpreting the entities
  2843. in `org-entities'. You can skip some of this package if you don't
  2844. use any of the symbols.
  2845. - capt-of: for captions outside of floats
  2846. - hyperref: for cross references
  2847. Therefore you should not modify this variable unless you know
  2848. what you are doing. The one reason to change it anyway is that
  2849. you might be loading some other package that conflicts with one
  2850. of the default packages. Each element is either a cell or
  2851. a string.
  2852. A cell is of the format
  2853. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2854. If SNIPPET-FLAG is non-nil, the package also needs to be included
  2855. when compiling LaTeX snippets into images for inclusion into
  2856. non-LaTeX output.
  2857. COMPILERS is a list of compilers that should include the package,
  2858. see `org-latex-compiler'. If the document compiler is not in the
  2859. list, and the list is non-nil, the package will not be inserted
  2860. in the final document.
  2861. A string will be inserted as-is in the header of the document."
  2862. :group 'org-latex
  2863. :group 'org-export-latex
  2864. :set 'org-set-packages-alist
  2865. :get 'org-get-packages-alist
  2866. :version "26.1"
  2867. :package-version '(Org . "8.3")
  2868. :type '(repeat
  2869. (choice
  2870. (list :tag "options/package pair"
  2871. (string :tag "options")
  2872. (string :tag "package")
  2873. (boolean :tag "Snippet")
  2874. (choice
  2875. (const :tag "For all compilers" nil)
  2876. (repeat :tag "Allowed compiler" string)))
  2877. (string :tag "A line of LaTeX"))))
  2878. (defcustom org-latex-packages-alist nil
  2879. "Alist of packages to be inserted in every LaTeX header.
  2880. These will be inserted after `org-latex-default-packages-alist'.
  2881. Each element is either a cell or a string.
  2882. A cell is of the format:
  2883. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  2884. SNIPPET-FLAG, when non-nil, indicates that this package is also
  2885. needed when turning LaTeX snippets into images for inclusion into
  2886. non-LaTeX output.
  2887. COMPILERS is a list of compilers that should include the package,
  2888. see `org-latex-compiler'. If the document compiler is not in the
  2889. list, and the list is non-nil, the package will not be inserted
  2890. in the final document.
  2891. A string will be inserted as-is in the header of the document.
  2892. Make sure that you only list packages here which:
  2893. - you want in every file;
  2894. - do not conflict with the setup in `org-format-latex-header';
  2895. - do not conflict with the default packages in
  2896. `org-latex-default-packages-alist'."
  2897. :group 'org-latex
  2898. :group 'org-export-latex
  2899. :set 'org-set-packages-alist
  2900. :get 'org-get-packages-alist
  2901. :type '(repeat
  2902. (choice
  2903. (list :tag "options/package pair"
  2904. (string :tag "options")
  2905. (string :tag "package")
  2906. (boolean :tag "Snippet"))
  2907. (string :tag "A line of LaTeX"))))
  2908. (defgroup org-appearance nil
  2909. "Settings for Org mode appearance."
  2910. :tag "Org Appearance"
  2911. :group 'org)
  2912. (defcustom org-level-color-stars-only nil
  2913. "Non-nil means fontify only the stars in each headline.
  2914. When nil, the entire headline is fontified.
  2915. Changing it requires restart of `font-lock-mode' to become effective
  2916. also in regions already fontified."
  2917. :group 'org-appearance
  2918. :type 'boolean)
  2919. (defcustom org-hide-leading-stars nil
  2920. "Non-nil means hide the first N-1 stars in a headline.
  2921. This works by using the face `org-hide' for these stars. This
  2922. face is white for a light background, and black for a dark
  2923. background. You may have to customize the face `org-hide' to
  2924. make this work.
  2925. Changing it requires restart of `font-lock-mode' to become effective
  2926. also in regions already fontified.
  2927. You may also set this on a per-file basis by adding one of the following
  2928. lines to the buffer:
  2929. #+STARTUP: hidestars
  2930. #+STARTUP: showstars"
  2931. :group 'org-appearance
  2932. :type 'boolean)
  2933. (defcustom org-hidden-keywords nil
  2934. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  2935. For example, a value \\='(title) for this list makes the document's title
  2936. appear in the buffer without the initial \"#+TITLE:\" part."
  2937. :group 'org-appearance
  2938. :package-version '(Org . "9.5")
  2939. :type '(set (const :tag "#+AUTHOR" author)
  2940. (const :tag "#+DATE" date)
  2941. (const :tag "#+EMAIL" email)
  2942. (const :tag "#+SUBTITLE" subtitle)
  2943. (const :tag "#+TITLE" title)))
  2944. (defcustom org-custom-properties nil
  2945. "List of properties (as strings) with a special meaning.
  2946. The default use of these custom properties is to let the user
  2947. hide them with `org-toggle-custom-properties-visibility'."
  2948. :group 'org-properties
  2949. :group 'org-appearance
  2950. :version "24.3"
  2951. :type '(repeat (string :tag "Property Name")))
  2952. (defcustom org-fontify-todo-headline nil
  2953. "Non-nil means change the face of a headline if it is marked as TODO.
  2954. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2955. When this is non-nil, the headline after the keyword is set to the
  2956. `org-headline-todo' as an additional indication."
  2957. :group 'org-appearance
  2958. :package-version '(Org . "9.4")
  2959. :type 'boolean
  2960. :safe #'booleanp)
  2961. (defcustom org-fontify-done-headline t
  2962. "Non-nil means change the face of a headline if it is marked DONE.
  2963. Normally, only the TODO/DONE keyword indicates the state of a headline.
  2964. When this is non-nil, the headline after the keyword is set to the
  2965. `org-headline-done' as an additional indication."
  2966. :group 'org-appearance
  2967. :package-version '(Org . "9.4")
  2968. :type 'boolean)
  2969. (defcustom org-fontify-emphasized-text t
  2970. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  2971. Changing this variable requires a restart of Emacs to take effect."
  2972. :group 'org-appearance
  2973. :type 'boolean)
  2974. (defcustom org-fontify-whole-heading-line nil
  2975. "Non-nil means fontify the whole line for headings.
  2976. This is useful when setting a background color for the
  2977. org-level-* faces."
  2978. :group 'org-appearance
  2979. :type 'boolean)
  2980. (defcustom org-fontify-whole-block-delimiter-line t
  2981. "Non-nil means fontify the whole line for begin/end lines of blocks.
  2982. This is useful when setting a background color for the
  2983. org-block-begin-line and org-block-end-line faces."
  2984. :group 'org-appearance
  2985. :type 'boolean)
  2986. (defcustom org-highlight-latex-and-related nil
  2987. "Non-nil means highlight LaTeX related syntax in the buffer.
  2988. When non-nil, the value should be a list containing any of the
  2989. following symbols:
  2990. `native' Highlight LaTeX snippets and environments natively.
  2991. `latex' Highlight LaTeX snippets and environments.
  2992. `script' Highlight subscript and superscript.
  2993. `entities' Highlight entities."
  2994. :group 'org-appearance
  2995. :version "24.4"
  2996. :package-version '(Org . "8.0")
  2997. :type '(choice
  2998. (const :tag "No highlighting" nil)
  2999. (set :greedy t :tag "Highlight"
  3000. (const :tag "LaTeX snippets and environments (native)" native)
  3001. (const :tag "LaTeX snippets and environments" latex)
  3002. (const :tag "Subscript and superscript" script)
  3003. (const :tag "Entities" entities))))
  3004. (defcustom org-hide-emphasis-markers nil
  3005. "Non-nil mean font-lock should hide the emphasis marker characters."
  3006. :group 'org-appearance
  3007. :type 'boolean
  3008. :safe #'booleanp)
  3009. (defcustom org-hide-macro-markers nil
  3010. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3011. :group 'org-appearance
  3012. :type 'boolean)
  3013. (defcustom org-pretty-entities nil
  3014. "Non-nil means show entities as UTF8 characters.
  3015. When nil, the \\name form remains in the buffer."
  3016. :group 'org-appearance
  3017. :version "24.1"
  3018. :type 'boolean)
  3019. (defcustom org-pretty-entities-include-sub-superscripts t
  3020. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3021. :group 'org-appearance
  3022. :version "24.1"
  3023. :type 'boolean)
  3024. (defvar org-emph-re nil
  3025. "Regular expression for matching emphasis.
  3026. After a match, the match groups contain these elements:
  3027. 0 The match of the full regular expression, including the characters
  3028. before and after the proper match
  3029. 1 The character before the proper match, or empty at beginning of line
  3030. 2 The proper match, including the leading and trailing markers
  3031. 3 The leading marker like * or /, indicating the type of highlighting
  3032. 4 The text between the emphasis markers, not including the markers
  3033. 5 The character after the match, empty at the end of a line")
  3034. (defvar org-verbatim-re nil
  3035. "Regular expression for matching verbatim text.")
  3036. (defvar org-emphasis-regexp-components) ; defined just below
  3037. (defvar org-emphasis-alist) ; defined just below
  3038. (defun org-set-emph-re (var val)
  3039. "Set variable and compute the emphasis regular expression."
  3040. (set-default-toplevel-value var val)
  3041. (when (and (boundp 'org-emphasis-alist)
  3042. (boundp 'org-emphasis-regexp-components)
  3043. org-emphasis-alist org-emphasis-regexp-components)
  3044. (pcase-let*
  3045. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3046. (body (if (<= nl 0) body
  3047. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3048. (template
  3049. (format (concat "\\([%s]\\|^\\)" ;before markers
  3050. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3051. "\\([%s]\\|$\\)") ;after markers
  3052. pre border border body border post)))
  3053. (setq org-emph-re (format template "*/_+"))
  3054. (setq org-verbatim-re (format template "=~")))))
  3055. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3056. ;; set this option proved cumbersome. See this message/thread:
  3057. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3058. (defvar org-emphasis-regexp-components
  3059. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3060. "Components used to build the regular expression for emphasis.
  3061. This is a list with five entries. Terminology: In an emphasis string
  3062. like \" *strong word* \", we call the initial space PREMATCH, the final
  3063. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3064. and \"trong wor\" is the body. The different components in this variable
  3065. specify what is allowed/forbidden in each part:
  3066. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3067. post Chars allowed as postmatch. End of line will be allowed too.
  3068. border The chars *forbidden* as border characters.
  3069. body-regexp A regexp like \".\" to match a body character. Don't use
  3070. non-shy groups here, and don't allow newline here.
  3071. newline The maximum number of newlines allowed in an emphasis exp.
  3072. You need to reload Org or to restart Emacs after setting this.")
  3073. (defcustom org-emphasis-alist
  3074. '(("*" bold)
  3075. ("/" italic)
  3076. ("_" underline)
  3077. ("=" org-verbatim verbatim)
  3078. ("~" org-code verbatim)
  3079. ("+" (:strike-through t)))
  3080. "Alist of characters and faces to emphasize text.
  3081. Text starting and ending with a special character will be emphasized,
  3082. for example *bold*, _underlined_ and /italic/. This variable sets the
  3083. marker characters and the face to be used by font-lock for highlighting
  3084. in Org buffers.
  3085. You need to reload Org or to restart Emacs after customizing this."
  3086. :group 'org-appearance
  3087. :set 'org-set-emph-re
  3088. :version "24.4"
  3089. :package-version '(Org . "8.0")
  3090. :type '(repeat
  3091. (list
  3092. (string :tag "Marker character")
  3093. (choice
  3094. (face :tag "Font-lock-face")
  3095. (plist :tag "Face property list"))
  3096. (option (const verbatim)))))
  3097. (defvar org-protecting-blocks '("src" "example" "export")
  3098. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3099. This is needed for font-lock setup.")
  3100. ;;; Functions and variables from their packages
  3101. ;; Declared here to avoid compiler warnings
  3102. (defvar mark-active)
  3103. ;; Various packages
  3104. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3105. (declare-function calendar-forward-day "cal-move" (arg))
  3106. (declare-function calendar-goto-date "cal-move" (date))
  3107. (declare-function calendar-goto-today "cal-move" ())
  3108. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3109. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3110. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3111. (declare-function cdlatex-tab "ext:cdlatex" ())
  3112. (declare-function dired-get-filename
  3113. "dired"
  3114. (&optional localp no-error-if-not-filep))
  3115. (declare-function iswitchb-read-buffer
  3116. "iswitchb"
  3117. (prompt &optional
  3118. default require-match _predicate start matches-set))
  3119. (declare-function org-agenda-change-all-lines
  3120. "org-agenda"
  3121. (newhead hdmarker &optional fixface just-this))
  3122. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3123. "org-agenda"
  3124. (&optional end))
  3125. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3126. (declare-function org-agenda-format-item
  3127. "org-agenda"
  3128. (extra txt &optional level category tags dotime
  3129. remove-re habitp))
  3130. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3131. (declare-function org-agenda-save-markers-for-cut-and-paste
  3132. "org-agenda"
  3133. (beg end))
  3134. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3135. (declare-function org-agenda-skip "org-agenda" (&optional element))
  3136. (declare-function org-attach-expand "org-attach" (file))
  3137. (declare-function org-attach-reveal "org-attach" ())
  3138. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3139. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3140. (declare-function org-indent-mode "org-indent" (&optional arg))
  3141. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3142. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3143. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3144. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3145. (declare-function parse-time-string "parse-time" (string))
  3146. (defvar align-mode-rules-list)
  3147. (defvar calc-embedded-close-formula)
  3148. (defvar calc-embedded-open-formula)
  3149. (defvar calc-embedded-open-mode)
  3150. (defvar font-lock-unfontify-region-function)
  3151. (defvar iswitchb-temp-buflist)
  3152. (defvar org-agenda-tags-todo-honor-ignore-options)
  3153. (defvar remember-data-file)
  3154. (defvar texmathp-why)
  3155. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3156. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3157. (declare-function org-resolve-clocks "org-clock"
  3158. (&optional also-non-dangling-p prompt last-valid))
  3159. (defvar org-clock-start-time)
  3160. (defvar org-clock-marker (make-marker)
  3161. "Marker recording the last clock-in.")
  3162. (defvar org-clock-hd-marker (make-marker)
  3163. "Marker recording the last clock-in, but the headline position.")
  3164. (defvar org-clock-heading ""
  3165. "The heading of the current clock entry.")
  3166. (defun org-clocking-buffer ()
  3167. "Return the buffer where the clock is currently running.
  3168. Return nil if no clock is running."
  3169. (marker-buffer org-clock-marker))
  3170. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3171. (defun org-check-running-clock ()
  3172. "Check if the current buffer contains the running clock.
  3173. If yes, offer to stop it and to save the buffer with the changes."
  3174. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3175. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3176. (buffer-name))))
  3177. (org-clock-out)
  3178. (when (y-or-n-p "Save changed buffer?")
  3179. (save-buffer))))
  3180. (defun org-clocktable-try-shift (dir n)
  3181. "Check if this line starts a clock table, if yes, shift the time block."
  3182. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3183. (org-clocktable-shift dir n)))
  3184. ;;;###autoload
  3185. (defun org-clock-persistence-insinuate ()
  3186. "Set up hooks for clock persistence."
  3187. (require 'org-clock)
  3188. (add-hook 'org-mode-hook 'org-clock-load)
  3189. (add-hook 'kill-emacs-hook 'org-clock-save))
  3190. (defun org-clock-auto-clockout-insinuate ()
  3191. "Set up hook for auto clocking out when Emacs is idle.
  3192. See `org-clock-auto-clockout-timer'.
  3193. This function is meant to be added to the user configuration."
  3194. (require 'org-clock)
  3195. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3196. (defgroup org-archive nil
  3197. "Options concerning archiving in Org mode."
  3198. :tag "Org Archive"
  3199. :group 'org-structure)
  3200. (defcustom org-archive-location "%s_archive::"
  3201. "The location where subtrees should be archived.
  3202. The value of this variable is a string, consisting of two parts,
  3203. separated by a double-colon. The first part is a filename and
  3204. the second part is a headline.
  3205. When the filename is omitted, archiving happens in the same file.
  3206. %s in the filename will be replaced by the current file
  3207. name (without the directory part). Archiving to a different file
  3208. is useful to keep archived entries from contributing to the
  3209. Org Agenda.
  3210. The archived entries will be filed as subtrees of the specified
  3211. headline. When the headline is omitted, the subtrees are simply
  3212. filed away at the end of the file, as top-level entries. Also in
  3213. the heading you can use %s to represent the file name, this can be
  3214. useful when using the same archive for a number of different files.
  3215. Here are a few examples:
  3216. \"%s_archive::\"
  3217. If the current file is Projects.org, archive in file
  3218. Projects.org_archive, as top-level trees. This is the default.
  3219. \"::* Archived Tasks\"
  3220. Archive in the current file, under the top-level headline
  3221. \"* Archived Tasks\".
  3222. \"~/org/archive.org::\"
  3223. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3224. \"~/org/archive.org::* From %s\"
  3225. Archive in file ~/org/archive.org (absolute path), under headlines
  3226. \"From FILENAME\" where file name is the current file name.
  3227. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3228. The \"datetree/\" string is special, signifying to archive
  3229. items to the datetree. Items are placed in either the CLOSED
  3230. date of the item, or the current date if there is no CLOSED date.
  3231. The heading will be a subentry to the current date. There doesn't
  3232. need to be a heading, but there always needs to be a slash after
  3233. datetree. For example, to store archived items directly in the
  3234. datetree, use \"~/org/datetree.org::datetree/\".
  3235. \"basement::** Finished Tasks\"
  3236. Archive in file ./basement (relative path), as level 3 trees
  3237. below the level 2 heading \"** Finished Tasks\".
  3238. You may define it locally by setting an ARCHIVE property. If
  3239. such a property is found in the file or in an entry, and anywhere
  3240. up the hierarchy, it will be used.
  3241. You can also set it for the whole file using the keyword-syntax:
  3242. #+ARCHIVE: basement::** Finished Tasks"
  3243. :group 'org-archive
  3244. :type 'string)
  3245. (defcustom org-agenda-skip-archived-trees t
  3246. "Non-nil means the agenda will skip any items located in archived trees.
  3247. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3248. variable is no longer recommended, you should leave it at the value t.
  3249. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3250. :group 'org-archive
  3251. :group 'org-agenda-skip
  3252. :type 'boolean)
  3253. (defcustom org-columns-skip-archived-trees t
  3254. "Non-nil means ignore archived trees when creating column view."
  3255. :group 'org-archive
  3256. :group 'org-properties
  3257. :type 'boolean)
  3258. (defcustom org-sparse-tree-open-archived-trees nil
  3259. "Non-nil means sparse tree construction shows matches in archived trees.
  3260. When nil, matches in these trees are highlighted, but the trees are kept in
  3261. collapsed state."
  3262. :group 'org-archive
  3263. :group 'org-sparse-trees
  3264. :type 'boolean)
  3265. (defcustom org-sparse-tree-default-date-type nil
  3266. "The default date type when building a sparse tree.
  3267. When this is nil, a date is a scheduled or a deadline timestamp.
  3268. Otherwise, these types are allowed:
  3269. all: all timestamps
  3270. active: only active timestamps (<...>)
  3271. inactive: only inactive timestamps ([...])
  3272. scheduled: only scheduled timestamps
  3273. deadline: only deadline timestamps"
  3274. :type '(choice (const :tag "Scheduled or deadline" nil)
  3275. (const :tag "All timestamps" all)
  3276. (const :tag "Only active timestamps" active)
  3277. (const :tag "Only inactive timestamps" inactive)
  3278. (const :tag "Only scheduled timestamps" scheduled)
  3279. (const :tag "Only deadline timestamps" deadline)
  3280. (const :tag "Only closed timestamps" closed))
  3281. :version "26.1"
  3282. :package-version '(Org . "8.3")
  3283. :group 'org-sparse-trees)
  3284. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3285. ;; Declare Column View Code
  3286. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3287. (declare-function org-columns-compute "org-colview" (property))
  3288. ;; Declare ID code
  3289. (declare-function org-id-store-link "org-id")
  3290. (declare-function org-id-locations-load "org-id")
  3291. (declare-function org-id-locations-save "org-id")
  3292. (defvar org-id-track-globally)
  3293. ;;; Variables for pre-computed regular expressions, all buffer local
  3294. (defvar-local org-todo-regexp nil
  3295. "Matches any of the TODO state keywords.
  3296. Since TODO keywords are case-sensitive, `case-fold-search' is
  3297. expected to be bound to nil when matching against this regexp.")
  3298. (defvar-local org-not-done-regexp nil
  3299. "Matches any of the TODO state keywords except the last one.
  3300. Since TODO keywords are case-sensitive, `case-fold-search' is
  3301. expected to be bound to nil when matching against this regexp.")
  3302. (defvar-local org-not-done-heading-regexp nil
  3303. "Matches a TODO headline that is not done.
  3304. Since TODO keywords are case-sensitive, `case-fold-search' is
  3305. expected to be bound to nil when matching against this regexp.")
  3306. (defvar-local org-todo-line-regexp nil
  3307. "Matches a headline and puts TODO state into group 2 if present.
  3308. Since TODO keywords are case-sensitive, `case-fold-search' is
  3309. expected to be bound to nil when matching against this regexp.")
  3310. (defvar-local org-complex-heading-regexp nil
  3311. "Matches a headline and puts everything into groups:
  3312. group 1: Stars
  3313. group 2: The TODO keyword, maybe
  3314. group 3: Priority cookie
  3315. group 4: True headline
  3316. group 5: Tags
  3317. Since TODO keywords are case-sensitive, `case-fold-search' is
  3318. expected to be bound to nil when matching against this regexp.")
  3319. (defvar-local org-complex-heading-regexp-format nil
  3320. "Printf format to make regexp to match an exact headline.
  3321. This regexp will match the headline of any node which has the
  3322. exact headline text that is put into the format, but may have any
  3323. TODO state, priority, tags, statistics cookies (at the beginning
  3324. or end of the headline title), or COMMENT keyword.")
  3325. (defvar-local org-todo-line-tags-regexp nil
  3326. "Matches a headline and puts TODO state into group 2 if present.
  3327. Also put tags into group 4 if tags are present.")
  3328. (defconst org-plain-time-of-day-regexp
  3329. (concat
  3330. "\\(\\<[012]?[0-9]"
  3331. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3332. "\\(--?"
  3333. "\\(\\<[012]?[0-9]"
  3334. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3335. "\\)?")
  3336. "Regular expression to match a plain time or time range.
  3337. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3338. groups carry important information:
  3339. 0 the full match
  3340. 1 the first time, range or not
  3341. 8 the second time, if it is a range.")
  3342. (defconst org-plain-time-extension-regexp
  3343. (concat
  3344. "\\(\\<[012]?[0-9]"
  3345. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3346. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3347. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3348. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3349. groups carry important information:
  3350. 0 the full match
  3351. 7 hours of duration
  3352. 9 minutes of duration")
  3353. (defconst org-stamp-time-of-day-regexp
  3354. (concat
  3355. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3356. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3357. "\\(--?"
  3358. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3359. "Regular expression to match a timestamp time or time range.
  3360. After a match, the following groups carry important information:
  3361. 0 the full match
  3362. 1 date plus weekday, for back referencing to make sure
  3363. both times are on the same day
  3364. 2 the first time, range or not
  3365. 4 the second time, if it is a range.")
  3366. (defconst org-startup-options
  3367. '(("fold" org-startup-folded t)
  3368. ("overview" org-startup-folded t)
  3369. ("nofold" org-startup-folded nil)
  3370. ("showall" org-startup-folded nil)
  3371. ("show2levels" org-startup-folded show2levels)
  3372. ("show3levels" org-startup-folded show3levels)
  3373. ("show4levels" org-startup-folded show4levels)
  3374. ("show5levels" org-startup-folded show5levels)
  3375. ("showeverything" org-startup-folded showeverything)
  3376. ("content" org-startup-folded content)
  3377. ("indent" org-startup-indented t)
  3378. ("noindent" org-startup-indented nil)
  3379. ("num" org-startup-numerated t)
  3380. ("nonum" org-startup-numerated nil)
  3381. ("hidestars" org-hide-leading-stars t)
  3382. ("showstars" org-hide-leading-stars nil)
  3383. ("odd" org-odd-levels-only t)
  3384. ("oddeven" org-odd-levels-only nil)
  3385. ("align" org-startup-align-all-tables t)
  3386. ("noalign" org-startup-align-all-tables nil)
  3387. ("shrink" org-startup-shrink-all-tables t)
  3388. ("inlineimages" org-startup-with-inline-images t)
  3389. ("noinlineimages" org-startup-with-inline-images nil)
  3390. ("latexpreview" org-startup-with-latex-preview t)
  3391. ("nolatexpreview" org-startup-with-latex-preview nil)
  3392. ("customtime" org-display-custom-times t)
  3393. ("logdone" org-log-done time)
  3394. ("lognotedone" org-log-done note)
  3395. ("nologdone" org-log-done nil)
  3396. ("lognoteclock-out" org-log-note-clock-out t)
  3397. ("nolognoteclock-out" org-log-note-clock-out nil)
  3398. ("logrepeat" org-log-repeat state)
  3399. ("lognoterepeat" org-log-repeat note)
  3400. ("logdrawer" org-log-into-drawer t)
  3401. ("nologdrawer" org-log-into-drawer nil)
  3402. ("logstatesreversed" org-log-states-order-reversed t)
  3403. ("nologstatesreversed" org-log-states-order-reversed nil)
  3404. ("nologrepeat" org-log-repeat nil)
  3405. ("logreschedule" org-log-reschedule time)
  3406. ("lognotereschedule" org-log-reschedule note)
  3407. ("nologreschedule" org-log-reschedule nil)
  3408. ("logredeadline" org-log-redeadline time)
  3409. ("lognoteredeadline" org-log-redeadline note)
  3410. ("nologredeadline" org-log-redeadline nil)
  3411. ("logrefile" org-log-refile time)
  3412. ("lognoterefile" org-log-refile note)
  3413. ("nologrefile" org-log-refile nil)
  3414. ("fninline" org-footnote-define-inline t)
  3415. ("nofninline" org-footnote-define-inline nil)
  3416. ("fnlocal" org-footnote-section nil)
  3417. ("fnauto" org-footnote-auto-label t)
  3418. ("fnprompt" org-footnote-auto-label nil)
  3419. ("fnconfirm" org-footnote-auto-label confirm)
  3420. ("fnplain" org-footnote-auto-label plain)
  3421. ("fnadjust" org-footnote-auto-adjust t)
  3422. ("nofnadjust" org-footnote-auto-adjust nil)
  3423. ("constcgs" constants-unit-system cgs)
  3424. ("constSI" constants-unit-system SI)
  3425. ("noptag" org-tag-persistent-alist nil)
  3426. ("hideblocks" org-hide-block-startup t)
  3427. ("nohideblocks" org-hide-block-startup nil)
  3428. ("beamer" org-startup-with-beamer-mode t)
  3429. ("entitiespretty" org-pretty-entities t)
  3430. ("entitiesplain" org-pretty-entities nil))
  3431. "Variable associated with STARTUP options for Org.
  3432. Each element is a list of three items: the startup options (as written
  3433. in the #+STARTUP line), the corresponding variable, and the value to set
  3434. this variable to if the option is found. An optional fourth element PUSH
  3435. means to push this value onto the list in the variable.")
  3436. (defcustom org-group-tags t
  3437. "When non-nil (the default), use group tags.
  3438. This can be turned on/off through `org-toggle-tags-groups'."
  3439. :group 'org-tags
  3440. :group 'org-startup
  3441. :type 'boolean)
  3442. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3443. (defun org-toggle-tags-groups ()
  3444. "Toggle support for group tags.
  3445. Support for group tags is controlled by the option
  3446. `org-group-tags', which is non-nil by default."
  3447. (interactive)
  3448. (setq org-group-tags (not org-group-tags))
  3449. (cond ((and (derived-mode-p 'org-agenda-mode)
  3450. org-group-tags)
  3451. (org-agenda-redo))
  3452. ((derived-mode-p 'org-mode)
  3453. (let ((org-inhibit-startup t)) (org-mode))))
  3454. (message "Groups tags support has been turned %s"
  3455. (if org-group-tags "on" "off")))
  3456. (defun org--tag-add-to-alist (alist1 alist2)
  3457. "Merge tags from ALIST1 into ALIST2.
  3458. Duplicates tags outside a group are removed. Keywords and order
  3459. are preserved.
  3460. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3461. See `org-tag-alist' for their structure."
  3462. (cond
  3463. ((null alist2) alist1)
  3464. ((null alist1) alist2)
  3465. (t
  3466. (let ((to-add nil)
  3467. (group-flag nil))
  3468. (dolist (tag-pair alist1)
  3469. (pcase tag-pair
  3470. (`(,(or :startgrouptag :startgroup))
  3471. (setq group-flag t)
  3472. (push tag-pair to-add))
  3473. (`(,(or :endgrouptag :endgroup))
  3474. (setq group-flag nil)
  3475. (push tag-pair to-add))
  3476. (`(,(or :grouptags :newline))
  3477. (push tag-pair to-add))
  3478. (`(,tag . ,_)
  3479. ;; Remove duplicates from ALIST1, unless they are in
  3480. ;; a group. Indeed, it makes sense to have a tag appear in
  3481. ;; multiple groups.
  3482. (when (or group-flag (not (assoc tag alist2)))
  3483. (push tag-pair to-add)))
  3484. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3485. ;; Preserve order of ALIST1.
  3486. (append (nreverse to-add) alist2)))))
  3487. (defun org-priority-to-value (s)
  3488. "Convert priority string S to its numeric value."
  3489. (or (save-match-data
  3490. (and (string-match "\\([0-9]+\\)" s)
  3491. (string-to-number (match-string 1 s))))
  3492. (string-to-char s)))
  3493. (defun org-set-regexps-and-options (&optional tags-only)
  3494. "Precompute regular expressions used in the current buffer.
  3495. When optional argument TAGS-ONLY is non-nil, only compute tags
  3496. related expressions."
  3497. (when (derived-mode-p 'org-mode)
  3498. (let ((alist (org-collect-keywords
  3499. (append '("FILETAGS" "TAGS")
  3500. (and (not tags-only)
  3501. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3502. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3503. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3504. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3505. ;; Startup options. Get this early since it does change
  3506. ;; behavior for other options (e.g., tags).
  3507. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3508. (cdr (assoc "STARTUP" alist)))))
  3509. (dolist (option startup)
  3510. (pcase (assoc-string option org-startup-options t)
  3511. (`(,_ ,variable ,value t)
  3512. (unless (listp (symbol-value variable))
  3513. (set (make-local-variable variable) nil))
  3514. (add-to-list variable value))
  3515. (`(,_ ,variable ,value . ,_)
  3516. (set (make-local-variable variable) value))
  3517. (_ nil))))
  3518. (setq-local org-file-tags
  3519. (mapcar #'org-add-prop-inherited
  3520. (cl-mapcan (lambda (value)
  3521. (cl-mapcan
  3522. (lambda (k) (org-split-string k ":"))
  3523. (split-string value)))
  3524. (cdr (assoc "FILETAGS" alist)))))
  3525. (setq org-current-tag-alist
  3526. (org--tag-add-to-alist
  3527. org-tag-persistent-alist
  3528. (let ((tags (cdr (assoc "TAGS" alist))))
  3529. (if tags
  3530. (org-tag-string-to-alist
  3531. (mapconcat #'identity tags "\n"))
  3532. org-tag-alist))))
  3533. (setq org-tag-groups-alist
  3534. (org-tag-alist-to-groups org-current-tag-alist))
  3535. (unless tags-only
  3536. ;; Properties.
  3537. (let ((properties nil))
  3538. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3539. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3540. (setq properties (org--update-property-plist
  3541. (match-string-no-properties 1 value)
  3542. (match-string-no-properties 2 value)
  3543. properties))))
  3544. (setq-local org-keyword-properties properties))
  3545. ;; Archive location.
  3546. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3547. (when archive (setq-local org-archive-location archive)))
  3548. ;; Category.
  3549. (let ((category (cdr (assoc "CATEGORY" alist))))
  3550. (when category
  3551. (setq-local org-category (intern category))
  3552. (setq-local org-keyword-properties
  3553. (org--update-property-plist
  3554. "CATEGORY" category org-keyword-properties))))
  3555. ;; Columns.
  3556. (let ((column (cdr (assoc "COLUMNS" alist))))
  3557. (when column (setq-local org-columns-default-format column)))
  3558. ;; Constants.
  3559. (let ((store nil))
  3560. (dolist (pair (cl-mapcan #'split-string
  3561. (cdr (assoc "CONSTANTS" alist))))
  3562. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3563. (let* ((name (match-string 1 pair))
  3564. (value (match-string 2 pair))
  3565. (old (assoc name store)))
  3566. (if old (setcdr old value)
  3567. (push (cons name value) store)))))
  3568. (setq org-table-formula-constants-local store))
  3569. ;; Link abbreviations.
  3570. (let ((links
  3571. (delq nil
  3572. (mapcar
  3573. (lambda (value)
  3574. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3575. (cons (match-string-no-properties 1 value)
  3576. (match-string-no-properties 2 value))))
  3577. (cdr (assoc "LINK" alist))))))
  3578. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3579. ;; Priorities.
  3580. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3581. (pcase (and value (split-string value))
  3582. (`(,high ,low ,default . ,_)
  3583. (setq-local org-priority-highest (org-priority-to-value high))
  3584. (setq-local org-priority-lowest (org-priority-to-value low))
  3585. (setq-local org-priority-default (org-priority-to-value default)))))
  3586. ;; Scripts.
  3587. (let ((value (cdr (assoc "OPTIONS" alist))))
  3588. (dolist (option value)
  3589. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3590. (setq-local org-use-sub-superscripts
  3591. (read (match-string 1 option))))))
  3592. ;; TODO keywords.
  3593. (setq-local org-todo-kwd-alist nil)
  3594. (setq-local org-todo-key-alist nil)
  3595. (setq-local org-todo-key-trigger nil)
  3596. (setq-local org-todo-keywords-1 nil)
  3597. (setq-local org-done-keywords nil)
  3598. (setq-local org-todo-heads nil)
  3599. (setq-local org-todo-sets nil)
  3600. (setq-local org-todo-log-states nil)
  3601. (let ((todo-sequences
  3602. (or (append (mapcar (lambda (value)
  3603. (cons 'type (split-string value)))
  3604. (cdr (assoc "TYP_TODO" alist)))
  3605. (mapcar (lambda (value)
  3606. (cons 'sequence (split-string value)))
  3607. (append (cdr (assoc "TODO" alist))
  3608. (cdr (assoc "SEQ_TODO" alist)))))
  3609. (let ((d (default-value 'org-todo-keywords)))
  3610. (if (not (stringp (car d))) d
  3611. ;; XXX: Backward compatibility code.
  3612. (list (cons org-todo-interpretation d)))))))
  3613. (dolist (sequence todo-sequences)
  3614. (let* ((sequence (or (run-hook-with-args-until-success
  3615. 'org-todo-setup-filter-hook sequence)
  3616. sequence))
  3617. (sequence-type (car sequence))
  3618. (keywords (cdr sequence))
  3619. (sep (member "|" keywords))
  3620. names alist)
  3621. (dolist (k (remove "|" keywords))
  3622. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3623. k)
  3624. (error "Invalid TODO keyword %s" k))
  3625. (let ((name (match-string 1 k))
  3626. (key (match-string 2 k))
  3627. (log (org-extract-log-state-settings k)))
  3628. (push name names)
  3629. (push (cons name (and key (string-to-char key))) alist)
  3630. (when log (push log org-todo-log-states))))
  3631. (let* ((names (nreverse names))
  3632. (done (if sep (org-remove-keyword-keys (cdr sep))
  3633. (last names)))
  3634. (head (car names))
  3635. (tail (list sequence-type head (car done) (org-last done))))
  3636. (add-to-list 'org-todo-heads head 'append)
  3637. (push names org-todo-sets)
  3638. (setq org-done-keywords (append org-done-keywords done nil))
  3639. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3640. (setq org-todo-key-alist
  3641. (append org-todo-key-alist
  3642. (and alist
  3643. (append '((:startgroup))
  3644. (nreverse alist)
  3645. '((:endgroup))))))
  3646. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3647. (setq org-todo-sets (nreverse org-todo-sets)
  3648. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3649. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3650. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3651. ;; Compute the regular expressions and other local variables.
  3652. ;; Using `org-outline-regexp-bol' would complicate them much,
  3653. ;; because of the fixed white space at the end of that string.
  3654. (unless org-done-keywords
  3655. (setq org-done-keywords
  3656. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3657. (setq org-not-done-keywords
  3658. (org-delete-all org-done-keywords
  3659. (copy-sequence org-todo-keywords-1))
  3660. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3661. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3662. org-not-done-heading-regexp
  3663. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3664. org-todo-line-regexp
  3665. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3666. org-complex-heading-regexp
  3667. (concat "^\\(\\*+\\)"
  3668. "\\(?: +" org-todo-regexp "\\)?"
  3669. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3670. "\\(?: +\\(.*?\\)\\)??"
  3671. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3672. "[ \t]*$")
  3673. org-complex-heading-regexp-format
  3674. (concat "^\\(\\*+\\)"
  3675. "\\(?: +" org-todo-regexp "\\)?"
  3676. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3677. "\\(?: +"
  3678. ;; Headline might be commented
  3679. "\\(?:" org-comment-string " +\\)?"
  3680. ;; Stats cookies can be stuck to body.
  3681. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3682. "\\(%s\\)"
  3683. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3684. "\\)"
  3685. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3686. "[ \t]*$")
  3687. org-todo-line-tags-regexp
  3688. (concat "^\\(\\*+\\)"
  3689. "\\(?: +" org-todo-regexp "\\)?"
  3690. "\\(?: +\\(.*?\\)\\)??"
  3691. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3692. "[ \t]*$"))
  3693. (org-compute-latex-and-related-regexp)))))
  3694. (defun org-collect-keywords (keywords &optional unique directory)
  3695. "Return values for KEYWORDS in current buffer, as an alist.
  3696. KEYWORDS is a list of strings. Return value is a list of
  3697. elements with the pattern:
  3698. (NAME . LIST-OF-VALUES)
  3699. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3700. is a list of non-empty values, as strings, in order of appearance
  3701. in the buffer.
  3702. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3703. value, empty or not, appearing in the buffer, as a string.
  3704. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3705. (VALUE . DIRECTORY)
  3706. where VALUE is the regular value, and DIRECTORY is the variable
  3707. `default-directory' for the buffer containing the keyword. This
  3708. is important for values containing relative file names, since the
  3709. function follows SETUPFILE keywords, and may change its working
  3710. directory."
  3711. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3712. (unique (mapcar #'upcase unique))
  3713. (alist (org--collect-keywords-1
  3714. keywords unique directory
  3715. (and buffer-file-name (list buffer-file-name))
  3716. nil)))
  3717. ;; Re-order results.
  3718. (dolist (entry alist)
  3719. (pcase entry
  3720. (`(,_ . ,(and value (pred consp)))
  3721. (setcdr entry (nreverse value)))))
  3722. (nreverse alist)))
  3723. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3724. (org-with-point-at 1
  3725. (let ((case-fold-search t)
  3726. (regexp (org-make-options-regexp keywords)))
  3727. (while (and keywords (re-search-forward regexp nil t))
  3728. (let ((element (org-element-at-point)))
  3729. (when (eq 'keyword (org-element-type element))
  3730. (let ((value (org-element-property :value element)))
  3731. (pcase (org-element-property :key element)
  3732. ("SETUPFILE"
  3733. (when (and (org-string-nw-p value)
  3734. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3735. (let* ((uri (org-strip-quotes value))
  3736. (uri-is-url (org-url-p uri))
  3737. (uri (if uri-is-url
  3738. uri
  3739. (expand-file-name uri))))
  3740. (unless (member uri files)
  3741. (with-temp-buffer
  3742. (unless uri-is-url
  3743. (setq default-directory (file-name-directory uri)))
  3744. (let ((contents (org-file-contents uri :noerror)))
  3745. (when contents
  3746. (insert contents)
  3747. ;; Fake Org mode: `org-element-at-point'
  3748. ;; doesn't need full set-up.
  3749. (let ((major-mode 'org-mode))
  3750. (setq alist
  3751. (org--collect-keywords-1
  3752. keywords unique directory
  3753. (cons uri files)
  3754. alist))))))))))
  3755. (keyword
  3756. (let ((entry (assoc keyword alist))
  3757. (final
  3758. (cond ((not (member keyword directory)) value)
  3759. (buffer-file-name
  3760. (cons value
  3761. (file-name-directory buffer-file-name)))
  3762. (t (cons value default-directory)))))
  3763. (cond ((member keyword unique)
  3764. (push (cons keyword final) alist)
  3765. (setq keywords (remove keyword keywords))
  3766. (setq regexp (org-make-options-regexp keywords)))
  3767. ((null entry) (push (list keyword final) alist))
  3768. (t (push final (cdr entry)))))))))))
  3769. alist)))
  3770. (defun org-tag-string-to-alist (s)
  3771. "Return tag alist associated to string S.
  3772. S is a value for TAGS keyword or produced with
  3773. `org-tag-alist-to-string'. Return value is an alist suitable for
  3774. `org-tag-alist' or `org-tag-persistent-alist'."
  3775. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3776. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3777. "\\(?:(\\(.\\))\\)?\\'"))
  3778. alist group-flag)
  3779. (dolist (tokens lines (cdr (nreverse alist)))
  3780. (push '(:newline) alist)
  3781. (while tokens
  3782. (let ((token (pop tokens)))
  3783. (pcase token
  3784. ("{"
  3785. (push '(:startgroup) alist)
  3786. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3787. ("}"
  3788. (push '(:endgroup) alist)
  3789. (setq group-flag nil))
  3790. ("["
  3791. (push '(:startgrouptag) alist)
  3792. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3793. ("]"
  3794. (push '(:endgrouptag) alist)
  3795. (setq group-flag nil))
  3796. (":"
  3797. (push '(:grouptags) alist))
  3798. ((guard (string-match tag-re token))
  3799. (let ((tag (match-string 1 token))
  3800. (key (and (match-beginning 2)
  3801. (string-to-char (match-string 2 token)))))
  3802. ;; Push all tags in groups, no matter if they already
  3803. ;; appear somewhere else in the list.
  3804. (when (or group-flag (not (assoc tag alist)))
  3805. (push (cons tag key) alist))))))))))
  3806. (defun org-tag-alist-to-string (alist &optional skip-key)
  3807. "Return tag string associated to ALIST.
  3808. ALIST is an alist, as defined in `org-tag-alist' or
  3809. `org-tag-persistent-alist', or produced with
  3810. `org-tag-string-to-alist'.
  3811. Return value is a string suitable as a value for \"TAGS\"
  3812. keyword.
  3813. When optional argument SKIP-KEY is non-nil, skip selection keys
  3814. next to tags."
  3815. (mapconcat (lambda (token)
  3816. (pcase token
  3817. (`(:startgroup) "{")
  3818. (`(:endgroup) "}")
  3819. (`(:startgrouptag) "[")
  3820. (`(:endgrouptag) "]")
  3821. (`(:grouptags) ":")
  3822. (`(:newline) "\\n")
  3823. ((and
  3824. (guard (not skip-key))
  3825. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  3826. (format "%s(%c)" tag key))
  3827. (`(,(and tag (pred stringp)) . ,_) tag)
  3828. (_ (user-error "Invalid tag token: %S" token))))
  3829. alist
  3830. " "))
  3831. (defun org-tag-alist-to-groups (alist)
  3832. "Return group alist from tag 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'. Return value is an alist following
  3836. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  3837. a string, summarizing TAGS, as a list of strings."
  3838. (let (groups group-status current-group)
  3839. (dolist (token alist (nreverse groups))
  3840. (pcase token
  3841. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  3842. (`(,(or :endgroup :endgrouptag))
  3843. (when (eq group-status 'append)
  3844. (push (nreverse current-group) groups))
  3845. (setq group-status nil current-group nil))
  3846. (`(:grouptags) (setq group-status 'append))
  3847. ((and `(,tag . ,_) (guard group-status))
  3848. (if (eq group-status 'append) (push tag current-group)
  3849. (setq current-group (list tag))))
  3850. (_ nil)))))
  3851. (defvar org--file-cache (make-hash-table :test #'equal)
  3852. "Hash table to store contents of files referenced via a URL.
  3853. This is the cache of file URLs read using `org-file-contents'.")
  3854. (defun org-reset-file-cache ()
  3855. "Reset the cache of files downloaded by `org-file-contents'."
  3856. (clrhash org--file-cache))
  3857. (defun org-file-contents (file &optional noerror nocache)
  3858. "Return the contents of FILE, as a string.
  3859. FILE can be a file name or URL.
  3860. If FILE is a URL, download the contents. If the URL contents are
  3861. already cached in the `org--file-cache' hash table, the download step
  3862. is skipped.
  3863. If NOERROR is non-nil, ignore the error when unable to read the FILE
  3864. from file or URL, and return nil.
  3865. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  3866. is available. This option applies only if FILE is a URL."
  3867. (let* ((is-url (org-url-p file))
  3868. (cache (and is-url
  3869. (not nocache)
  3870. (gethash file org--file-cache))))
  3871. (cond
  3872. (cache)
  3873. (is-url
  3874. (with-current-buffer (url-retrieve-synchronously file)
  3875. (goto-char (point-min))
  3876. ;; Move point to after the url-retrieve header.
  3877. (search-forward "\n\n" nil :move)
  3878. ;; Search for the success code only in the url-retrieve header.
  3879. (if (save-excursion
  3880. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  3881. ;; Update the cache `org--file-cache' and return contents.
  3882. (puthash file
  3883. (buffer-substring-no-properties (point) (point-max))
  3884. org--file-cache)
  3885. (funcall (if noerror #'message #'user-error)
  3886. "Unable to fetch file from %S"
  3887. file)
  3888. nil)))
  3889. (t
  3890. (with-temp-buffer
  3891. (condition-case nil
  3892. (progn
  3893. (insert-file-contents file)
  3894. (buffer-string))
  3895. (file-error
  3896. (funcall (if noerror #'message #'user-error)
  3897. "Unable to read file %S"
  3898. file)
  3899. nil)))))))
  3900. (defun org-extract-log-state-settings (x)
  3901. "Extract the log state setting from a TODO keyword string.
  3902. This will extract info from a string like \"WAIT(w@/!)\"."
  3903. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  3904. (let ((kw (match-string 1 x))
  3905. (log1 (and (match-end 3) (match-string 3 x)))
  3906. (log2 (and (match-end 4) (match-string 4 x))))
  3907. (and (or log1 log2)
  3908. (list kw
  3909. (and log1 (if (equal log1 "!") 'time 'note))
  3910. (and log2 (if (equal log2 "!") 'time 'note)))))))
  3911. (defun org-remove-keyword-keys (list)
  3912. "Remove a pair of parenthesis at the end of each string in LIST."
  3913. (mapcar (lambda (x)
  3914. (if (string-match "(.*)$" x)
  3915. (substring x 0 (match-beginning 0))
  3916. x))
  3917. list))
  3918. (defun org-assign-fast-keys (alist)
  3919. "Assign fast keys to a keyword-key alist.
  3920. Respect keys that are already there."
  3921. (let (new e (alt ?0))
  3922. (while (setq e (pop alist))
  3923. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  3924. (cdr e)) ;; Key already assigned.
  3925. (push e new)
  3926. (let ((clist (string-to-list (downcase (car e))))
  3927. (used (append new alist)))
  3928. (when (= (car clist) ?@)
  3929. (pop clist))
  3930. (while (and clist (rassoc (car clist) used))
  3931. (pop clist))
  3932. (unless clist
  3933. (while (rassoc alt used)
  3934. (cl-incf alt)))
  3935. (push (cons (car e) (or (car clist) alt)) new))))
  3936. (nreverse new)))
  3937. ;;; Some variables used in various places
  3938. (defvar org-window-configuration nil
  3939. "Used in various places to store a window configuration.")
  3940. (defvar org-selected-window nil
  3941. "Used in various places to store a window configuration.")
  3942. (defvar org-finish-function nil
  3943. "Function to be called when `C-c C-c' is used.
  3944. This is for getting out of special buffers like capture.")
  3945. (defvar org-last-state)
  3946. ;; Defined somewhere in this file, but used before definition.
  3947. (defvar org-entities) ;; defined in org-entities.el
  3948. (defvar org-struct-menu)
  3949. (defvar org-org-menu)
  3950. (defvar org-tbl-menu)
  3951. ;;;; Define the Org mode
  3952. (defun org-before-change-function (_beg _end)
  3953. "Every change indicates that a table might need an update."
  3954. (setq org-table-may-need-update t))
  3955. (defvar org-mode-map)
  3956. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  3957. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  3958. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  3959. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  3960. (defvar bidi-paragraph-direction)
  3961. (defvar buffer-face-mode-face)
  3962. (require 'outline)
  3963. ;; Other stuff we need.
  3964. (require 'time-date)
  3965. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  3966. (require 'easymenu))
  3967. (require 'org-entities)
  3968. (require 'org-faces)
  3969. (require 'org-list)
  3970. (require 'org-pcomplete)
  3971. (require 'org-src)
  3972. (require 'org-footnote)
  3973. (require 'org-macro)
  3974. ;; babel
  3975. (require 'ob)
  3976. (defvar org-element-cache-persistent); Defined in org-element.el
  3977. (defvar org-element-use-cache); Defined in org-element.el
  3978. (defvar org-mode-loading nil
  3979. "Non-nil during Org mode initialisation.")
  3980. ;;;###autoload
  3981. (define-derived-mode org-mode outline-mode "Org"
  3982. "Outline-based notes management and organizer, alias
  3983. \"Carsten's outline-mode for keeping track of everything.\"
  3984. Org mode develops organizational tasks around a NOTES file which
  3985. contains information about projects as plain text. Org mode is
  3986. implemented on top of Outline mode, which is ideal to keep the content
  3987. of large files well structured. It supports ToDo items, deadlines and
  3988. time stamps, which magically appear in the diary listing of the Emacs
  3989. calendar. Tables are easily created with a built-in table editor.
  3990. Plain text URL-like links connect to websites, emails (VM), Usenet
  3991. messages (Gnus), BBDB entries, and any files related to the project.
  3992. For printing and sharing of notes, an Org file (or a part of it)
  3993. can be exported as a structured ASCII or HTML file.
  3994. The following commands are available:
  3995. \\{org-mode-map}"
  3996. (setq-local org-mode-loading t)
  3997. (org-load-modules-maybe)
  3998. (org-install-agenda-files-menu)
  3999. (when (and org-link-descriptive
  4000. (eq org-fold-core-style 'overlays))
  4001. (add-to-invisibility-spec '(org-link)))
  4002. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4003. "..."))
  4004. (make-local-variable 'org-link-descriptive)
  4005. (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
  4006. (if org-link-descriptive
  4007. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
  4008. (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
  4009. (setq-local outline-regexp org-outline-regexp)
  4010. (setq-local outline-level 'org-outline-level)
  4011. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4012. (unless org-display-table
  4013. (setq org-display-table (make-display-table)))
  4014. (set-display-table-slot
  4015. org-display-table 4
  4016. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4017. org-ellipsis)))
  4018. (setq buffer-display-table org-display-table))
  4019. (org-set-regexps-and-options)
  4020. (org-set-font-lock-defaults)
  4021. (when (and org-tag-faces (not org-tags-special-faces-re))
  4022. ;; tag faces set outside customize.... force initialization.
  4023. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4024. ;; Calc embedded
  4025. (setq-local calc-embedded-open-mode "# ")
  4026. ;; Modify a few syntax entries
  4027. (modify-syntax-entry ?\" "\"")
  4028. (modify-syntax-entry ?\\ "_")
  4029. (modify-syntax-entry ?~ "_")
  4030. (modify-syntax-entry ?< "(>")
  4031. (modify-syntax-entry ?> ")<")
  4032. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4033. ;; Activate before-change-function
  4034. (setq-local org-table-may-need-update t)
  4035. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4036. ;; Check for running clock before killing a buffer
  4037. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4038. ;; Initialize cache.
  4039. (org-element-cache-reset)
  4040. (when (and org-element-cache-persistent
  4041. org-element-use-cache)
  4042. (org-persist-load 'org-element--cache (current-buffer) t))
  4043. ;; Initialize macros templates.
  4044. (org-macro-initialize-templates)
  4045. ;; Initialize radio targets.
  4046. (org-update-radio-target-regexp)
  4047. ;; Indentation.
  4048. (setq-local indent-line-function 'org-indent-line)
  4049. (setq-local indent-region-function 'org-indent-region)
  4050. ;; Filling and auto-filling.
  4051. (org-setup-filling)
  4052. ;; Comments.
  4053. (org-setup-comments-handling)
  4054. ;; Beginning/end of defun
  4055. (setq-local beginning-of-defun-function 'org-backward-element)
  4056. (setq-local end-of-defun-function
  4057. (lambda ()
  4058. (if (not (org-at-heading-p))
  4059. (org-forward-element)
  4060. (org-forward-element)
  4061. (forward-char -1))))
  4062. ;; Next error for sparse trees
  4063. (setq-local next-error-function 'org-occur-next-match)
  4064. ;; Make commit log messages from Org documents easier.
  4065. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4066. ;; Make sure dependence stuff works reliably, even for users who set it
  4067. ;; too late :-(
  4068. (if org-enforce-todo-dependencies
  4069. (add-hook 'org-blocker-hook
  4070. 'org-block-todo-from-children-or-siblings-or-parent)
  4071. (remove-hook 'org-blocker-hook
  4072. 'org-block-todo-from-children-or-siblings-or-parent))
  4073. (if org-enforce-todo-checkbox-dependencies
  4074. (add-hook 'org-blocker-hook
  4075. 'org-block-todo-from-checkboxes)
  4076. (remove-hook 'org-blocker-hook
  4077. 'org-block-todo-from-checkboxes))
  4078. ;; Align options lines
  4079. (setq-local
  4080. align-mode-rules-list
  4081. '((org-in-buffer-settings
  4082. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4083. (modes . '(org-mode)))))
  4084. ;; Setup the pcomplete hooks
  4085. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4086. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4087. (setq-local pcomplete-default-completion-function #'ignore)
  4088. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4089. (setq-local pcomplete-termination-string "")
  4090. (add-hook 'completion-at-point-functions
  4091. #'pcomplete-completions-at-point nil t)
  4092. (setq-local buffer-face-mode-face 'org-default)
  4093. ;; If empty file that did not turn on Org mode automatically, make
  4094. ;; it to.
  4095. (when (and org-insert-mode-line-in-empty-file
  4096. (called-interactively-p 'any)
  4097. (= (point-min) (point-max)))
  4098. (insert "# -*- mode: org -*-\n\n"))
  4099. (unless org-inhibit-startup
  4100. (org-unmodified
  4101. (when org-startup-with-beamer-mode (org-beamer-mode))
  4102. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4103. (org-table-map-tables
  4104. (cond ((and org-startup-align-all-tables
  4105. org-startup-shrink-all-tables)
  4106. (lambda () (org-table-align) (org-table-shrink)))
  4107. (org-startup-align-all-tables #'org-table-align)
  4108. (t #'org-table-shrink))
  4109. t))
  4110. (when org-startup-with-inline-images (org-display-inline-images))
  4111. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4112. (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
  4113. (when org-startup-truncated (setq truncate-lines t))
  4114. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4115. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4116. ;; Add a custom keymap for `visual-line-mode' so that activating
  4117. ;; this minor mode does not override Org's keybindings.
  4118. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4119. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4120. (newmap (make-sparse-keymap)))
  4121. (set-keymap-parent newmap oldmap)
  4122. (define-key newmap [remap move-beginning-of-line] nil)
  4123. (define-key newmap [remap move-end-of-line] nil)
  4124. (define-key newmap [remap kill-line] nil)
  4125. (make-local-variable 'minor-mode-overriding-map-alist)
  4126. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4127. ;; Activate `org-table-header-line-mode'
  4128. (when org-table-header-line-p
  4129. (org-table-header-line-mode 1))
  4130. ;; Try to set `org-hide' face correctly.
  4131. (let ((foreground (org-find-invisible-foreground)))
  4132. (when foreground
  4133. (set-face-foreground 'org-hide foreground)))
  4134. ;; Set face extension as requested.
  4135. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4136. org-fontify-whole-block-delimiter-line)
  4137. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
  4138. (setq-local org-mode-loading nil))
  4139. ;; Update `customize-package-emacs-version-alist'
  4140. (add-to-list 'customize-package-emacs-version-alist
  4141. '(Org ("8.0" . "24.4")
  4142. ("8.1" . "24.4")
  4143. ("8.2" . "24.4")
  4144. ("8.2.7" . "24.4")
  4145. ("8.3" . "26.1")
  4146. ("9.0" . "26.1")
  4147. ("9.1" . "26.1")
  4148. ("9.2" . "27.1")
  4149. ("9.3" . "27.1")
  4150. ("9.4" . "27.2")
  4151. ("9.5" . "28.1")
  4152. ("9.6" . "29.1")))
  4153. (defvar org-mode-transpose-word-syntax-table
  4154. (let ((st (make-syntax-table text-mode-syntax-table)))
  4155. (dolist (c org-emphasis-alist st)
  4156. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4157. (when (fboundp 'abbrev-table-put)
  4158. (abbrev-table-put org-mode-abbrev-table
  4159. :parents (list text-mode-abbrev-table)))
  4160. (defun org-find-invisible-foreground ()
  4161. (let ((candidates (remove
  4162. "unspecified-bg"
  4163. (nconc
  4164. (list (face-background 'default)
  4165. (face-background 'org-default))
  4166. (mapcar
  4167. (lambda (alist)
  4168. (when (boundp alist)
  4169. (cdr (assq 'background-color (symbol-value alist)))))
  4170. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4171. (list (face-foreground 'org-hide))))))
  4172. (car (remove nil candidates))))
  4173. (defun org-current-time (&optional rounding-minutes past)
  4174. "Current time, possibly rounded to ROUNDING-MINUTES.
  4175. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4176. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4177. the rounding returns a past time."
  4178. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4179. (car org-time-stamp-rounding-minutes)))
  4180. (now (current-time)))
  4181. (if (< r 1)
  4182. now
  4183. (let* ((time (decode-time now))
  4184. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4185. (nthcdr 2 time))))
  4186. (if (or (not past) (time-less-p res now))
  4187. res
  4188. (time-subtract res (* r 60)))))))
  4189. (defun org-today ()
  4190. "Return today date, considering `org-extend-today-until'."
  4191. (time-to-days
  4192. (time-since (* 3600 org-extend-today-until))))
  4193. ;;;; Font-Lock stuff, including the activators
  4194. (defconst org-match-sexp-depth 3
  4195. "Number of stacked braces for sub/superscript matching.")
  4196. (defun org-create-multibrace-regexp (left right n)
  4197. "Create a regular expression which will match a balanced sexp.
  4198. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4199. as single character strings.
  4200. The regexp returned will match the entire expression including the
  4201. delimiters. It will also define a single group which contains the
  4202. match except for the outermost delimiters. The maximum depth of
  4203. stacked delimiters is N. Escaping delimiters is not possible."
  4204. (let* ((nothing (concat "[^" left right "]*?"))
  4205. (or "\\|")
  4206. (re nothing)
  4207. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4208. (while (> n 1)
  4209. (setq n (1- n)
  4210. re (concat re or next)
  4211. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4212. (concat left "\\(" re "\\)" right)))
  4213. (defconst org-match-substring-regexp
  4214. (concat
  4215. "\\(\\S-\\)\\([_^]\\)\\("
  4216. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4217. "\\|"
  4218. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4219. "\\|"
  4220. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4221. "The regular expression matching a sub- or superscript.")
  4222. (defconst org-match-substring-with-braces-regexp
  4223. (concat
  4224. "\\(\\S-\\)\\([_^]\\)"
  4225. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4226. "The regular expression matching a sub- or superscript, forcing braces.")
  4227. (defvar org-emph-face nil)
  4228. (defun org-do-emphasis-faces (limit)
  4229. "Run through the buffer and emphasize strings."
  4230. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4231. (car org-emphasis-regexp-components))))
  4232. (catch :exit
  4233. (while (re-search-forward quick-re limit t)
  4234. (let* ((marker (match-string 2))
  4235. (verbatim? (member marker '("~" "="))))
  4236. (when (save-excursion
  4237. (goto-char (match-beginning 0))
  4238. (and
  4239. ;; Do not match table hlines.
  4240. (not (and (equal marker "+")
  4241. (org-match-line
  4242. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4243. ;; Do not match headline stars. Do not consider
  4244. ;; stars of a headline as closing marker for bold
  4245. ;; markup either.
  4246. (not (and (equal marker "*")
  4247. (save-excursion
  4248. (forward-char)
  4249. (skip-chars-backward "*")
  4250. (looking-at-p org-outline-regexp-bol))))
  4251. ;; Match full emphasis markup regexp.
  4252. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4253. ;; Do not span over paragraph boundaries.
  4254. (not (string-match-p org-element-paragraph-separate
  4255. (match-string 2)))
  4256. ;; Do not span over cells in table rows.
  4257. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4258. (string-match-p "|" (match-string 4))))))
  4259. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4260. (m (if org-hide-emphasis-markers 4 2)))
  4261. (font-lock-prepend-text-property
  4262. (match-beginning m) (match-end m) 'face face)
  4263. (when verbatim?
  4264. (org-remove-flyspell-overlays-in
  4265. (match-beginning 0) (match-end 0))
  4266. (when (and (org-fold-core-folding-spec-p 'org-link)
  4267. (org-fold-core-folding-spec-p 'org-link-description))
  4268. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
  4269. (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
  4270. (remove-text-properties (match-beginning 2) (match-end 2)
  4271. '(display t invisible t intangible t)))
  4272. (add-text-properties (match-beginning 2) (match-end 2)
  4273. '(font-lock-multiline t org-emphasis t))
  4274. (when (and org-hide-emphasis-markers
  4275. (not (org-at-comment-p)))
  4276. (add-text-properties (match-end 4) (match-beginning 5)
  4277. '(invisible t))
  4278. (add-text-properties (match-beginning 3) (match-end 3)
  4279. '(invisible t)))
  4280. (throw :exit t))))))))
  4281. (defun org-emphasize (&optional char)
  4282. "Insert or change an emphasis, i.e. a font like bold or italic.
  4283. If there is an active region, change that region to a new emphasis.
  4284. If there is no region, just insert the marker characters and position
  4285. the cursor between them.
  4286. CHAR should be the marker character. If it is a space, it means to
  4287. remove the emphasis of the selected region.
  4288. If CHAR is not given (for example in an interactive call) it will be
  4289. prompted for."
  4290. (interactive)
  4291. (let ((erc org-emphasis-regexp-components)
  4292. (string "") beg end move s)
  4293. (if (org-region-active-p)
  4294. (setq beg (region-beginning)
  4295. end (region-end)
  4296. string (buffer-substring beg end))
  4297. (setq move t))
  4298. (unless char
  4299. (message "Emphasis marker or tag: [%s]"
  4300. (mapconcat #'car org-emphasis-alist ""))
  4301. (setq char (read-char-exclusive)))
  4302. (if (equal char ?\s)
  4303. (setq s ""
  4304. move nil)
  4305. (unless (assoc (char-to-string char) org-emphasis-alist)
  4306. (user-error "No such emphasis marker: \"%c\"" char))
  4307. (setq s (char-to-string char)))
  4308. (while (and (> (length string) 1)
  4309. (equal (substring string 0 1) (substring string -1))
  4310. (assoc (substring string 0 1) org-emphasis-alist))
  4311. (setq string (substring string 1 -1)))
  4312. (setq string (concat s string s))
  4313. (when beg (delete-region beg end))
  4314. (unless (or (bolp)
  4315. (string-match (concat "[" (nth 0 erc) "\n]")
  4316. (char-to-string (char-before (point)))))
  4317. (insert " "))
  4318. (unless (or (eobp)
  4319. (string-match (concat "[" (nth 1 erc) "\n]")
  4320. (char-to-string (char-after (point)))))
  4321. (insert " ") (backward-char 1))
  4322. (insert string)
  4323. (and move (backward-char 1))))
  4324. (defconst org-nonsticky-props
  4325. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4326. (defsubst org-rear-nonsticky-at (pos)
  4327. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4328. (defun org-activate-links--overlays (limit)
  4329. "Add link properties to links.
  4330. This includes angle, plain, and bracket links."
  4331. (catch :exit
  4332. (while (re-search-forward org-link-any-re limit t)
  4333. (let* ((start (match-beginning 0))
  4334. (end (match-end 0))
  4335. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4336. (visible-end (or (match-end 3) (match-end 2)))
  4337. (style (cond ((eq ?< (char-after start)) 'angle)
  4338. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4339. (t 'plain))))
  4340. (when (and (memq style org-highlight-links)
  4341. ;; Do not span over paragraph boundaries.
  4342. (not (string-match-p org-element-paragraph-separate
  4343. (match-string 0)))
  4344. ;; Do not confuse plain links with tags.
  4345. (not (and (eq style 'plain)
  4346. (let ((face (get-text-property
  4347. (max (1- start) (point-min)) 'face)))
  4348. (if (consp face) (memq 'org-tag face)
  4349. (eq 'org-tag face))))))
  4350. (let* ((link-object (save-excursion
  4351. (goto-char start)
  4352. (save-match-data (org-element-link-parser))))
  4353. (link (org-element-property :raw-link link-object))
  4354. (type (org-element-property :type link-object))
  4355. (path (org-element-property :path link-object))
  4356. (face-property (pcase (org-link-get-parameter type :face)
  4357. ((and (pred functionp) face) (funcall face path))
  4358. ((and (pred facep) face) face)
  4359. ((and (pred consp) face) face) ;anonymous
  4360. (_ 'org-link)))
  4361. (properties ;for link's visible part
  4362. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4363. 'highlight)
  4364. 'keymap (or (org-link-get-parameter type :keymap)
  4365. org-mouse-map)
  4366. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4367. ((and (pred stringp) echo) echo)
  4368. ((and (pred functionp) echo) echo)
  4369. (_ (concat "LINK: " link)))
  4370. 'htmlize-link (pcase (org-link-get-parameter type
  4371. :htmlize-link)
  4372. ((and (pred functionp) f) (funcall f))
  4373. (_ `(:uri ,link)))
  4374. 'font-lock-multiline t)))
  4375. (org-remove-flyspell-overlays-in start end)
  4376. (org-rear-nonsticky-at end)
  4377. (if (not (eq 'bracket style))
  4378. (progn
  4379. (add-face-text-property start end face-property)
  4380. (add-text-properties start end properties))
  4381. ;; Handle invisible parts in bracket links.
  4382. (remove-text-properties start end '(invisible nil))
  4383. (let ((hidden
  4384. (append `(invisible
  4385. ,(or (org-link-get-parameter type :display)
  4386. 'org-link))
  4387. properties)))
  4388. (add-text-properties start visible-start hidden)
  4389. (add-face-text-property start end face-property)
  4390. (add-text-properties visible-start visible-end properties)
  4391. (add-text-properties visible-end end hidden)
  4392. (org-rear-nonsticky-at visible-start)
  4393. (org-rear-nonsticky-at visible-end)))
  4394. (let ((f (org-link-get-parameter type :activate-func)))
  4395. (when (functionp f)
  4396. (funcall f start end path (eq style 'bracket))))
  4397. (throw :exit t))))) ;signal success
  4398. nil))
  4399. (defun org-activate-links--text-properties (limit)
  4400. "Add link properties to links.
  4401. This includes angle, plain, and bracket links."
  4402. (catch :exit
  4403. (while (re-search-forward org-link-any-re limit t)
  4404. (let* ((start (match-beginning 0))
  4405. (end (match-end 0))
  4406. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4407. (visible-end (or (match-end 3) (match-end 2)))
  4408. (style (cond ((eq ?< (char-after start)) 'angle)
  4409. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4410. (t 'plain))))
  4411. (when (and (memq style org-highlight-links)
  4412. ;; Do not span over paragraph boundaries.
  4413. (not (string-match-p org-element-paragraph-separate
  4414. (match-string 0)))
  4415. ;; Do not confuse plain links with tags.
  4416. (not (and (eq style 'plain)
  4417. (let ((face (get-text-property
  4418. (max (1- start) (point-min)) 'face)))
  4419. (if (consp face) (memq 'org-tag face)
  4420. (eq 'org-tag face))))))
  4421. (let* ((link-object (save-excursion
  4422. (goto-char start)
  4423. (save-match-data (org-element-link-parser))))
  4424. (link (org-element-property :raw-link link-object))
  4425. (type (org-element-property :type link-object))
  4426. (path (org-element-property :path link-object))
  4427. (face-property (pcase (org-link-get-parameter type :face)
  4428. ((and (pred functionp) face) (funcall face path))
  4429. ((and (pred facep) face) face)
  4430. ((and (pred consp) face) face) ;anonymous
  4431. (_ 'org-link)))
  4432. (properties ;for link's visible part
  4433. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4434. 'highlight)
  4435. 'keymap (or (org-link-get-parameter type :keymap)
  4436. org-mouse-map)
  4437. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4438. ((and (pred stringp) echo) echo)
  4439. ((and (pred functionp) echo) echo)
  4440. (_ (concat "LINK: " link)))
  4441. 'htmlize-link (pcase (org-link-get-parameter type
  4442. :htmlize-link)
  4443. ((and (pred functionp) f) (funcall f))
  4444. (_ `(:uri ,link)))
  4445. 'font-lock-multiline t)))
  4446. (org-remove-flyspell-overlays-in start end)
  4447. (org-rear-nonsticky-at end)
  4448. (if (not (eq 'bracket style))
  4449. (progn
  4450. (add-face-text-property start end face-property)
  4451. (add-text-properties start end properties))
  4452. ;; Initialise folding when used ouside org-mode.
  4453. (unless (or (derived-mode-p 'org-mode)
  4454. (and (org-fold-folding-spec-p 'org-link-description)
  4455. (org-fold-folding-spec-p 'org-link)))
  4456. (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
  4457. "...")))
  4458. ;; Handle invisible parts in bracket links.
  4459. (let ((spec (or (org-link-get-parameter type :display)
  4460. 'org-link)))
  4461. (unless (org-fold-folding-spec-p spec)
  4462. (org-fold-add-folding-spec spec
  4463. (cdr org-link--link-folding-spec)
  4464. nil
  4465. 'append)
  4466. (org-fold-core-set-folding-spec-property spec :visible t))
  4467. (org-fold-region start end nil 'org-link)
  4468. (org-fold-region start end nil 'org-link-description)
  4469. ;; We are folding the whole emphasised text with SPEC
  4470. ;; first. It makes everything invisible (or whatever
  4471. ;; the user wants).
  4472. (org-fold-region start end t spec)
  4473. ;; The visible part of the text is folded using
  4474. ;; 'org-link-description, which is forcing this part of
  4475. ;; the text to be visible.
  4476. (org-fold-region visible-start visible-end t 'org-link-description)
  4477. (add-text-properties start end properties)
  4478. (add-face-text-property start end face-property)
  4479. (org-rear-nonsticky-at visible-start)
  4480. (org-rear-nonsticky-at visible-end)))
  4481. (let ((f (org-link-get-parameter type :activate-func)))
  4482. (when (functionp f)
  4483. (funcall f start end path (eq style 'bracket))))
  4484. (throw :exit t))))) ;signal success
  4485. nil))
  4486. (defsubst org-activate-links (limit)
  4487. "Add link properties to links.
  4488. This includes angle, plain, and bracket links."
  4489. (if (eq org-fold-core-style 'text-properties)
  4490. (org-activate-links--text-properties limit)
  4491. (org-activate-links--overlays limit)))
  4492. (defun org-activate-code (limit)
  4493. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4494. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4495. (remove-text-properties (match-beginning 0) (match-end 0)
  4496. '(display t invisible t intangible t))
  4497. t))
  4498. (defcustom org-src-fontify-natively t
  4499. "When non-nil, fontify code in code blocks.
  4500. See also the `org-block' face."
  4501. :type 'boolean
  4502. :version "26.1"
  4503. :package-version '(Org . "8.3")
  4504. :group 'org-appearance
  4505. :group 'org-babel)
  4506. (defcustom org-allow-promoting-top-level-subtree nil
  4507. "When non-nil, allow promoting a top level subtree.
  4508. The leading star of the top level headline will be replaced
  4509. by a #."
  4510. :type 'boolean
  4511. :version "24.1"
  4512. :group 'org-appearance)
  4513. (defun org-fontify-meta-lines-and-blocks (limit)
  4514. (condition-case nil
  4515. (org-fontify-meta-lines-and-blocks-1 limit)
  4516. (error (message "Org mode fontification error in %S at %d"
  4517. (current-buffer)
  4518. (line-number-at-pos)))))
  4519. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4520. "Fontify #+ lines and blocks."
  4521. (let ((case-fold-search t))
  4522. (when (re-search-forward
  4523. (rx bol (group (zero-or-more (any " \t")) "#"
  4524. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4525. (any " \t")
  4526. eol))
  4527. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4528. (zero-or-more (any " \t"))
  4529. (group (group (zero-or-more (not (any " \t\n"))))
  4530. (zero-or-more (any " \t"))
  4531. (group (zero-or-more any)))))
  4532. limit t)
  4533. (let ((beg (match-beginning 0))
  4534. (end-of-beginline (match-end 0))
  4535. ;; Including \n at end of #+begin line will include \n
  4536. ;; after the end of block content.
  4537. (block-start (match-end 0))
  4538. (block-end nil)
  4539. (lang (match-string 7)) ; The language, if it is a source block.
  4540. (bol-after-beginline (line-beginning-position 2))
  4541. (dc1 (downcase (match-string 2)))
  4542. (dc3 (downcase (match-string 3)))
  4543. (whole-blockline org-fontify-whole-block-delimiter-line)
  4544. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4545. (cond
  4546. ((and (match-end 4) (equal dc3 "+begin"))
  4547. ;; Truly a block
  4548. (setq block-type (downcase (match-string 5))
  4549. ;; Src, example, export, maybe more.
  4550. quoting (member block-type org-protecting-blocks))
  4551. (when (re-search-forward
  4552. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4553. (seq (zero-or-more (any " \t"))
  4554. "#+end"
  4555. ,(match-string 4)
  4556. word-end
  4557. (zero-or-more any)))))
  4558. ;; We look further than LIMIT on purpose.
  4559. nil t)
  4560. ;; We do have a matching #+end line.
  4561. (setq beg-of-endline (match-beginning 0)
  4562. end-of-endline (match-end 0)
  4563. nl-before-endline (1- (match-beginning 0)))
  4564. (setq block-end (match-beginning 0)) ; Include the final newline.
  4565. (when quoting
  4566. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4567. (remove-text-properties beg end-of-endline
  4568. '(display t invisible t intangible t)))
  4569. (add-text-properties
  4570. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4571. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4572. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4573. (cond
  4574. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4575. (save-match-data
  4576. (org-src-font-lock-fontify-block lang block-start block-end))
  4577. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4578. (quoting
  4579. (add-text-properties
  4580. bol-after-beginline beg-of-endline
  4581. (list 'face
  4582. (list :inherit
  4583. (let ((face-name
  4584. (intern (format "org-block-%s" lang))))
  4585. (append (and (facep face-name) (list face-name))
  4586. '(org-block)))))))
  4587. ((not org-fontify-quote-and-verse-blocks))
  4588. ((string= block-type "quote")
  4589. (add-face-text-property
  4590. bol-after-beginline beg-of-endline 'org-quote t))
  4591. ((string= block-type "verse")
  4592. (add-face-text-property
  4593. bol-after-beginline beg-of-endline 'org-verse t)))
  4594. ;; Fontify the #+begin and #+end lines of the blocks
  4595. (add-text-properties
  4596. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4597. '(face org-block-begin-line))
  4598. (unless (eq (char-after beg-of-endline) ?*)
  4599. (add-text-properties
  4600. beg-of-endline
  4601. (if whole-blockline
  4602. (let ((beg-of-next-line (1+ end-of-endline)))
  4603. (min (point-max) beg-of-next-line))
  4604. (min (point-max) end-of-endline))
  4605. '(face org-block-end-line)))
  4606. t))
  4607. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4608. (org-remove-flyspell-overlays-in
  4609. (match-beginning 0)
  4610. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4611. (add-text-properties
  4612. beg (match-end 3)
  4613. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4614. '(font-lock-fontified t invisible t)
  4615. '(font-lock-fontified t face org-document-info-keyword)))
  4616. (add-text-properties
  4617. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4618. (if (string-equal dc1 "+title:")
  4619. '(font-lock-fontified t face org-document-title)
  4620. '(font-lock-fontified t face org-document-info))))
  4621. ((string-prefix-p "+caption" dc1)
  4622. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4623. (remove-text-properties (match-beginning 0) (match-end 0)
  4624. '(display t invisible t intangible t))
  4625. ;; Handle short captions
  4626. (save-excursion
  4627. (beginning-of-line)
  4628. (looking-at (rx (group (zero-or-more (any " \t"))
  4629. "#+caption"
  4630. (optional "[" (zero-or-more any) "]")
  4631. ":")
  4632. (zero-or-more (any " \t")))))
  4633. (add-text-properties (line-beginning-position) (match-end 1)
  4634. '(font-lock-fontified t face org-meta-line))
  4635. (add-text-properties (match-end 0) (line-end-position)
  4636. '(font-lock-fontified t face org-block))
  4637. t)
  4638. ((member dc3 '(" " ""))
  4639. ;; Just a comment, the plus was not there
  4640. (org-remove-flyspell-overlays-in beg (match-end 0))
  4641. (add-text-properties
  4642. beg (match-end 0)
  4643. '(font-lock-fontified t face font-lock-comment-face)))
  4644. (t ;; Just any other in-buffer setting, but not indented
  4645. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4646. (remove-text-properties (match-beginning 0) (match-end 0)
  4647. '(display t invisible t intangible t))
  4648. (add-text-properties beg (match-end 0)
  4649. '(font-lock-fontified t face org-meta-line))
  4650. t))))))
  4651. (defun org-fontify-drawers (limit)
  4652. "Fontify drawers."
  4653. (when (re-search-forward org-drawer-regexp limit t)
  4654. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4655. '(font-lock-fontified t face org-drawer))
  4656. (org-remove-flyspell-overlays-in
  4657. (line-beginning-position) (line-beginning-position 2))
  4658. t))
  4659. (defun org-fontify-macros (limit)
  4660. "Fontify macros."
  4661. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4662. (let ((begin (match-beginning 0))
  4663. (opening-end (match-beginning 1)))
  4664. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4665. (match-string 1))
  4666. (let ((end (match-end 1))
  4667. (closing-start (match-beginning 1)))
  4668. (add-text-properties
  4669. begin end
  4670. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4671. (org-remove-flyspell-overlays-in begin end)
  4672. (when org-hide-macro-markers
  4673. (add-text-properties begin opening-end '(invisible t))
  4674. (add-text-properties closing-start end '(invisible t)))
  4675. t)))))
  4676. (defun org-fontify-extend-region (beg end _old-len)
  4677. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4678. (1+ end) end))
  4679. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4680. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4681. (extend
  4682. (lambda (r1 r2 dir)
  4683. (let ((re (replace-regexp-in-string
  4684. "\\(begin\\|end\\)" r1
  4685. (replace-regexp-in-string
  4686. "[][]" r2
  4687. (match-string-no-properties 0)))))
  4688. (re-search-forward (regexp-quote re) nil t dir)))))
  4689. (goto-char beg)
  4690. (back-to-indentation)
  4691. (save-match-data
  4692. (cond ((looking-at end-re)
  4693. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4694. ((looking-at begin-re)
  4695. (cons beg (or (funcall extend "end" "]" 1) end)))
  4696. (t (cons beg end))))))
  4697. (defun org-activate-footnote-links (limit)
  4698. "Add text properties for footnotes."
  4699. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4700. (when fn
  4701. (let* ((beg (nth 1 fn))
  4702. (end (nth 2 fn))
  4703. (label (car fn))
  4704. (referencep (/= (line-beginning-position) beg)))
  4705. (when (and referencep (nth 3 fn))
  4706. (save-excursion
  4707. (goto-char beg)
  4708. (search-forward (or label "fn:"))
  4709. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4710. (add-text-properties beg end
  4711. (list 'mouse-face 'highlight
  4712. 'keymap org-mouse-map
  4713. 'help-echo
  4714. (if referencep "Footnote reference"
  4715. "Footnote definition")
  4716. 'font-lock-fontified t
  4717. 'font-lock-multiline t
  4718. 'face 'org-footnote))))))
  4719. (defun org-activate-dates (limit)
  4720. "Add text properties for dates."
  4721. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4722. (not (equal (char-before (match-beginning 0)) 91)))
  4723. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4724. (add-text-properties (match-beginning 0) (match-end 0)
  4725. (list 'mouse-face 'highlight
  4726. 'keymap org-mouse-map))
  4727. (org-rear-nonsticky-at (match-end 0))
  4728. (when org-display-custom-times
  4729. ;; If it's a date range, activate custom time for second date.
  4730. (when (match-end 3)
  4731. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4732. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4733. t))
  4734. (defun org-activate-target-links (limit)
  4735. "Add text properties for target matches."
  4736. (when org-target-link-regexp
  4737. (let ((case-fold-search t))
  4738. ;; `org-target-link-regexp' matches one character before the
  4739. ;; actual target.
  4740. (unless (bolp) (forward-char -1))
  4741. (when (re-search-forward org-target-link-regexp limit t)
  4742. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4743. (add-text-properties (match-beginning 1) (match-end 1)
  4744. (list 'mouse-face 'highlight
  4745. 'keymap org-mouse-map
  4746. 'help-echo "Radio target link"
  4747. 'org-linked-text t))
  4748. (org-rear-nonsticky-at (match-end 1))
  4749. t))))
  4750. (defvar org-latex-and-related-regexp nil
  4751. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4752. (defun org-compute-latex-and-related-regexp ()
  4753. "Compute regular expression for LaTeX, entities and sub/superscript.
  4754. Result depends on variable `org-highlight-latex-and-related'."
  4755. (let ((re-sub
  4756. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4757. ((eq org-use-sub-superscripts '{})
  4758. (list org-match-substring-with-braces-regexp))
  4759. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4760. (re-latex
  4761. (when (or (memq 'latex org-highlight-latex-and-related)
  4762. (memq 'native org-highlight-latex-and-related))
  4763. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4764. (delq nil
  4765. (mapcar (lambda (x)
  4766. (and (member (car x) matchers) (nth 1 x)))
  4767. org-latex-regexps)))))
  4768. (re-entities
  4769. (when (memq 'entities org-highlight-latex-and-related)
  4770. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4771. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4772. (setq-local org-latex-and-related-regexp
  4773. (mapconcat #'identity
  4774. (append re-latex re-entities re-sub)
  4775. "\\|"))))
  4776. (defun org-do-latex-and-related (limit)
  4777. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4778. Stop at first highlighted object, if any. Return t if some
  4779. highlighting was done, nil otherwise."
  4780. (when (org-string-nw-p org-latex-and-related-regexp)
  4781. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4782. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4783. (catch 'found
  4784. (while (and (< (point) limit)
  4785. (re-search-forward org-latex-and-related-regexp nil t))
  4786. (cond
  4787. ((>= (match-beginning 0) limit)
  4788. (throw 'found nil))
  4789. ((cl-some (lambda (f)
  4790. (memq f '(org-code org-verbatim underline
  4791. org-special-keyword)))
  4792. (save-excursion
  4793. (goto-char (1+ (match-beginning 0)))
  4794. (face-at-point nil t))))
  4795. ;; Try to limit false positives. In this case, ignore
  4796. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4797. ;; contain an empty line.
  4798. ((save-excursion
  4799. (goto-char (match-beginning 0))
  4800. (and (looking-at-p latex-prefix-re)
  4801. (save-match-data
  4802. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4803. (t
  4804. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4805. '(?_ ?^))
  4806. 1
  4807. 0))
  4808. (start (+ offset (match-beginning 0)))
  4809. (end (match-end 0)))
  4810. (if (memq 'native org-highlight-latex-and-related)
  4811. (org-src-font-lock-fontify-block "latex" start end)
  4812. (font-lock-prepend-text-property start end
  4813. 'face 'org-latex-and-related))
  4814. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4815. '(font-lock-multiline t))
  4816. (throw 'found t)))))
  4817. nil))))
  4818. (defun org-restart-font-lock ()
  4819. "Restart `font-lock-mode', to force refontification."
  4820. (when font-lock-mode
  4821. (font-lock-mode -1)
  4822. (font-lock-mode 1)))
  4823. (defun org-activate-tags (limit)
  4824. (when (re-search-forward org-tag-line-re limit t)
  4825. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4826. (add-text-properties (match-beginning 1) (match-end 1)
  4827. (list 'mouse-face 'highlight
  4828. 'keymap org-mouse-map))
  4829. (org-rear-nonsticky-at (match-end 1))
  4830. t))
  4831. (defun org-outline-level ()
  4832. "Compute the outline level of the heading at point.
  4833. If this is called at a normal headline, the level is the number
  4834. of stars. Use `org-reduced-level' to remove the effect of
  4835. `org-odd-levels'. Unlike to `org-current-level', this function
  4836. takes into consideration inlinetasks."
  4837. (org-with-wide-buffer
  4838. (end-of-line)
  4839. (if (re-search-backward org-outline-regexp-bol nil t)
  4840. (1- (- (match-end 0) (match-beginning 0)))
  4841. 0)))
  4842. (defvar org-font-lock-keywords nil)
  4843. (defsubst org-re-property (property &optional literal allow-null value)
  4844. "Return a regexp matching a PROPERTY line.
  4845. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4846. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4847. non-nil, match properties even without a value.
  4848. Match group 3 is set to the value when it exists. If there is no
  4849. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4850. With optional argument VALUE, match only property lines with
  4851. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4852. unless LITERAL is non-nil."
  4853. (concat
  4854. "^\\(?4:[ \t]*\\)"
  4855. (format "\\(?1::\\(?2:%s\\):\\)"
  4856. (if literal property (regexp-quote property)))
  4857. (cond (value
  4858. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4859. (if literal value (regexp-quote value))))
  4860. (allow-null
  4861. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4862. (t
  4863. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4864. (defconst org-property-re
  4865. (org-re-property "\\S-+" 'literal t)
  4866. "Regular expression matching a property line.
  4867. There are four matching groups:
  4868. 1: :PROPKEY: including the leading and trailing colon,
  4869. 2: PROPKEY without the leading and trailing colon,
  4870. 3: PROPVAL without leading or trailing spaces,
  4871. 4: the indentation of the current line,
  4872. 5: trailing whitespace.")
  4873. (defvar org-font-lock-hook nil
  4874. "Functions to be called for special font lock stuff.")
  4875. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4876. (defvar org-font-lock-set-keywords-hook nil
  4877. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4878. This is called after `org-font-lock-extra-keywords' is defined, but before
  4879. it is installed to be used by font lock. This can be useful if something
  4880. needs to be inserted at a specific position in the font-lock sequence.")
  4881. (defun org-font-lock-hook (limit)
  4882. "Run `org-font-lock-hook' within LIMIT."
  4883. (run-hook-with-args 'org-font-lock-hook limit))
  4884. (defun org-set-font-lock-defaults ()
  4885. "Set font lock defaults for the current buffer."
  4886. (let ((org-font-lock-extra-keywords
  4887. (list
  4888. ;; Call the hook
  4889. '(org-font-lock-hook)
  4890. ;; Headlines
  4891. `(,(if org-fontify-whole-heading-line
  4892. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4893. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4894. (1 (org-get-level-face 1))
  4895. (2 (org-get-level-face 2))
  4896. (3 (org-get-level-face 3)))
  4897. ;; Table lines
  4898. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4899. (1 'org-table t))
  4900. ;; Table internals
  4901. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4902. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4903. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4904. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4905. ;; Properties
  4906. (list org-property-re
  4907. '(1 'org-special-keyword t)
  4908. '(3 'org-property-value t))
  4909. ;; Drawers
  4910. '(org-fontify-drawers)
  4911. ;; Link related fontification.
  4912. '(org-activate-links)
  4913. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4914. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4915. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4916. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  4917. ;; Targets.
  4918. (list org-radio-target-regexp '(0 'org-target t))
  4919. (list org-target-regexp '(0 'org-target t))
  4920. ;; Diary sexps.
  4921. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  4922. ;; Macro
  4923. '(org-fontify-macros)
  4924. ;; TODO keyword
  4925. (list (format org-heading-keyword-regexp-format
  4926. org-todo-regexp)
  4927. '(2 (org-get-todo-face 2) prepend))
  4928. ;; TODO
  4929. (when org-fontify-todo-headline
  4930. (list (format org-heading-keyword-regexp-format
  4931. (concat
  4932. "\\(?:"
  4933. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  4934. "\\)"))
  4935. '(2 'org-headline-todo prepend)))
  4936. ;; DONE
  4937. (when org-fontify-done-headline
  4938. (list (format org-heading-keyword-regexp-format
  4939. (concat
  4940. "\\(?:"
  4941. (mapconcat 'regexp-quote org-done-keywords "\\|")
  4942. "\\)"))
  4943. '(2 'org-headline-done prepend)))
  4944. ;; Priorities
  4945. '(org-font-lock-add-priority-faces)
  4946. ;; Tags
  4947. '(org-font-lock-add-tag-faces)
  4948. ;; Tags groups
  4949. (when (and org-group-tags org-tag-groups-alist)
  4950. (list (concat org-outline-regexp-bol ".+\\(:"
  4951. (regexp-opt (mapcar 'car org-tag-groups-alist))
  4952. ":\\).*$")
  4953. '(1 'org-tag-group prepend)))
  4954. ;; Special keywords
  4955. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  4956. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  4957. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  4958. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  4959. ;; Emphasis
  4960. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  4961. ;; Checkboxes
  4962. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  4963. 1 'org-checkbox prepend)
  4964. (when (cdr (assq 'checkbox org-list-automatic-rules))
  4965. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  4966. (0 (org-get-checkbox-statistics-face) prepend)))
  4967. ;; Description list items
  4968. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  4969. 1 'org-list-dt prepend)
  4970. ;; Inline export snippets
  4971. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  4972. (1 'font-lock-comment-face t)
  4973. (2 'org-tag t)
  4974. (3 'font-lock-comment-face t))
  4975. ;; ARCHIVEd headings
  4976. (list (concat
  4977. org-outline-regexp-bol
  4978. "\\(.*:" org-archive-tag ":.*\\)")
  4979. '(1 'org-archived prepend))
  4980. ;; Specials
  4981. '(org-do-latex-and-related)
  4982. '(org-fontify-entities)
  4983. '(org-raise-scripts)
  4984. ;; Code
  4985. '(org-activate-code (1 'org-code t))
  4986. ;; COMMENT
  4987. (list (format
  4988. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  4989. org-todo-regexp
  4990. org-comment-string)
  4991. '(9 'org-special-keyword t))
  4992. ;; Blocks and meta lines
  4993. '(org-fontify-meta-lines-and-blocks)
  4994. '(org-fontify-inline-src-blocks)
  4995. ;; Citations. When an activate processor is specified, if
  4996. ;; specified, try loading it beforehand.
  4997. (progn
  4998. (unless (null org-cite-activate-processor)
  4999. (org-cite-try-load-processor org-cite-activate-processor))
  5000. '(org-cite-activate)))))
  5001. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5002. (run-hooks 'org-font-lock-set-keywords-hook)
  5003. ;; Now set the full font-lock-keywords
  5004. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5005. (setq-local font-lock-defaults
  5006. '(org-font-lock-keywords t nil nil backward-paragraph))
  5007. (setq-local font-lock-extend-after-change-region-function
  5008. #'org-fontify-extend-region)
  5009. (kill-local-variable 'font-lock-keywords)
  5010. nil))
  5011. (defun org-toggle-pretty-entities ()
  5012. "Toggle the composition display of entities as UTF8 characters."
  5013. (interactive)
  5014. (setq-local org-pretty-entities (not org-pretty-entities))
  5015. (org-restart-font-lock)
  5016. (if org-pretty-entities
  5017. (message "Entities are now displayed as UTF8 characters")
  5018. (save-restriction
  5019. (widen)
  5020. (decompose-region (point-min) (point-max))
  5021. (message "Entities are now displayed as plain text"))))
  5022. (defvar-local org-custom-properties-overlays nil
  5023. "List of overlays used for custom properties.")
  5024. (defun org-toggle-custom-properties-visibility ()
  5025. "Display or hide properties in `org-custom-properties'."
  5026. (interactive)
  5027. (if org-custom-properties-overlays
  5028. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5029. (setq org-custom-properties-overlays nil))
  5030. (when org-custom-properties
  5031. (org-with-wide-buffer
  5032. (goto-char (point-min))
  5033. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5034. (while (re-search-forward regexp nil t)
  5035. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5036. (when (and end (< (point) end))
  5037. ;; Hide first custom property in current drawer.
  5038. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5039. (overlay-put o 'invisible t)
  5040. (overlay-put o 'org-custom-property t)
  5041. (push o org-custom-properties-overlays))
  5042. ;; Hide additional custom properties in the same drawer.
  5043. (while (re-search-forward regexp end t)
  5044. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5045. (overlay-put o 'invisible t)
  5046. (overlay-put o 'org-custom-property t)
  5047. (push o org-custom-properties-overlays)))))
  5048. ;; Each entry is limited to a single property drawer.
  5049. (outline-next-heading)))))))
  5050. (defun org-fontify-entities (limit)
  5051. "Find an entity to fontify."
  5052. (let (ee)
  5053. (when org-pretty-entities
  5054. (catch 'match
  5055. ;; "\_ "-family is left out on purpose. Only the first one,
  5056. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5057. ;; confusing when adding a second white space character.
  5058. (while (re-search-forward
  5059. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5060. limit t)
  5061. (when (and (not (org-at-comment-p))
  5062. (setq ee (org-entity-get (match-string 1)))
  5063. (= (length (nth 6 ee)) 1))
  5064. (let* ((end (if (equal (match-string 2) "{}")
  5065. (match-end 2)
  5066. (match-end 1))))
  5067. (add-text-properties
  5068. (match-beginning 0) end
  5069. (list 'font-lock-fontified t))
  5070. (compose-region (match-beginning 0) end
  5071. (nth 6 ee) nil)
  5072. (backward-char 1)
  5073. (throw 'match t))))
  5074. nil))))
  5075. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5076. "Fontify string S like in Org mode."
  5077. (with-temp-buffer
  5078. (insert s)
  5079. (let ((org-odd-levels-only odd-levels))
  5080. (org-mode)
  5081. (org-font-lock-ensure)
  5082. (if org-link-descriptive
  5083. (org-link-display-format
  5084. (buffer-string))
  5085. (buffer-string)))))
  5086. (defun org-get-level-face (n)
  5087. "Get the right face for match N in font-lock matching of headlines."
  5088. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5089. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5090. (org-f (if org-cycle-level-faces
  5091. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5092. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5093. (cond
  5094. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5095. ((eq n 2) org-f)
  5096. (t (unless org-level-color-stars-only org-f)))))
  5097. (defun org-face-from-face-or-color (context inherit face-or-color)
  5098. "Create a face list that inherits INHERIT, but sets the foreground color.
  5099. When FACE-OR-COLOR is not a string, just return it."
  5100. (if (stringp face-or-color)
  5101. (list :inherit inherit
  5102. (cdr (assoc context org-faces-easy-properties))
  5103. face-or-color)
  5104. face-or-color))
  5105. (defun org-get-todo-face (kwd)
  5106. "Get the right face for a TODO keyword KWD.
  5107. If KWD is a number, get the corresponding match group."
  5108. (when (numberp kwd) (setq kwd (match-string kwd)))
  5109. (or (org-face-from-face-or-color
  5110. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5111. (and (member kwd org-done-keywords) 'org-done)
  5112. 'org-todo))
  5113. (defun org-get-priority-face (priority)
  5114. "Get the right face for PRIORITY.
  5115. PRIORITY is a character."
  5116. (or (org-face-from-face-or-color
  5117. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5118. 'org-priority))
  5119. (defun org-get-tag-face (tag)
  5120. "Get the right face for TAG.
  5121. If TAG is a number, get the corresponding match group."
  5122. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5123. (or (org-face-from-face-or-color
  5124. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5125. 'org-tag)))
  5126. (defvar org-priority-regexp) ; defined later in the file
  5127. (defun org-font-lock-add-priority-faces (limit)
  5128. "Add the special priority faces."
  5129. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5130. (let ((beg (match-beginning 1))
  5131. (end (1+ (match-end 2))))
  5132. (add-face-text-property
  5133. beg end
  5134. (org-get-priority-face (string-to-char (match-string 2))))
  5135. (add-text-properties
  5136. beg end
  5137. (list 'font-lock-fontified t)))))
  5138. (defun org-font-lock-add-tag-faces (limit)
  5139. "Add the special tag faces."
  5140. (when (and org-tag-faces org-tags-special-faces-re)
  5141. (while (re-search-forward org-tags-special-faces-re limit t)
  5142. (add-face-text-property
  5143. (match-beginning 1)
  5144. (match-end 1)
  5145. (org-get-tag-face 1))
  5146. (add-text-properties (match-beginning 1) (match-end 1)
  5147. (list 'font-lock-fontified t))
  5148. (backward-char 1))))
  5149. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5150. "Remove fontification and activation overlays from links."
  5151. (font-lock-default-unfontify-region beg end)
  5152. (let* ((buffer-undo-list t)
  5153. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5154. (inhibit-modification-hooks t)
  5155. deactivate-mark buffer-file-name buffer-file-truename)
  5156. (decompose-region beg end)
  5157. (remove-text-properties beg end
  5158. '(mouse-face t keymap t org-linked-text t
  5159. invisible t intangible t
  5160. org-emphasis t))
  5161. (org-fold-core-update-optimisation beg end)
  5162. (org-remove-font-lock-display-properties beg end)))
  5163. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5164. ((raise 0.3) (height 0.7))
  5165. ((raise -0.5))
  5166. ((raise 0.5)))
  5167. "Display properties for showing superscripts and subscripts.")
  5168. (defun org-remove-font-lock-display-properties (beg end)
  5169. "Remove specific display properties that have been added by font lock.
  5170. The will remove the raise properties that are used to show superscripts
  5171. and subscripts."
  5172. (let (next prop)
  5173. (while (< beg end)
  5174. (setq next (next-single-property-change beg 'display nil end)
  5175. prop (get-text-property beg 'display))
  5176. (when (member prop org-script-display)
  5177. (put-text-property beg next 'display nil))
  5178. (setq beg next))))
  5179. (defun org-raise-scripts (limit)
  5180. "Add raise properties to sub/superscripts."
  5181. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5182. (re-search-forward
  5183. (if (eq org-use-sub-superscripts t)
  5184. org-match-substring-regexp
  5185. org-match-substring-with-braces-regexp)
  5186. limit t))
  5187. (let* ((pos (point)) table-p comment-p
  5188. (mpos (match-beginning 3))
  5189. (emph-p (get-text-property mpos 'org-emphasis))
  5190. (link-p (get-text-property mpos 'mouse-face))
  5191. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5192. (goto-char (point-at-bol))
  5193. (setq table-p (looking-at-p org-table-dataline-regexp)
  5194. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5195. (goto-char pos)
  5196. ;; Handle a_b^c
  5197. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5198. (unless (or comment-p emph-p link-p keyw-p)
  5199. (put-text-property (match-beginning 3) (match-end 0)
  5200. 'display
  5201. (if (equal (char-after (match-beginning 2)) ?^)
  5202. (nth (if table-p 3 1) org-script-display)
  5203. (nth (if table-p 2 0) org-script-display)))
  5204. (put-text-property (match-beginning 2) (match-end 3)
  5205. 'org-emphasis t)
  5206. (add-text-properties (match-beginning 2) (match-end 2)
  5207. (list 'invisible t))
  5208. (when (and (eq (char-after (match-beginning 3)) ?{)
  5209. (eq (char-before (match-end 3)) ?}))
  5210. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5211. (list 'invisible t))
  5212. (add-text-properties (1- (match-end 3)) (match-end 3)
  5213. (list 'invisible t))))
  5214. t)))
  5215. (defun org-remove-empty-overlays-at (pos)
  5216. "Remove outline overlays that do not contain non-white stuff."
  5217. (dolist (o (overlays-at pos))
  5218. (and (eq 'outline (overlay-get o 'invisible))
  5219. (not (string-match-p
  5220. "\\S-" (buffer-substring (overlay-start o)
  5221. (overlay-end o))))
  5222. (delete-overlay o))))
  5223. ;; FIXME: This function is unused.
  5224. (defun org-show-empty-lines-in-parent ()
  5225. "Move to the parent and re-show empty lines before visible headlines."
  5226. (save-excursion
  5227. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5228. (org-cycle-show-empty-lines context))))
  5229. (defun org-files-list ()
  5230. "Return `org-agenda-files' list, plus all open Org files.
  5231. This is useful for operations that need to scan all of a user's
  5232. open and agenda-wise Org files."
  5233. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5234. (dolist (buf (buffer-list))
  5235. (with-current-buffer buf
  5236. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5237. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5238. :test #'equal))))
  5239. files))
  5240. (defsubst org-entry-beginning-position ()
  5241. "Return the beginning position of the current entry."
  5242. (save-excursion (org-back-to-heading t) (point)))
  5243. (defsubst org-entry-end-position ()
  5244. "Return the end position of the current entry."
  5245. (save-excursion (outline-next-heading) (point)))
  5246. (defun org-subtree-end-visible-p ()
  5247. "Is the end of the current subtree visible?"
  5248. (pos-visible-in-window-p
  5249. (save-excursion (org-end-of-subtree t) (point))))
  5250. (defun org-first-headline-recenter ()
  5251. "Move cursor to the first headline and recenter the headline."
  5252. (let ((window (get-buffer-window)))
  5253. (when window
  5254. (goto-char (point-min))
  5255. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5256. (set-window-start window (line-beginning-position))))))
  5257. ;; FIXME: It was in the middle of visibility section. Where should it go to?
  5258. (defvar org-called-with-limited-levels nil
  5259. "Non-nil when `org-with-limited-levels' is currently active.")
  5260. ;;; Indirect buffer display of subtrees
  5261. (defvar org-indirect-dedicated-frame nil
  5262. "This is the frame being used for indirect tree display.")
  5263. (defvar org-last-indirect-buffer nil)
  5264. (defun org-tree-to-indirect-buffer (&optional arg)
  5265. "Create indirect buffer and narrow it to current subtree.
  5266. With a numerical prefix ARG, go up to this level and then take that tree.
  5267. If ARG is negative, go up that many levels.
  5268. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  5269. indirect buffer previously made with this command, to avoid proliferation of
  5270. indirect buffers. However, when you call the command with a \
  5271. `\\[universal-argument]' prefix, or
  5272. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  5273. so that you can work with several indirect buffers at the same time. If
  5274. `org-indirect-buffer-display' is `dedicated-frame', the \
  5275. `\\[universal-argument]' prefix also
  5276. requests that a new frame be made for the new buffer, so that the dedicated
  5277. frame is not changed."
  5278. (interactive "P")
  5279. (let ((cbuf (current-buffer))
  5280. (cwin (selected-window))
  5281. (pos (point))
  5282. beg end level heading ibuf)
  5283. (save-excursion
  5284. (org-back-to-heading t)
  5285. (when (numberp arg)
  5286. (setq level (org-outline-level))
  5287. (when (< arg 0) (setq arg (+ level arg)))
  5288. (while (> (setq level (org-outline-level)) arg)
  5289. (org-up-heading-safe)))
  5290. (setq beg (point)
  5291. heading (org-get-heading 'no-tags))
  5292. (org-end-of-subtree t t)
  5293. (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
  5294. (setq end (point)))
  5295. (when (and (buffer-live-p org-last-indirect-buffer)
  5296. (not (eq org-indirect-buffer-display 'new-frame))
  5297. (not arg))
  5298. (kill-buffer org-last-indirect-buffer))
  5299. (setq ibuf (org-get-indirect-buffer cbuf heading)
  5300. org-last-indirect-buffer ibuf)
  5301. (cond
  5302. ((or (eq org-indirect-buffer-display 'new-frame)
  5303. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  5304. (select-frame (make-frame))
  5305. (delete-other-windows)
  5306. (pop-to-buffer-same-window ibuf)
  5307. (org-set-frame-title heading))
  5308. ((eq org-indirect-buffer-display 'dedicated-frame)
  5309. (raise-frame
  5310. (select-frame (or (and org-indirect-dedicated-frame
  5311. (frame-live-p org-indirect-dedicated-frame)
  5312. org-indirect-dedicated-frame)
  5313. (setq org-indirect-dedicated-frame (make-frame)))))
  5314. (delete-other-windows)
  5315. (pop-to-buffer-same-window ibuf)
  5316. (org-set-frame-title (concat "Indirect: " heading)))
  5317. ((eq org-indirect-buffer-display 'current-window)
  5318. (pop-to-buffer-same-window ibuf))
  5319. ((eq org-indirect-buffer-display 'other-window)
  5320. (pop-to-buffer ibuf))
  5321. (t (error "Invalid value")))
  5322. (narrow-to-region beg end)
  5323. (org-fold-show-all '(headings drawers blocks))
  5324. (goto-char pos)
  5325. (run-hook-with-args 'org-cycle-hook 'all)
  5326. (and (window-live-p cwin) (select-window cwin))))
  5327. (defun org-get-indirect-buffer (&optional buffer heading)
  5328. (setq buffer (or buffer (current-buffer)))
  5329. (let ((n 1) (base (buffer-name buffer)) bname)
  5330. (while (buffer-live-p
  5331. (get-buffer
  5332. (setq bname
  5333. (concat base "-"
  5334. (if heading (concat heading "-" (number-to-string n))
  5335. (number-to-string n))))))
  5336. (setq n (1+ n)))
  5337. (condition-case nil
  5338. (let ((indirect-buffer (make-indirect-buffer buffer bname 'clone)))
  5339. ;; Decouple folding state. We need to do it manually since
  5340. ;; `make-indirect-buffer' does not run
  5341. ;; `clone-indirect-buffer-hook'.
  5342. (org-fold-core-decouple-indirect-buffer-folds)
  5343. ;; Return the buffer.
  5344. indirect-buffer)
  5345. (error (make-indirect-buffer buffer bname)))))
  5346. (defun org-set-frame-title (title)
  5347. "Set the title of the current frame to the string TITLE."
  5348. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  5349. ;;;; Structure editing
  5350. ;;; Inserting headlines
  5351. (defun org--blank-before-heading-p (&optional parent)
  5352. "Non-nil when an empty line should precede a new heading here.
  5353. When optional argument PARENT is non-nil, consider parent
  5354. headline instead of current one."
  5355. (pcase (assq 'heading org-blank-before-new-entry)
  5356. (`(heading . auto)
  5357. (save-excursion
  5358. (org-with-limited-levels
  5359. (unless (and (org-before-first-heading-p)
  5360. (not (outline-next-heading)))
  5361. (org-back-to-heading t)
  5362. (when parent (org-up-heading-safe))
  5363. (cond ((not (bobp))
  5364. (org-previous-line-empty-p))
  5365. ((outline-next-heading)
  5366. (org-previous-line-empty-p))
  5367. ;; Ignore trailing spaces on last buffer line.
  5368. ((progn (skip-chars-backward " \t") (bolp))
  5369. (org-previous-line-empty-p))
  5370. (t nil))))))
  5371. (`(heading . ,value) value)
  5372. (_ nil)))
  5373. (defun org-insert-heading (&optional arg invisible-ok top)
  5374. "Insert a new heading or an item with the same depth at point.
  5375. If point is at the beginning of a heading, insert a new heading
  5376. or a new headline above the current one. When at the beginning
  5377. of a regular line of text, turn it into a heading.
  5378. If point is in the middle of a line, split it and create a new
  5379. headline with the text in the current line after point (see
  5380. `org-M-RET-may-split-line' on how to modify this behavior). As
  5381. a special case, on a headline, splitting can only happen on the
  5382. title itself. E.g., this excludes breaking stars or tags.
  5383. With a `\\[universal-argument]' prefix, set \
  5384. `org-insert-heading-respect-content' to
  5385. a non-nil value for the duration of the command. This forces the
  5386. insertion of a heading after the current subtree, independently
  5387. on the location of point.
  5388. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  5389. insert the heading at the end of the tree
  5390. above the current heading. For example, if point is within a
  5391. 2nd-level heading, then it will insert a 2nd-level heading at
  5392. the end of the 1st-level parent subtree.
  5393. When INVISIBLE-OK is set, stop at invisible headlines when going
  5394. back. This is important for non-interactive uses of the
  5395. command.
  5396. When optional argument TOP is non-nil, insert a level 1 heading,
  5397. unconditionally."
  5398. (interactive "P")
  5399. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  5400. (level (org-current-level))
  5401. (stars (make-string (if (and level (not top)) level 1) ?*)))
  5402. (cond
  5403. ((or org-insert-heading-respect-content
  5404. (member arg '((4) (16)))
  5405. (and (not invisible-ok)
  5406. (invisible-p (max (1- (point)) (point-min)))))
  5407. ;; Position point at the location of insertion. Make sure we
  5408. ;; end up on a visible headline if INVISIBLE-OK is nil.
  5409. (org-with-limited-levels
  5410. (if (not level) (outline-next-heading) ;before first headline
  5411. (org-back-to-heading invisible-ok)
  5412. (when (equal arg '(16)) (org-up-heading-safe))
  5413. (org-end-of-subtree)))
  5414. (unless (bolp) (insert "\n"))
  5415. (when (and blank? (save-excursion
  5416. (backward-char)
  5417. (org-before-first-heading-p)))
  5418. (insert "\n")
  5419. (backward-char))
  5420. (when (and (not level) (not (eobp)) (not (bobp)))
  5421. (when (org-at-heading-p) (insert "\n"))
  5422. (backward-char))
  5423. (unless (and blank? (org-previous-line-empty-p))
  5424. (org-N-empty-lines-before-current (if blank? 1 0)))
  5425. (insert stars " ")
  5426. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  5427. ;; is visible.
  5428. (unless invisible-ok
  5429. (if (eq org-fold-core-style 'text-properties)
  5430. (cond
  5431. ((org-fold-folded-p (line-beginning-position) 'headline)
  5432. (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
  5433. (t nil))
  5434. (pcase (get-char-property-and-overlay (point) 'invisible)
  5435. (`(outline . ,o)
  5436. (move-overlay o (overlay-start o) (line-end-position 0)))
  5437. (_ nil)))))
  5438. ;; At a headline...
  5439. ((org-at-heading-p)
  5440. (cond ((bolp)
  5441. (when blank? (save-excursion (insert "\n")))
  5442. (save-excursion (insert stars " \n"))
  5443. (unless (and blank? (org-previous-line-empty-p))
  5444. (org-N-empty-lines-before-current (if blank? 1 0)))
  5445. (end-of-line))
  5446. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  5447. (org-match-line org-complex-heading-regexp)
  5448. (org-pos-in-match-range (point) 4))
  5449. ;; Grab the text that should moved to the new headline.
  5450. ;; Preserve tags.
  5451. (let ((split (delete-and-extract-region (point) (match-end 4))))
  5452. (if (looking-at "[ \t]*$") (replace-match "")
  5453. (org-align-tags))
  5454. (end-of-line)
  5455. (when blank? (insert "\n"))
  5456. (insert "\n" stars " ")
  5457. (when (org-string-nw-p split) (insert split))))
  5458. (t
  5459. (end-of-line)
  5460. (when blank? (insert "\n"))
  5461. (insert "\n" stars " "))))
  5462. ;; On regular text, turn line into a headline or split, if
  5463. ;; appropriate.
  5464. ((bolp)
  5465. (insert stars " ")
  5466. (unless (and blank? (org-previous-line-empty-p))
  5467. (org-N-empty-lines-before-current (if blank? 1 0))))
  5468. (t
  5469. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  5470. (end-of-line))
  5471. (insert "\n" stars " ")
  5472. (unless (and blank? (org-previous-line-empty-p))
  5473. (org-N-empty-lines-before-current (if blank? 1 0))))))
  5474. (run-hooks 'org-insert-heading-hook))
  5475. (defun org-N-empty-lines-before-current (n)
  5476. "Make the number of empty lines before current exactly N.
  5477. So this will delete or add empty lines."
  5478. (let ((column (current-column)))
  5479. (beginning-of-line)
  5480. (unless (bobp)
  5481. (let ((start (save-excursion
  5482. (skip-chars-backward " \r\t\n")
  5483. (line-end-position))))
  5484. (delete-region start (line-end-position 0))))
  5485. (insert (make-string n ?\n))
  5486. (move-to-column column)))
  5487. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  5488. "Return the heading of the current entry, without the stars.
  5489. When NO-TAGS is non-nil, don't include tags.
  5490. When NO-TODO is non-nil, don't include TODO keywords.
  5491. When NO-PRIORITY is non-nil, don't include priority cookie.
  5492. When NO-COMMENT is non-nil, don't include COMMENT string.
  5493. Return nil before first heading."
  5494. (unless (org-before-first-heading-p)
  5495. (save-excursion
  5496. (org-back-to-heading t)
  5497. (let ((case-fold-search nil))
  5498. (looking-at org-complex-heading-regexp)
  5499. ;; When using `org-fold-core--optimise-for-huge-buffers',
  5500. ;; returned text will be invisible. Clear it up.
  5501. (save-match-data
  5502. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
  5503. (let ((todo (and (not no-todo) (match-string 2)))
  5504. (priority (and (not no-priority) (match-string 3)))
  5505. (headline (pcase (match-string 4)
  5506. (`nil "")
  5507. ((and (guard no-comment) h)
  5508. (replace-regexp-in-string
  5509. (eval-when-compile
  5510. (format "\\`%s[ \t]+" org-comment-string))
  5511. "" h))
  5512. (h h)))
  5513. (tags (and (not no-tags) (match-string 5))))
  5514. ;; Restore cleared optimisation.
  5515. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
  5516. (mapconcat #'identity
  5517. (delq nil (list todo priority headline tags))
  5518. " "))))))
  5519. (defun org-heading-components ()
  5520. "Return the components of the current heading.
  5521. This is a list with the following elements:
  5522. - the level as an integer
  5523. - the reduced level, different if `org-odd-levels-only' is set.
  5524. - the TODO keyword, or nil
  5525. - the priority character, like ?A, or nil if no priority is given
  5526. - the headline text itself, or the tags string if no headline text
  5527. - the tags string, or nil."
  5528. (save-excursion
  5529. (org-back-to-heading t)
  5530. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  5531. (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
  5532. (prog1
  5533. (list (length (match-string 1))
  5534. (org-reduced-level (length (match-string 1)))
  5535. (match-string-no-properties 2)
  5536. (and (match-end 3) (aref (match-string 3) 2))
  5537. (match-string-no-properties 4)
  5538. (match-string-no-properties 5))
  5539. (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
  5540. (defun org-get-entry ()
  5541. "Get the entry text, after heading, entire subtree."
  5542. (save-excursion
  5543. (org-back-to-heading t)
  5544. (filter-buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  5545. (defun org-edit-headline (&optional heading)
  5546. "Edit the current headline.
  5547. Set it to HEADING when provided."
  5548. (interactive)
  5549. (org-with-wide-buffer
  5550. (org-back-to-heading t)
  5551. (let ((case-fold-search nil))
  5552. (when (looking-at org-complex-heading-regexp)
  5553. (let* ((old (match-string-no-properties 4))
  5554. (new (save-match-data
  5555. (org-trim (or heading (read-string "Edit: " old))))))
  5556. (unless (equal old new)
  5557. (if old (replace-match new t t nil 4)
  5558. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  5559. (insert " " new))
  5560. (org-align-tags)
  5561. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  5562. (defun org-insert-heading-after-current ()
  5563. "Insert a new heading with same level as current, after current subtree."
  5564. (interactive)
  5565. (org-back-to-heading)
  5566. (org-insert-heading)
  5567. (org-move-subtree-down)
  5568. (end-of-line 1))
  5569. (defun org-insert-heading-respect-content (&optional invisible-ok)
  5570. "Insert heading with `org-insert-heading-respect-content' set to t."
  5571. (interactive)
  5572. (org-insert-heading '(4) invisible-ok))
  5573. (defun org-insert-todo-heading-respect-content (&optional force-state)
  5574. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  5575. (interactive)
  5576. (org-insert-todo-heading force-state '(4)))
  5577. (defun org-insert-todo-heading (arg &optional force-heading)
  5578. "Insert a new heading with the same level and TODO state as current heading.
  5579. If the heading has no TODO state, or if the state is DONE, use
  5580. the first state (TODO by default). Also with one prefix arg,
  5581. force first state. With two prefix args, force inserting at the
  5582. end of the parent subtree.
  5583. When called at a plain list item, insert a new item with an
  5584. unchecked check box."
  5585. (interactive "P")
  5586. (when (or force-heading (not (org-insert-item 'checkbox)))
  5587. (org-insert-heading (or (and (equal arg '(16)) '(16))
  5588. force-heading))
  5589. (save-excursion
  5590. (org-forward-heading-same-level -1)
  5591. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  5592. (let* ((new-mark-x
  5593. (if (or (equal arg '(4))
  5594. (not (match-beginning 2))
  5595. (member (match-string 2) org-done-keywords))
  5596. (car org-todo-keywords-1)
  5597. (match-string 2)))
  5598. (new-mark
  5599. (or
  5600. (run-hook-with-args-until-success
  5601. 'org-todo-get-default-hook new-mark-x nil)
  5602. new-mark-x)))
  5603. (beginning-of-line 1)
  5604. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  5605. (if org-treat-insert-todo-heading-as-state-change
  5606. (org-todo new-mark)
  5607. (insert new-mark " "))))
  5608. (when org-provide-todo-statistics
  5609. (org-update-parent-todo-statistics))))
  5610. (defun org-insert-subheading (arg)
  5611. "Insert a new subheading and demote it.
  5612. Works for outline headings and for plain lists alike."
  5613. (interactive "P")
  5614. (org-insert-heading arg)
  5615. (cond
  5616. ((org-at-heading-p) (org-do-demote))
  5617. ((org-at-item-p) (org-indent-item))))
  5618. (defun org-insert-todo-subheading (arg)
  5619. "Insert a new subheading with TODO keyword or checkbox and demote it.
  5620. Works for outline headings and for plain lists alike."
  5621. (interactive "P")
  5622. (org-insert-todo-heading arg)
  5623. (cond
  5624. ((org-at-heading-p) (org-do-demote))
  5625. ((org-at-item-p) (org-indent-item))))
  5626. ;;; Promotion and Demotion
  5627. (defvar org-after-demote-entry-hook nil
  5628. "Hook run after an entry has been demoted.
  5629. The cursor will be at the beginning of the entry.
  5630. When a subtree is being demoted, the hook will be called for each node.")
  5631. (defvar org-after-promote-entry-hook nil
  5632. "Hook run after an entry has been promoted.
  5633. The cursor will be at the beginning of the entry.
  5634. When a subtree is being promoted, the hook will be called for each node.")
  5635. (defun org-promote-subtree ()
  5636. "Promote the entire subtree.
  5637. See also `org-promote'."
  5638. (interactive)
  5639. (save-excursion
  5640. (org-back-to-heading t)
  5641. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5642. (org-with-limited-levels (org-map-tree 'org-promote))))
  5643. (org-fix-position-after-promote))
  5644. (defun org-demote-subtree ()
  5645. "Demote the entire subtree.
  5646. See `org-demote' and `org-promote'."
  5647. (interactive)
  5648. (save-excursion
  5649. (org-back-to-heading t)
  5650. (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
  5651. (org-with-limited-levels (org-map-tree 'org-demote))))
  5652. (org-fix-position-after-promote))
  5653. (defun org-do-promote ()
  5654. "Promote the current heading higher up the tree.
  5655. If the region is active in `transient-mark-mode', promote all
  5656. headings in the region."
  5657. (interactive)
  5658. (save-excursion
  5659. (if (org-region-active-p)
  5660. (org-map-region 'org-promote (region-beginning) (region-end))
  5661. (org-promote)))
  5662. (org-fix-position-after-promote))
  5663. (defun org-do-demote ()
  5664. "Demote the current heading lower down the tree.
  5665. If the region is active in `transient-mark-mode', demote all
  5666. headings in the region."
  5667. (interactive)
  5668. (save-excursion
  5669. (if (org-region-active-p)
  5670. (org-map-region 'org-demote (region-beginning) (region-end))
  5671. (org-demote)))
  5672. (org-fix-position-after-promote))
  5673. (defun org-fix-position-after-promote ()
  5674. "Fix cursor position and indentation after demoting/promoting."
  5675. (let ((pos (point)))
  5676. (when (save-excursion
  5677. (beginning-of-line)
  5678. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  5679. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  5680. (cond ((eobp) (insert " "))
  5681. ((eolp) (insert " "))
  5682. ((equal (char-after) ?\s) (forward-char 1))))))
  5683. (defun org-current-level ()
  5684. "Return the level of the current entry, or nil if before the first headline.
  5685. The level is the number of stars at the beginning of the
  5686. headline. Use `org-reduced-level' to remove the effect of
  5687. `org-odd-levels'. Unlike to `org-outline-level', this function
  5688. ignores inlinetasks."
  5689. (let ((level (org-with-limited-levels (org-outline-level))))
  5690. (and (> level 0) level)))
  5691. (defun org-get-previous-line-level ()
  5692. "Return the outline depth of the last headline before the current line.
  5693. Returns 0 for the first headline in the buffer, and nil if before the
  5694. first headline."
  5695. (and (org-current-level)
  5696. (or (and (/= (line-beginning-position) (point-min))
  5697. (save-excursion (beginning-of-line 0) (org-current-level)))
  5698. 0)))
  5699. (defun org-reduced-level (l)
  5700. "Compute the effective level of a heading.
  5701. This takes into account the setting of `org-odd-levels-only'."
  5702. (cond
  5703. ((zerop l) 0)
  5704. (org-odd-levels-only (1+ (floor (/ l 2))))
  5705. (t l)))
  5706. (defun org-level-increment ()
  5707. "Return the number of stars that will be added or removed at a
  5708. time to headlines when structure editing, based on the value of
  5709. `org-odd-levels-only'."
  5710. (if org-odd-levels-only 2 1))
  5711. (defun org-get-valid-level (level &optional change)
  5712. "Rectify a level change under the influence of `org-odd-levels-only'.
  5713. LEVEL is a current level, CHANGE is by how much the level should
  5714. be modified. Even if CHANGE is nil, LEVEL may be returned
  5715. modified because even level numbers will become the next higher
  5716. odd number. Returns values greater than 0."
  5717. (if org-odd-levels-only
  5718. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  5719. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  5720. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  5721. (max 1 (+ level (or change 0)))))
  5722. (defun org-promote ()
  5723. "Promote the current heading higher up the tree."
  5724. (org-with-wide-buffer
  5725. (org-back-to-heading t)
  5726. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5727. after-change-functions))
  5728. (level (save-match-data (funcall outline-level)))
  5729. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  5730. (diff (abs (- level (length up-head) -1))))
  5731. (cond
  5732. ((and (= level 1) org-allow-promoting-top-level-subtree)
  5733. (replace-match "# " nil t))
  5734. ((= level 1)
  5735. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  5736. (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
  5737. (unless (= level 1)
  5738. (when org-auto-align-tags (org-align-tags))
  5739. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  5740. (run-hooks 'org-after-promote-entry-hook))))
  5741. (defun org-demote ()
  5742. "Demote the current heading lower down the tree."
  5743. (org-with-wide-buffer
  5744. (org-back-to-heading t)
  5745. (let* ((after-change-functions (remq 'flyspell-after-change-function
  5746. after-change-functions))
  5747. (level (save-match-data (funcall outline-level)))
  5748. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  5749. (diff (abs (- level (length down-head) -1))))
  5750. (org-fold-core-ignore-fragility-checks
  5751. (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
  5752. (when org-auto-align-tags (org-align-tags))
  5753. (when org-adapt-indentation (org-fixup-indentation diff)))
  5754. (run-hooks 'org-after-demote-entry-hook))))
  5755. (defun org-cycle-level ()
  5756. "Cycle the level of an empty headline through possible states.
  5757. This goes first to child, then to parent, level, then up the hierarchy.
  5758. After top level, it switches back to sibling level."
  5759. (interactive)
  5760. (let ((org-adapt-indentation nil))
  5761. (when (org-point-at-end-of-empty-headline)
  5762. (setq this-command 'org-cycle-level) ; Only needed for caching
  5763. (let ((cur-level (org-current-level))
  5764. (prev-level (org-get-previous-line-level)))
  5765. (cond
  5766. ;; If first headline in file, promote to top-level.
  5767. ((= prev-level 0)
  5768. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5769. do (org-do-promote)))
  5770. ;; If same level as prev, demote one.
  5771. ((= prev-level cur-level)
  5772. (org-do-demote))
  5773. ;; If parent is top-level, promote to top level if not already.
  5774. ((= prev-level 1)
  5775. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  5776. do (org-do-promote)))
  5777. ;; If top-level, return to prev-level.
  5778. ((= cur-level 1)
  5779. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  5780. do (org-do-demote)))
  5781. ;; If less than prev-level, promote one.
  5782. ((< cur-level prev-level)
  5783. (org-do-promote))
  5784. ;; If deeper than prev-level, promote until higher than
  5785. ;; prev-level.
  5786. ((> cur-level prev-level)
  5787. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  5788. do (org-do-promote))))
  5789. t))))
  5790. (defun org-map-tree (fun)
  5791. "Call FUN for every heading underneath the current one."
  5792. (org-back-to-heading t)
  5793. (let ((level (funcall outline-level)))
  5794. (save-excursion
  5795. (funcall fun)
  5796. (while (and (progn
  5797. (outline-next-heading)
  5798. (> (funcall outline-level) level))
  5799. (not (eobp)))
  5800. (funcall fun)))))
  5801. (defun org-map-region (fun beg end)
  5802. "Call FUN for every heading between BEG and END."
  5803. (let ((org-ignore-region t))
  5804. (save-excursion
  5805. (setq end (copy-marker end))
  5806. (goto-char beg)
  5807. (when (and (re-search-forward org-outline-regexp-bol nil t)
  5808. (< (point) end))
  5809. (funcall fun))
  5810. (while (and (progn
  5811. (outline-next-heading)
  5812. (< (point) end))
  5813. (not (eobp)))
  5814. (funcall fun)))))
  5815. (defun org-fixup-indentation (diff)
  5816. "Change the indentation in the current entry by DIFF.
  5817. DIFF is an integer. Indentation is done according to the
  5818. following rules:
  5819. - Planning information and property drawers are always indented
  5820. according to the new level of the headline;
  5821. - Footnote definitions and their contents are ignored;
  5822. - Inlinetasks' boundaries are not shifted;
  5823. - Empty lines are ignored;
  5824. - Other lines' indentation are shifted by DIFF columns, unless
  5825. it would introduce a structural change in the document, in
  5826. which case no shifting is done at all.
  5827. Assume point is at a heading or an inlinetask beginning."
  5828. (org-with-wide-buffer
  5829. (narrow-to-region (line-beginning-position)
  5830. (save-excursion
  5831. (if (org-with-limited-levels (org-at-heading-p))
  5832. (org-with-limited-levels (outline-next-heading))
  5833. (org-inlinetask-goto-end))
  5834. (point)))
  5835. (forward-line)
  5836. ;; Indent properly planning info and property drawer.
  5837. (when (looking-at-p org-planning-line-re)
  5838. (org-indent-line)
  5839. (forward-line))
  5840. (when (looking-at org-property-drawer-re)
  5841. (goto-char (match-end 0))
  5842. (forward-line)
  5843. (org-indent-region (match-beginning 0) (match-end 0)))
  5844. (when (looking-at org-logbook-drawer-re)
  5845. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  5846. (col (+ (current-indentation) diff)))
  5847. (when (wholenump col)
  5848. (while (< (point) end-marker)
  5849. (if (natnump diff)
  5850. (insert (make-string diff 32))
  5851. (delete-char (abs diff)))
  5852. (forward-line)))))
  5853. (catch 'no-shift
  5854. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  5855. (throw 'no-shift nil))
  5856. ;; If DIFF is negative, first check if a shift is possible at all
  5857. ;; (e.g., it doesn't break structure). This can only happen if
  5858. ;; some contents are not properly indented.
  5859. (let ((case-fold-search t))
  5860. (when (< diff 0)
  5861. (let ((diff (- diff))
  5862. (forbidden-re (concat org-outline-regexp
  5863. "\\|"
  5864. (substring org-footnote-definition-re 1))))
  5865. (save-excursion
  5866. (while (not (eobp))
  5867. (cond
  5868. ((looking-at-p "[ \t]*$") (forward-line))
  5869. ((and (looking-at-p org-footnote-definition-re)
  5870. (let ((e (org-element-at-point)))
  5871. (and (eq (org-element-type e) 'footnote-definition)
  5872. (goto-char (org-element-property :end e))))))
  5873. ((looking-at-p org-outline-regexp) (forward-line))
  5874. ;; Give up if shifting would move before column 0 or
  5875. ;; if it would introduce a headline or a footnote
  5876. ;; definition.
  5877. (t
  5878. (skip-chars-forward " \t")
  5879. (let ((ind (current-column)))
  5880. (when (or (< ind diff)
  5881. (and (= ind diff) (looking-at-p forbidden-re)))
  5882. (throw 'no-shift nil)))
  5883. ;; Ignore contents of example blocks and source
  5884. ;; blocks if their indentation is meant to be
  5885. ;; preserved. Jump to block's closing line.
  5886. (beginning-of-line)
  5887. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5888. (let ((e (org-element-at-point)))
  5889. (and (memq (org-element-type e)
  5890. '(example-block src-block))
  5891. (or org-src-preserve-indentation
  5892. (org-element-property :preserve-indent e))
  5893. (goto-char (org-element-property :end e))
  5894. (progn (skip-chars-backward " \r\t\n")
  5895. (beginning-of-line)
  5896. t))))
  5897. (forward-line))))))))
  5898. ;; Shift lines but footnote definitions, inlinetasks boundaries
  5899. ;; by DIFF. Also skip contents of source or example blocks
  5900. ;; when indentation is meant to be preserved.
  5901. (while (not (eobp))
  5902. (cond
  5903. ((and (looking-at-p org-footnote-definition-re)
  5904. (let ((e (org-element-at-point)))
  5905. (and (eq (org-element-type e) 'footnote-definition)
  5906. (goto-char (org-element-property :end e))))))
  5907. ((looking-at-p org-outline-regexp) (forward-line))
  5908. ((looking-at-p "[ \t]*$") (forward-line))
  5909. (t
  5910. (indent-line-to (+ (current-indentation) diff))
  5911. (beginning-of-line)
  5912. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  5913. (let ((e (org-element-at-point)))
  5914. (and (memq (org-element-type e)
  5915. '(example-block src-block))
  5916. (or org-src-preserve-indentation
  5917. (org-element-property :preserve-indent e))
  5918. (goto-char (org-element-property :end e))
  5919. (progn (skip-chars-backward " \r\t\n")
  5920. (beginning-of-line)
  5921. t))))
  5922. (forward-line)))))))))
  5923. (defun org-convert-to-odd-levels ()
  5924. "Convert an Org file with all levels allowed to one with odd levels.
  5925. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  5926. level 5 etc."
  5927. (interactive)
  5928. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  5929. (let ((outline-level 'org-outline-level)
  5930. (org-odd-levels-only nil) n)
  5931. (save-excursion
  5932. (goto-char (point-min))
  5933. (while (re-search-forward "^\\*\\*+ " nil t)
  5934. (setq n (- (length (match-string 0)) 2))
  5935. (while (>= (setq n (1- n)) 0)
  5936. (org-demote))
  5937. (end-of-line 1))))))
  5938. (defun org-convert-to-oddeven-levels ()
  5939. "Convert an Org file with only odd levels to one with odd/even levels.
  5940. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  5941. file contains a section with an even level, conversion would
  5942. destroy the structure of the file. An error is signaled in this
  5943. case."
  5944. (interactive)
  5945. (goto-char (point-min))
  5946. ;; First check if there are no even levels
  5947. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  5948. (org-fold-show-set-visibility 'canonical)
  5949. (error "Not all levels are odd in this file. Conversion not possible"))
  5950. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  5951. (let ((outline-regexp org-outline-regexp)
  5952. (outline-level 'org-outline-level)
  5953. (org-odd-levels-only nil) n)
  5954. (save-excursion
  5955. (goto-char (point-min))
  5956. (while (re-search-forward "^\\*\\*+ " nil t)
  5957. (setq n (/ (1- (length (match-string 0))) 2))
  5958. (while (>= (setq n (1- n)) 0)
  5959. (org-promote))
  5960. (end-of-line 1))))))
  5961. (defun org-tr-level (n)
  5962. "Make N odd if required."
  5963. (if org-odd-levels-only (1+ (/ n 2)) n))
  5964. ;;; Vertical tree motion, cutting and pasting of subtrees
  5965. (defun org-move-subtree-up (&optional arg)
  5966. "Move the current subtree up past ARG headlines of the same level."
  5967. (interactive "p")
  5968. (org-move-subtree-down (- (prefix-numeric-value arg))))
  5969. (defun org-clean-visibility-after-subtree-move ()
  5970. "Fix visibility issues after moving a subtree."
  5971. ;; First, find a reasonable region to look at:
  5972. ;; Start two siblings above, end three below
  5973. (let* ((beg (save-excursion
  5974. (and (org-get-previous-sibling)
  5975. (org-get-previous-sibling))
  5976. (point)))
  5977. (end (save-excursion
  5978. (and (org-get-next-sibling)
  5979. (org-get-next-sibling)
  5980. (org-get-next-sibling))
  5981. (if (org-at-heading-p)
  5982. (point-at-eol)
  5983. (point))))
  5984. (level (looking-at "\\*+"))
  5985. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5986. (save-excursion
  5987. (save-restriction
  5988. (narrow-to-region beg end)
  5989. (when re
  5990. ;; Properly fold already folded siblings
  5991. (goto-char (point-min))
  5992. (while (re-search-forward re nil t)
  5993. (when (and (not (org-invisible-p))
  5994. (org-invisible-p (line-end-position)))
  5995. (org-fold-heading nil))))
  5996. (org-cycle-hide-drawers 'all)
  5997. (org-cycle-show-empty-lines 'overview)))))
  5998. (defun org-move-subtree-down (&optional arg)
  5999. "Move the current subtree down past ARG headlines of the same level."
  6000. (interactive "p")
  6001. (setq arg (prefix-numeric-value arg))
  6002. (org-preserve-local-variables
  6003. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6004. 'org-get-previous-sibling))
  6005. (ins-point (make-marker))
  6006. (cnt (abs arg))
  6007. (col (current-column))
  6008. beg end txt folded)
  6009. ;; Select the tree
  6010. (org-back-to-heading)
  6011. (setq beg (point))
  6012. (save-match-data
  6013. (save-excursion (outline-end-of-heading)
  6014. (setq folded (org-invisible-p)))
  6015. (progn (org-end-of-subtree nil t)
  6016. (unless (eobp) (backward-char))))
  6017. (outline-next-heading)
  6018. (setq end (point))
  6019. (goto-char beg)
  6020. ;; Find insertion point, with error handling
  6021. (while (> cnt 0)
  6022. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6023. (goto-char beg)
  6024. (user-error "Cannot move past superior level or buffer limit"))
  6025. (setq cnt (1- cnt)))
  6026. (when (> arg 0)
  6027. ;; Moving forward - still need to move over subtree
  6028. (org-end-of-subtree t t)
  6029. (save-excursion
  6030. (org-back-over-empty-lines)
  6031. (or (bolp) (newline))))
  6032. (move-marker ins-point (point))
  6033. (setq txt (buffer-substring beg end))
  6034. (org-save-markers-in-region beg end)
  6035. (delete-region beg end)
  6036. (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
  6037. (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
  6038. (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
  6039. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6040. (let ((bbb (point)))
  6041. (insert-before-markers txt)
  6042. (org-reinstall-markers-in-region bbb)
  6043. (move-marker ins-point bbb))
  6044. (or (bolp) (insert "\n"))
  6045. (goto-char ins-point)
  6046. (org-skip-whitespace)
  6047. (move-marker ins-point nil)
  6048. (if folded
  6049. (org-fold-subtree t)
  6050. (org-fold-show-entry)
  6051. (org-fold-show-children))
  6052. (org-clean-visibility-after-subtree-move)
  6053. ;; move back to the initial column we were at
  6054. (move-to-column col))))
  6055. (defvar org-subtree-clip ""
  6056. "Clipboard for cut and paste of subtrees.
  6057. This is actually only a copy of the kill, because we use the normal kill
  6058. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6059. (defvar org-subtree-clip-folded nil
  6060. "Was the last copied subtree folded?
  6061. This is used to fold the tree back after pasting.")
  6062. (defun org-cut-subtree (&optional n)
  6063. "Cut the current subtree into the clipboard.
  6064. With prefix arg N, cut this many sequential subtrees.
  6065. This is a short-hand for marking the subtree and then cutting it."
  6066. (interactive "p")
  6067. (org-copy-subtree n 'cut))
  6068. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6069. "Copy the current subtree into the clipboard.
  6070. With prefix arg N, copy this many sequential subtrees.
  6071. This is a short-hand for marking the subtree and then copying it.
  6072. If CUT is non-nil, actually cut the subtree.
  6073. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6074. of some markers in the region, even if CUT is non-nil. This is
  6075. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6076. (interactive "p")
  6077. (org-preserve-local-variables
  6078. (let (beg end folded (beg0 (point)))
  6079. (if (called-interactively-p 'any)
  6080. (org-back-to-heading nil) ; take what looks like a subtree
  6081. (org-back-to-heading t)) ; take what is really there
  6082. (setq beg (point))
  6083. (skip-chars-forward " \t\r\n")
  6084. (save-match-data
  6085. (if nosubtrees
  6086. (outline-next-heading)
  6087. (save-excursion (outline-end-of-heading)
  6088. (setq folded (org-invisible-p)))
  6089. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6090. (org-end-of-subtree t t)))
  6091. ;; Include the end of an inlinetask
  6092. (when (and (featurep 'org-inlinetask)
  6093. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6094. "END[ \t]*$")))
  6095. (end-of-line))
  6096. (setq end (point))
  6097. (goto-char beg0)
  6098. (when (> end beg)
  6099. (setq org-subtree-clip-folded folded)
  6100. (when (or cut force-store-markers)
  6101. (org-save-markers-in-region beg end))
  6102. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6103. (setq org-subtree-clip (current-kill 0))
  6104. (message "%s: Subtree(s) with %d characters"
  6105. (if cut "Cut" "Copied")
  6106. (length org-subtree-clip))))))
  6107. (defun org-paste-subtree (&optional level tree for-yank remove)
  6108. "Paste the clipboard as a subtree, with modification of headline level.
  6109. The entire subtree is promoted or demoted in order to match a new headline
  6110. level.
  6111. If the cursor is at the beginning of a headline, the same level as
  6112. that headline is used to paste the tree.
  6113. If not, the new level is derived from the *visible* headings
  6114. before and after the insertion point, and taken to be the inferior headline
  6115. level of the two. So if the previous visible heading is level 3 and the
  6116. next is level 4 (or vice versa), level 4 will be used for insertion.
  6117. This makes sure that the subtree remains an independent subtree and does
  6118. not swallow low level entries.
  6119. You can also force a different level, either by using a numeric prefix
  6120. argument, or by inserting the heading marker by hand. For example, if the
  6121. cursor is after \"*****\", then the tree will be shifted to level 5.
  6122. If optional TREE is given, use this text instead of the kill ring.
  6123. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6124. move back over whitespace before inserting, and move point to the end of
  6125. the inserted text when done.
  6126. When REMOVE is non-nil, remove the subtree from the clipboard."
  6127. (interactive "P")
  6128. (setq tree (or tree (and kill-ring (current-kill 0))))
  6129. (unless (org-kill-is-subtree-p tree)
  6130. (user-error
  6131. (substitute-command-keys
  6132. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6133. (org-with-limited-levels
  6134. (org-fold-core-ignore-fragility-checks
  6135. (let* ((visp (not (org-invisible-p)))
  6136. (txt tree)
  6137. (old-level (if (string-match org-outline-regexp-bol txt)
  6138. (- (match-end 0) (match-beginning 0) 1)
  6139. -1))
  6140. (force-level
  6141. (cond
  6142. (level (prefix-numeric-value level))
  6143. ;; When point is after the stars in an otherwise empty
  6144. ;; headline, use the number of stars as the forced level.
  6145. ((and (org-match-line "^\\*+[ \t]*$")
  6146. (not (eq ?* (char-after))))
  6147. (org-outline-level))
  6148. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6149. (previous-level
  6150. (save-excursion
  6151. (org-previous-visible-heading 1)
  6152. (if (org-at-heading-p) (org-outline-level) 1)))
  6153. (next-level
  6154. (save-excursion
  6155. (if (org-at-heading-p) (org-outline-level)
  6156. (org-next-visible-heading 1)
  6157. (if (org-at-heading-p) (org-outline-level) 1))))
  6158. (new-level (or force-level (max previous-level next-level)))
  6159. (shift (if (or (= old-level -1)
  6160. (= new-level -1)
  6161. (= old-level new-level))
  6162. 0
  6163. (- new-level old-level)))
  6164. (delta (if (> shift 0) -1 1))
  6165. (func (if (> shift 0) #'org-demote #'org-promote))
  6166. (org-odd-levels-only nil)
  6167. beg end newend)
  6168. ;; Remove the forced level indicator.
  6169. (when (and force-level (not level))
  6170. (delete-region (line-beginning-position) (point)))
  6171. ;; Paste before the next visible heading or at end of buffer,
  6172. ;; unless point is at the beginning of a headline.
  6173. (unless (and (bolp) (org-at-heading-p))
  6174. (org-next-visible-heading 1)
  6175. (unless (bolp) (insert "\n")))
  6176. (setq beg (point))
  6177. ;; Avoid re-parsing cache elements when i.e. level 1 heading
  6178. ;; is inserted and then promoted.
  6179. (combine-change-calls beg beg
  6180. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6181. (insert-before-markers txt)
  6182. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6183. (setq newend (point))
  6184. (org-reinstall-markers-in-region beg)
  6185. (setq end (point))
  6186. (goto-char beg)
  6187. (skip-chars-forward " \t\n\r")
  6188. (setq beg (point))
  6189. (when (and (org-invisible-p) visp)
  6190. (save-excursion (org-fold-heading nil)))
  6191. ;; Shift if necessary.
  6192. (unless (= shift 0)
  6193. (save-restriction
  6194. (narrow-to-region beg end)
  6195. (while (not (= shift 0))
  6196. (org-map-region func (point-min) (point-max))
  6197. (setq shift (+ delta shift)))
  6198. (goto-char (point-min))
  6199. (setq newend (point-max)))))
  6200. (when (or for-yank (called-interactively-p 'interactive))
  6201. (message "Clipboard pasted as level %d subtree" new-level))
  6202. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6203. kill-ring
  6204. (equal org-subtree-clip (current-kill 0))
  6205. org-subtree-clip-folded)
  6206. ;; The tree was folded before it was killed/copied
  6207. (org-fold-subtree t))
  6208. (when for-yank (goto-char newend))
  6209. (when remove (pop kill-ring))))))
  6210. (defun org-kill-is-subtree-p (&optional txt)
  6211. "Check if the current kill is an outline subtree, or a set of trees.
  6212. Returns nil if kill does not start with a headline, or if the first
  6213. headline level is not the largest headline level in the tree.
  6214. So this will actually accept several entries of equal levels as well,
  6215. which is OK for `org-paste-subtree'.
  6216. If optional TXT is given, check this string instead of the current kill."
  6217. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6218. (re (org-get-limited-outline-regexp))
  6219. (^re (concat "^" re))
  6220. (start-level (and kill
  6221. (string-match
  6222. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6223. kill)
  6224. (- (match-end 2) (match-beginning 2) 1)))
  6225. (start (1+ (or (match-beginning 2) -1))))
  6226. (if (not start-level)
  6227. (progn
  6228. nil) ;; does not even start with a heading
  6229. (catch 'exit
  6230. (while (setq start (string-match ^re kill (1+ start)))
  6231. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  6232. (throw 'exit nil)))
  6233. t))))
  6234. (defvar org-markers-to-move nil
  6235. "Markers that should be moved with a cut-and-paste operation.
  6236. Those markers are stored together with their positions relative to
  6237. the start of the region.")
  6238. (defun org-save-markers-in-region (beg end)
  6239. "Check markers in region.
  6240. If these markers are between BEG and END, record their position relative
  6241. to BEG, so that after moving the block of text, we can put the markers back
  6242. into place.
  6243. This function gets called just before an entry or tree gets cut from the
  6244. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  6245. called immediately, to move the markers with the entries."
  6246. (setq org-markers-to-move nil)
  6247. (when (featurep 'org-clock)
  6248. (org-clock-save-markers-for-cut-and-paste beg end))
  6249. (when (featurep 'org-agenda)
  6250. (org-agenda-save-markers-for-cut-and-paste beg end)))
  6251. (defun org-check-and-save-marker (marker beg end)
  6252. "Check if MARKER is between BEG and END.
  6253. If yes, remember the marker and the distance to BEG."
  6254. (when (and (marker-buffer marker)
  6255. (or (equal (marker-buffer marker) (current-buffer))
  6256. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  6257. (>= marker beg) (< marker end))
  6258. (push (cons marker (- marker beg)) org-markers-to-move)))
  6259. (defun org-reinstall-markers-in-region (beg)
  6260. "Move all remembered markers to their position relative to BEG."
  6261. (dolist (x org-markers-to-move)
  6262. (move-marker (car x) (+ beg (cdr x))))
  6263. (setq org-markers-to-move nil))
  6264. (defun org-narrow-to-subtree (&optional element)
  6265. "Narrow buffer to the current subtree."
  6266. (interactive)
  6267. (if (org-element--cache-active-p)
  6268. (let* ((heading (org-element-lineage
  6269. (or element (org-element-at-point))
  6270. '(headline) t))
  6271. (end (org-element-property :end heading)))
  6272. (if (and heading end)
  6273. (narrow-to-region (org-element-property :begin heading)
  6274. (if (= end (point-max))
  6275. end (1- end)))
  6276. (signal 'outline-before-first-heading nil)))
  6277. (save-excursion
  6278. (save-match-data
  6279. (org-with-limited-levels
  6280. (narrow-to-region
  6281. (progn (org-back-to-heading t) (point))
  6282. (progn (org-end-of-subtree t t)
  6283. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  6284. (point))))))))
  6285. (defun org-toggle-narrow-to-subtree ()
  6286. "Narrow to the subtree at point or widen a narrowed buffer."
  6287. (interactive)
  6288. (if (buffer-narrowed-p)
  6289. (progn (widen) (message "Buffer widen"))
  6290. (org-narrow-to-subtree)
  6291. (message "Buffer narrowed to current subtree")))
  6292. (defun org-narrow-to-block ()
  6293. "Narrow buffer to the current block."
  6294. (interactive)
  6295. (let* ((case-fold-search t)
  6296. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  6297. "^[ \t]*#\\+end_.*")))
  6298. (if blockp
  6299. (narrow-to-region (car blockp) (cdr blockp))
  6300. (user-error "Not in a block"))))
  6301. (defun org-clone-subtree-with-time-shift (n &optional shift)
  6302. "Clone the task (subtree) at point N times.
  6303. The clones will be inserted as siblings.
  6304. In interactive use, the user will be prompted for the number of
  6305. clones to be produced. If the entry has a timestamp, the user
  6306. will also be prompted for a time shift, which may be a repeater
  6307. as used in time stamps, for example `+3d'. To disable this,
  6308. you can call the function with a universal prefix argument.
  6309. When a valid repeater is given and the entry contains any time
  6310. stamps, the clones will become a sequence in time, with time
  6311. stamps in the subtree shifted for each clone produced. If SHIFT
  6312. is nil or the empty string, time stamps will be left alone. The
  6313. ID property of the original subtree is removed.
  6314. In each clone, all the CLOCK entries will be removed. This
  6315. prevents Org from considering that the clocked times overlap.
  6316. If the original subtree did contain time stamps with a repeater,
  6317. the following will happen:
  6318. - the repeater will be removed in each clone
  6319. - an additional clone will be produced, with the current, unshifted
  6320. date(s) in the entry.
  6321. - the original entry will be placed *after* all the clones, with
  6322. repeater intact.
  6323. - the start days in the repeater in the original entry will be shifted
  6324. to past the last clone.
  6325. In this way you can spell out a number of instances of a repeating task,
  6326. and still retain the repeater to cover future instances of the task.
  6327. As described above, N+1 clones are produced when the original
  6328. subtree has a repeater. Setting N to 0, then, can be used to
  6329. remove the repeater from a subtree and create a shifted clone
  6330. with the original repeater."
  6331. (interactive "nNumber of clones to produce: ")
  6332. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  6333. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  6334. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  6335. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  6336. (shift
  6337. (or shift
  6338. (if (and (not (equal current-prefix-arg '(4)))
  6339. (save-excursion
  6340. (goto-char beg)
  6341. (re-search-forward org-ts-regexp-both end-of-tree t)))
  6342. (read-from-minibuffer
  6343. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  6344. ""))) ;No time shift
  6345. (doshift
  6346. (and (org-string-nw-p shift)
  6347. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  6348. shift)
  6349. (user-error "Invalid shift specification %s" shift)))))
  6350. (goto-char end-of-tree)
  6351. (unless (bolp) (insert "\n"))
  6352. (let* ((end (point))
  6353. (template (buffer-substring beg end))
  6354. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  6355. (shift-what (pcase (and doshift (match-string 2 shift))
  6356. (`nil nil)
  6357. ("h" 'hour)
  6358. ("d" 'day)
  6359. ("w" (setq shift-n (* 7 shift-n)) 'day)
  6360. ("m" 'month)
  6361. ("y" 'year)
  6362. (_ (error "Unsupported time unit"))))
  6363. (nmin 1)
  6364. (nmax n)
  6365. (n-no-remove -1)
  6366. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  6367. (idprop (org-entry-get beg "ID")))
  6368. (when (and doshift
  6369. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  6370. template))
  6371. (delete-region beg end)
  6372. (setq end beg)
  6373. (setq nmin 0)
  6374. (setq nmax (1+ nmax))
  6375. (setq n-no-remove nmax))
  6376. (goto-char end)
  6377. (cl-loop for n from nmin to nmax do
  6378. (insert
  6379. ;; Prepare clone.
  6380. (with-temp-buffer
  6381. (insert template)
  6382. (org-mode)
  6383. (goto-char (point-min))
  6384. (org-fold-show-subtree)
  6385. (and idprop (if org-clone-delete-id
  6386. (org-entry-delete nil "ID")
  6387. (org-id-get-create t)))
  6388. (unless (= n 0)
  6389. (while (re-search-forward org-clock-line-re nil t)
  6390. (delete-region (line-beginning-position)
  6391. (line-beginning-position 2)))
  6392. (goto-char (point-min))
  6393. (while (re-search-forward org-drawer-regexp nil t)
  6394. (org-remove-empty-drawer-at (point))))
  6395. (goto-char (point-min))
  6396. (when doshift
  6397. (while (re-search-forward org-ts-regexp-both nil t)
  6398. (org-timestamp-change (* n shift-n) shift-what))
  6399. (unless (= n n-no-remove)
  6400. (goto-char (point-min))
  6401. (while (re-search-forward org-ts-regexp nil t)
  6402. (save-excursion
  6403. (goto-char (match-beginning 0))
  6404. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  6405. (delete-region (match-beginning 1) (match-end 1)))))))
  6406. (buffer-string)))))
  6407. (goto-char beg)))
  6408. ;;; Outline path
  6409. (defvar org-outline-path-cache nil
  6410. "Alist between buffer positions and outline paths.
  6411. It value is an alist (POSITION . PATH) where POSITION is the
  6412. buffer position at the beginning of an entry and PATH is a list
  6413. of strings describing the outline path for that entry, in reverse
  6414. order.")
  6415. (defun org--get-outline-path-1 (&optional use-cache)
  6416. "Return outline path to current headline.
  6417. Outline path is a list of strings, in reverse order. When
  6418. optional argument USE-CACHE is non-nil, make use of a cache. See
  6419. `org-get-outline-path' for details.
  6420. Assume buffer is widened and point is on a headline."
  6421. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  6422. (let ((p (point))
  6423. (heading (let ((case-fold-search nil))
  6424. (looking-at org-complex-heading-regexp)
  6425. (if (not (match-end 4)) ""
  6426. ;; Remove statistics cookies.
  6427. (org-trim
  6428. (org-link-display-format
  6429. (replace-regexp-in-string
  6430. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  6431. (match-string-no-properties 4))))))))
  6432. (if (org-up-heading-safe)
  6433. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  6434. (when use-cache
  6435. (push (cons p path) org-outline-path-cache))
  6436. path)
  6437. ;; This is a new root node. Since we assume we are moving
  6438. ;; forward, we can drop previous cache so as to limit number
  6439. ;; of associations there.
  6440. (let ((path (list heading)))
  6441. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  6442. path)))))
  6443. (defun org-get-outline-path (&optional with-self use-cache)
  6444. "Return the outline path to the current entry.
  6445. An outline path is a list of ancestors for current headline, as
  6446. a list of strings. Statistics cookies are removed and links are
  6447. replaced with their description, if any, or their path otherwise.
  6448. When optional argument WITH-SELF is non-nil, the path also
  6449. includes the current headline.
  6450. When optional argument USE-CACHE is non-nil, cache outline paths
  6451. between calls to this function so as to avoid backtracking. This
  6452. argument is useful when planning to find more than one outline
  6453. path in the same document. In that case, there are two
  6454. conditions to satisfy:
  6455. - `org-outline-path-cache' is set to nil before starting the
  6456. process;
  6457. - outline paths are computed by increasing buffer positions."
  6458. (org-with-wide-buffer
  6459. (and (or (and with-self (org-back-to-heading t))
  6460. (org-up-heading-safe))
  6461. (reverse (org--get-outline-path-1 use-cache)))))
  6462. (defun org-format-outline-path (path &optional width prefix separator)
  6463. "Format the outline path PATH for display.
  6464. WIDTH is the maximum number of characters that is available.
  6465. PREFIX is a prefix to be included in the returned string,
  6466. such as the file name.
  6467. SEPARATOR is inserted between the different parts of the path,
  6468. the default is \"/\"."
  6469. (setq width (or width 79))
  6470. (setq path (delq nil path))
  6471. (unless (> width 0)
  6472. (user-error "Argument `width' must be positive"))
  6473. (setq separator (or separator "/"))
  6474. (let* ((org-odd-levels-only nil)
  6475. (fpath (concat
  6476. prefix (and prefix path separator)
  6477. (mapconcat
  6478. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  6479. (cl-loop for head in path
  6480. for n from 0
  6481. collect (org-add-props
  6482. head nil 'face
  6483. (nth (% n org-n-level-faces) org-level-faces)))
  6484. separator))))
  6485. (when (> (length fpath) width)
  6486. (if (< width 7)
  6487. ;; It's unlikely that `width' will be this small, but don't
  6488. ;; waste characters by adding ".." if it is.
  6489. (setq fpath (substring fpath 0 width))
  6490. (setf (substring fpath (- width 2)) "..")))
  6491. fpath))
  6492. (defun org-display-outline-path (&optional file current separator just-return-string)
  6493. "Display the current outline path in the echo area.
  6494. If FILE is non-nil, prepend the output with the file name.
  6495. If CURRENT is non-nil, append the current heading to the output.
  6496. SEPARATOR is passed through to `org-format-outline-path'. It separates
  6497. the different parts of the path and defaults to \"/\".
  6498. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  6499. (interactive "P")
  6500. (let* (case-fold-search
  6501. (bfn (buffer-file-name (buffer-base-buffer)))
  6502. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  6503. res)
  6504. (when current (setq path (append path
  6505. (save-excursion
  6506. (org-back-to-heading t)
  6507. (when (looking-at org-complex-heading-regexp)
  6508. (list (match-string 4)))))))
  6509. (setq res
  6510. (org-format-outline-path
  6511. path
  6512. (1- (frame-width))
  6513. (and file bfn (concat (file-name-nondirectory bfn) separator))
  6514. separator))
  6515. (add-face-text-property 0 (length res)
  6516. `(:height ,(face-attribute 'default :height))
  6517. nil res)
  6518. (if just-return-string
  6519. res
  6520. (org-unlogged-message "%s" res))))
  6521. ;;; Outline Sorting
  6522. (defun org-sort (&optional with-case)
  6523. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  6524. Optional argument WITH-CASE means sort case-sensitively."
  6525. (interactive "P")
  6526. (org-call-with-arg
  6527. (cond ((org-at-table-p) #'org-table-sort-lines)
  6528. ((org-at-item-p) #'org-sort-list)
  6529. (t #'org-sort-entries))
  6530. with-case))
  6531. (defun org-sort-remove-invisible (s)
  6532. "Remove emphasis markers and any invisible property from string S.
  6533. Assume S may contain only objects."
  6534. ;; org-element-interpret-data clears any text property, including
  6535. ;; invisible part.
  6536. (org-element-interpret-data
  6537. (let ((tree (org-element-parse-secondary-string
  6538. s (org-element-restriction 'paragraph))))
  6539. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  6540. (lambda (o)
  6541. (pcase (org-element-type o)
  6542. ;; Terminal object. Replace it with its value.
  6543. ((or `code `verbatim)
  6544. (let ((new (org-element-property :value o)))
  6545. (org-element-insert-before new o)
  6546. (org-element-put-property
  6547. new :post-blank (org-element-property :post-blank o))))
  6548. ;; Non-terminal objects. Splice contents.
  6549. (type
  6550. (let ((contents
  6551. (or (org-element-contents o)
  6552. (and (eq type 'link)
  6553. (list (org-element-property :raw-link o)))))
  6554. (c nil))
  6555. (while contents
  6556. (setq c (pop contents))
  6557. (org-element-insert-before c o))
  6558. (org-element-put-property
  6559. c :post-blank (org-element-property :post-blank o)))))
  6560. (org-element-extract-element o)))
  6561. ;; Return modified tree.
  6562. tree)))
  6563. (defvar org-after-sorting-entries-or-items-hook nil
  6564. "Hook that is run after a bunch of entries or items have been sorted.
  6565. When children are sorted, the cursor is in the parent line when this
  6566. hook gets called. When a region or a plain list is sorted, the cursor
  6567. will be in the first entry of the sorted region/list.")
  6568. (defun org-sort-entries
  6569. (&optional with-case sorting-type getkey-func compare-func property
  6570. interactive?)
  6571. "Sort entries on a certain level of an outline tree.
  6572. If there is an active region, the entries in the region are sorted.
  6573. Else, if the cursor is before the first entry, sort the top-level items.
  6574. Else, the children of the entry at point are sorted.
  6575. Sorting can be alphabetically, numerically, by date/time as given by
  6576. a time stamp, by a property, by priority order, or by a custom function.
  6577. The command prompts for the sorting type unless it has been given to the
  6578. function through the SORTING-TYPE argument, which needs to be a character,
  6579. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  6580. the precise meaning of each character:
  6581. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  6582. c By creation time, which is assumed to be the first inactive time stamp
  6583. at the beginning of a line.
  6584. d By deadline date/time.
  6585. k By clocking time.
  6586. n Numerically, by converting the beginning of the entry/item to a number.
  6587. o By order of TODO keywords.
  6588. p By priority according to the cookie.
  6589. r By the value of a property.
  6590. s By scheduled date/time.
  6591. t By date/time, either the first active time stamp in the entry, or, if
  6592. none exist, by the first inactive one.
  6593. Capital letters will reverse the sort order.
  6594. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  6595. called with point at the beginning of the record. It must return a
  6596. value that is compatible with COMPARE-FUNC, the function used to
  6597. compare entries.
  6598. Comparing entries ignores case by default. However, with an optional argument
  6599. WITH-CASE, the sorting considers case as well.
  6600. Sorting is done against the visible part of the headlines, it ignores hidden
  6601. links.
  6602. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  6603. A non-nil value for INTERACTIVE? is used to signal that this
  6604. function is being called interactively."
  6605. (interactive (list current-prefix-arg nil nil nil nil t))
  6606. (let ((case-func (if with-case 'identity 'downcase))
  6607. start beg end stars re re2
  6608. txt what tmp)
  6609. ;; Find beginning and end of region to sort
  6610. (cond
  6611. ((org-region-active-p)
  6612. ;; we will sort the region
  6613. (setq end (region-end)
  6614. what "region")
  6615. (goto-char (region-beginning))
  6616. (unless (org-at-heading-p) (outline-next-heading))
  6617. (setq start (point)))
  6618. ((or (org-at-heading-p)
  6619. (ignore-errors (progn (org-back-to-heading) t)))
  6620. ;; we will sort the children of the current headline
  6621. (org-back-to-heading)
  6622. (setq start (point)
  6623. end (progn (org-end-of-subtree t t)
  6624. (or (bolp) (insert "\n"))
  6625. (when (>= (org-back-over-empty-lines) 1)
  6626. (forward-line 1))
  6627. (point))
  6628. what "children")
  6629. (goto-char start)
  6630. (org-fold-show-subtree)
  6631. (outline-next-heading))
  6632. (t
  6633. ;; we will sort the top-level entries in this file
  6634. (goto-char (point-min))
  6635. (or (org-at-heading-p) (outline-next-heading))
  6636. (setq start (point))
  6637. (goto-char (point-max))
  6638. (beginning-of-line 1)
  6639. (when (looking-at ".*?\\S-")
  6640. ;; File ends in a non-white line
  6641. (end-of-line 1)
  6642. (insert "\n"))
  6643. (setq end (point-max))
  6644. (setq what "top-level")
  6645. (goto-char start)
  6646. (org-fold-show-all '(headings drawers blocks))))
  6647. (setq beg (point))
  6648. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  6649. (looking-at "\\(\\*+\\)")
  6650. (setq stars (match-string 1)
  6651. re (concat "^" (regexp-quote stars) " +")
  6652. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  6653. txt (buffer-substring beg end))
  6654. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  6655. (when (and (not (equal stars "*")) (string-match re2 txt))
  6656. (user-error "Region to sort contains a level above the first entry"))
  6657. (unless sorting-type
  6658. (message
  6659. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  6660. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  6661. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  6662. what)
  6663. (setq sorting-type (read-char-exclusive)))
  6664. (unless getkey-func
  6665. (and (= (downcase sorting-type) ?f)
  6666. (setq getkey-func
  6667. (or (and interactive?
  6668. (org-read-function
  6669. "Function for extracting keys: "))
  6670. (error "Missing key extractor")))))
  6671. (and (= (downcase sorting-type) ?r)
  6672. (not property)
  6673. (setq property
  6674. (completing-read "Property: "
  6675. (mapcar #'list (org-buffer-property-keys t))
  6676. nil t)))
  6677. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  6678. (message "Sorting entries...")
  6679. (save-restriction
  6680. (narrow-to-region start end)
  6681. (let ((restore-clock?
  6682. ;; The clock marker is lost when using `sort-subr'; mark
  6683. ;; the clock with temporary `:org-clock-marker-backup'
  6684. ;; text property.
  6685. (when (and (eq (org-clocking-buffer) (current-buffer))
  6686. (<= start (marker-position org-clock-marker))
  6687. (>= end (marker-position org-clock-marker)))
  6688. (with-silent-modifications
  6689. (put-text-property (1- org-clock-marker) org-clock-marker
  6690. :org-clock-marker-backup t))
  6691. t))
  6692. (dcst (downcase sorting-type))
  6693. (case-fold-search nil)
  6694. (now (current-time)))
  6695. (org-preserve-local-variables
  6696. (sort-subr
  6697. (/= dcst sorting-type)
  6698. ;; This function moves to the beginning character of the
  6699. ;; "record" to be sorted.
  6700. (lambda nil
  6701. (if (re-search-forward re nil t)
  6702. (goto-char (match-beginning 0))
  6703. (goto-char (point-max))))
  6704. ;; This function moves to the last character of the "record" being
  6705. ;; sorted.
  6706. (lambda nil
  6707. (save-match-data
  6708. (condition-case nil
  6709. (outline-forward-same-level 1)
  6710. (error
  6711. (goto-char (point-max))))))
  6712. ;; This function returns the value that gets sorted against.
  6713. (lambda ()
  6714. (cond
  6715. ((= dcst ?n)
  6716. (string-to-number
  6717. (org-sort-remove-invisible (org-get-heading t t t t))))
  6718. ((= dcst ?a)
  6719. (funcall case-func
  6720. (org-sort-remove-invisible (org-get-heading t t t t))))
  6721. ((= dcst ?k)
  6722. (or (get-text-property (point) :org-clock-minutes) 0))
  6723. ((= dcst ?t)
  6724. (let ((end (save-excursion (outline-next-heading) (point))))
  6725. (if (or (re-search-forward org-ts-regexp end t)
  6726. (re-search-forward org-ts-regexp-both end t))
  6727. (org-time-string-to-seconds (match-string 0))
  6728. (float-time now))))
  6729. ((= dcst ?c)
  6730. (let ((end (save-excursion (outline-next-heading) (point))))
  6731. (if (re-search-forward
  6732. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  6733. end t)
  6734. (org-time-string-to-seconds (match-string 0))
  6735. (float-time now))))
  6736. ((= dcst ?s)
  6737. (let ((end (save-excursion (outline-next-heading) (point))))
  6738. (if (re-search-forward org-scheduled-time-regexp end t)
  6739. (org-time-string-to-seconds (match-string 1))
  6740. (float-time now))))
  6741. ((= dcst ?d)
  6742. (let ((end (save-excursion (outline-next-heading) (point))))
  6743. (if (re-search-forward org-deadline-time-regexp end t)
  6744. (org-time-string-to-seconds (match-string 1))
  6745. (float-time now))))
  6746. ((= dcst ?p)
  6747. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  6748. (string-to-char (match-string 2))
  6749. org-priority-default))
  6750. ((= dcst ?r)
  6751. (or (org-entry-get nil property) ""))
  6752. ((= dcst ?o)
  6753. (when (looking-at org-complex-heading-regexp)
  6754. (let* ((m (match-string 2))
  6755. (s (if (member m org-done-keywords) '- '+)))
  6756. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  6757. ((= dcst ?f)
  6758. (if getkey-func
  6759. (progn
  6760. (setq tmp (funcall getkey-func))
  6761. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  6762. tmp)
  6763. (error "Invalid key function `%s'" getkey-func)))
  6764. (t (error "Invalid sorting type `%c'" sorting-type))))
  6765. nil
  6766. (cond
  6767. ((= dcst ?a) 'string-collate-lessp)
  6768. ((= dcst ?f)
  6769. (or compare-func
  6770. (and interactive?
  6771. (org-read-function
  6772. (concat "Function for comparing keys "
  6773. "(empty for default `sort-subr' predicate): ")
  6774. 'allow-empty))))
  6775. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  6776. (org-cycle-hide-drawers 'all)
  6777. (when restore-clock?
  6778. (move-marker org-clock-marker
  6779. (1+ (next-single-property-change
  6780. start :org-clock-marker-backup)))
  6781. (remove-text-properties (1- org-clock-marker) org-clock-marker
  6782. '(:org-clock-marker-backup t)))))
  6783. (run-hooks 'org-after-sorting-entries-or-items-hook)
  6784. (message "Sorting entries...done")))
  6785. (defun org-contextualize-keys (alist contexts)
  6786. "Return valid elements in ALIST depending on CONTEXTS.
  6787. `org-agenda-custom-commands' or `org-capture-templates' are the
  6788. values used for ALIST, and `org-agenda-custom-commands-contexts'
  6789. or `org-capture-templates-contexts' are the associated contexts
  6790. definitions."
  6791. (let ((contexts
  6792. ;; normalize contexts
  6793. (mapcar
  6794. (lambda(c) (cond ((listp (cadr c))
  6795. (list (car c) (car c) (nth 1 c)))
  6796. ((string= "" (cadr c))
  6797. (list (car c) (car c) (nth 2 c)))
  6798. (t c)))
  6799. contexts))
  6800. (a alist) r s)
  6801. ;; loop over all commands or templates
  6802. (dolist (c a)
  6803. (let (vrules repl)
  6804. (cond
  6805. ((not (assoc (car c) contexts))
  6806. (push c r))
  6807. ((and (assoc (car c) contexts)
  6808. (setq vrules (org-contextualize-validate-key
  6809. (car c) contexts)))
  6810. (mapc (lambda (vr)
  6811. (unless (equal (car vr) (cadr vr))
  6812. (setq repl vr)))
  6813. vrules)
  6814. (if (not repl) (push c r)
  6815. (push (cadr repl) s)
  6816. (push
  6817. (cons (car c)
  6818. (cdr (or (assoc (cadr repl) alist)
  6819. (error "Undefined key `%s' as contextual replacement for `%s'"
  6820. (cadr repl) (car c)))))
  6821. r))))))
  6822. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  6823. (delq
  6824. nil
  6825. (delete-dups
  6826. (mapcar (lambda (x)
  6827. (let ((tpl (car x)))
  6828. (unless (delq
  6829. nil
  6830. (mapcar (lambda (y)
  6831. (equal y tpl))
  6832. s))
  6833. x)))
  6834. (reverse r))))))
  6835. (defun org-contextualize-validate-key (key contexts)
  6836. "Check CONTEXTS for agenda or capture KEY."
  6837. (let (res)
  6838. (dolist (r contexts)
  6839. (dolist (rr (car (last r)))
  6840. (when
  6841. (and (equal key (car r))
  6842. (if (functionp rr) (funcall rr)
  6843. (or (and (eq (car rr) 'in-file)
  6844. (buffer-file-name)
  6845. (string-match (cdr rr) (buffer-file-name)))
  6846. (and (eq (car rr) 'in-mode)
  6847. (string-match (cdr rr) (symbol-name major-mode)))
  6848. (and (eq (car rr) 'in-buffer)
  6849. (string-match (cdr rr) (buffer-name)))
  6850. (when (and (eq (car rr) 'not-in-file)
  6851. (buffer-file-name))
  6852. (not (string-match (cdr rr) (buffer-file-name))))
  6853. (when (eq (car rr) 'not-in-mode)
  6854. (not (string-match (cdr rr) (symbol-name major-mode))))
  6855. (when (eq (car rr) 'not-in-buffer)
  6856. (not (string-match (cdr rr) (buffer-name)))))))
  6857. (push r res))))
  6858. (delete-dups (delq nil res))))
  6859. ;; Defined to provide a value for defcustom, since there is no
  6860. ;; string-collate-greaterp in Emacs.
  6861. (defun org-string-collate-greaterp (s1 s2)
  6862. "Return non-nil if S1 is greater than S2 in collation order."
  6863. (not (string-collate-lessp s1 s2)))
  6864. ;;;###autoload
  6865. (defun org-run-like-in-org-mode (cmd)
  6866. "Run a command, pretending that the current buffer is in Org mode.
  6867. This will temporarily bind local variables that are typically bound in
  6868. Org mode to the values they have in Org mode, and then interactively
  6869. call CMD."
  6870. (org-load-modules-maybe)
  6871. (let (vars vals)
  6872. (dolist (var (org-get-local-variables))
  6873. (when (or (not (boundp (car var)))
  6874. (eq (symbol-value (car var))
  6875. (default-value (car var))))
  6876. (push (car var) vars)
  6877. (push (cadr var) vals)))
  6878. (cl-progv vars vals
  6879. (call-interactively cmd))))
  6880. (defun org-get-category (&optional pos force-refresh)
  6881. "Get the category applying to position POS."
  6882. (save-match-data
  6883. (when force-refresh (org-refresh-category-properties))
  6884. (let ((pos (or pos (point))))
  6885. (if (org-element--cache-active-p)
  6886. ;; Sync cache.
  6887. (org-with-point-at (org-element-property :begin (org-element-at-point pos))
  6888. (or (org-entry-get-with-inheritance "CATEGORY")
  6889. "???"))
  6890. (or (get-text-property pos 'org-category)
  6891. (progn
  6892. (org-refresh-category-properties)
  6893. (get-text-property pos 'org-category)))))))
  6894. ;;; Refresh properties
  6895. (defun org-refresh-properties (dprop tprop)
  6896. "Refresh buffer text properties.
  6897. DPROP is the drawer property and TPROP is either the
  6898. corresponding text property to set, or an alist with each element
  6899. being a text property (as a symbol) and a function to apply to
  6900. the value of the drawer property."
  6901. (let* ((case-fold-search t)
  6902. (inhibit-read-only t)
  6903. (inherit? (org-property-inherit-p dprop))
  6904. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  6905. (global-or-keyword (and inherit?
  6906. (org--property-global-or-keyword-value dprop nil))))
  6907. (with-silent-modifications
  6908. (org-with-point-at 1
  6909. ;; Set global and keyword based values to the whole buffer.
  6910. (when global-or-keyword
  6911. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  6912. ;; Set values based on property-drawers throughout the document.
  6913. (while (re-search-forward property-re nil t)
  6914. (when (org-at-property-p)
  6915. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  6916. (outline-next-heading))))))
  6917. (defun org-refresh-property (tprop p &optional inherit)
  6918. "Refresh the buffer text property TPROP from the drawer property P.
  6919. The refresh happens only for the current entry, or the whole
  6920. sub-tree if optional argument INHERIT is non-nil.
  6921. If point is before first headline, the function applies to the
  6922. part before the first headline. In that particular case, when
  6923. optional argument INHERIT is non-nil, it refreshes properties for
  6924. the whole buffer."
  6925. (save-excursion
  6926. (org-back-to-heading-or-point-min t)
  6927. (let ((start (point))
  6928. (end (save-excursion
  6929. (cond ((and inherit (org-before-first-heading-p))
  6930. (point-max))
  6931. (inherit
  6932. (org-end-of-subtree t t))
  6933. ((outline-next-heading))
  6934. ((point-max))))))
  6935. (with-silent-modifications
  6936. (if (symbolp tprop)
  6937. ;; TPROP is a text property symbol.
  6938. (put-text-property start end tprop p)
  6939. ;; TPROP is an alist with (property . function) elements.
  6940. (pcase-dolist (`(,prop . ,f) tprop)
  6941. (put-text-property start end prop (funcall f p))))))))
  6942. (defun org-refresh-category-properties ()
  6943. "Refresh category text properties in the buffer."
  6944. (unless (org-element--cache-active-p)
  6945. (let ((case-fold-search t)
  6946. (inhibit-read-only t)
  6947. (default-category
  6948. (cond ((null org-category)
  6949. (if buffer-file-name
  6950. (file-name-sans-extension
  6951. (file-name-nondirectory buffer-file-name))
  6952. "???"))
  6953. ((symbolp org-category) (symbol-name org-category))
  6954. (t org-category))))
  6955. (let ((category (catch 'buffer-category
  6956. (org-with-wide-buffer
  6957. (goto-char (point-max))
  6958. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  6959. (let ((element (org-element-at-point-no-context)))
  6960. (when (eq (org-element-type element) 'keyword)
  6961. (throw 'buffer-category
  6962. (org-element-property :value element))))))
  6963. default-category)))
  6964. (with-silent-modifications
  6965. (org-with-wide-buffer
  6966. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  6967. ;; keyword. If none is found, fall-back to `org-category' or
  6968. ;; buffer file name, or set it by the document property drawer.
  6969. (put-text-property (point-min) (point-max)
  6970. 'org-category category)
  6971. ;; Set categories from the document property drawer or
  6972. ;; property drawers in the outline. If category is found in
  6973. ;; the property drawer for the whole buffer that value
  6974. ;; overrides the keyword-based value set above.
  6975. (goto-char (point-min))
  6976. (let ((regexp (org-re-property "CATEGORY")))
  6977. (while (re-search-forward regexp nil t)
  6978. (let ((value (match-string-no-properties 3)))
  6979. (when (org-at-property-p)
  6980. (put-text-property
  6981. (save-excursion (org-back-to-heading-or-point-min t))
  6982. (save-excursion (if (org-before-first-heading-p)
  6983. (point-max)
  6984. (org-end-of-subtree t t)))
  6985. 'org-category
  6986. value)))))))))))
  6987. (defun org-refresh-stats-properties ()
  6988. "Refresh stats text properties in the buffer."
  6989. (with-silent-modifications
  6990. (org-with-point-at 1
  6991. (let ((regexp (concat org-outline-regexp-bol
  6992. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  6993. (while (re-search-forward regexp nil t)
  6994. (let* ((numerator (string-to-number (match-string 1)))
  6995. (denominator (and (match-end 2)
  6996. (string-to-number (match-string 2))))
  6997. (stats (cond ((not denominator) numerator) ;percent
  6998. ((= denominator 0) 0)
  6999. (t (/ (* numerator 100) denominator)))))
  7000. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7001. 'org-stats stats)))))))
  7002. (defun org-refresh-effort-properties ()
  7003. "Refresh effort properties."
  7004. (org-refresh-properties
  7005. org-effort-property
  7006. '((effort . identity)
  7007. (effort-minutes . org-duration-to-minutes))))
  7008. (defun org-find-file-at-mouse (ev)
  7009. "Open file link or URL at mouse."
  7010. (interactive "e")
  7011. (mouse-set-point ev)
  7012. (org-open-at-point 'in-emacs))
  7013. (defun org-open-at-mouse (ev)
  7014. "Open file link or URL at mouse.
  7015. See the docstring of `org-open-file' for details."
  7016. (interactive "e")
  7017. (mouse-set-point ev)
  7018. (when (eq major-mode 'org-agenda-mode)
  7019. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7020. (org-open-at-point))
  7021. (defvar org-window-config-before-follow-link nil
  7022. "The window configuration before following a link.
  7023. This is saved in case the need arises to restore it.")
  7024. (defun org--file-default-apps ()
  7025. "Return the default applications for this operating system."
  7026. (pcase system-type
  7027. (`darwin org-file-apps-macos)
  7028. (`windows-nt org-file-apps-windowsnt)
  7029. (_ org-file-apps-gnu)))
  7030. (defun org--file-apps-entry-dlink-p (entry)
  7031. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7032. It assumes that is the case when the entry uses a regular
  7033. expression which has at least one grouping construct and the
  7034. action is either a Lisp form or a command string containing
  7035. \"%1\", i.e., using at least one subexpression match as
  7036. a parameter."
  7037. (pcase entry
  7038. (`(,selector . ,action)
  7039. (and (stringp selector)
  7040. (> (regexp-opt-depth selector) 0)
  7041. (or (and (stringp action)
  7042. (string-match "%[0-9]" action))
  7043. (consp action))))
  7044. (_ nil)))
  7045. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7046. "Convert extensions to regular expressions in the cars of LIST.
  7047. Also, weed out any non-string entries, because the return value
  7048. is used only for regexp matching.
  7049. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7050. point to the symbol `emacs', indicating that the file should be
  7051. opened in Emacs."
  7052. (append
  7053. (delq nil
  7054. (mapcar (lambda (x)
  7055. (unless (not (stringp (car x)))
  7056. (if (string-match "\\W" (car x))
  7057. x
  7058. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7059. list))
  7060. (when add-auto-mode
  7061. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7062. ;;;###autoload
  7063. (defun org-open-file (path &optional in-emacs line search)
  7064. "Open the file at PATH.
  7065. First, this expands any special file name abbreviations. Then the
  7066. configuration variable `org-file-apps' is checked if it contains an
  7067. entry for this file type, and if yes, the corresponding command is launched.
  7068. If no application is found, Emacs simply visits the file.
  7069. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7070. With a double \\[universal-argument] \\[universal-argument] \
  7071. prefix arg, Org tries to avoid opening in Emacs
  7072. and to use an external application to visit the file.
  7073. Optional LINE specifies a line to go to, optional SEARCH a string
  7074. to search for. If LINE or SEARCH is given, the file will be
  7075. opened in Emacs, unless an entry from `org-file-apps' that makes
  7076. use of groups in a regexp matches.
  7077. If you want to change the way frames are used when following a
  7078. link, please customize `org-link-frame-setup'.
  7079. If the file does not exist, throw an error."
  7080. (let* ((file (if (equal path "") buffer-file-name
  7081. (substitute-in-file-name (expand-file-name path))))
  7082. (file-apps (append org-file-apps (org--file-default-apps)))
  7083. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7084. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7085. file-apps))
  7086. (remp (and (assq 'remote apps) (file-remote-p file)))
  7087. (dirp (unless remp (file-directory-p file)))
  7088. (file (if (and dirp org-open-directory-means-index-dot-org)
  7089. (concat (file-name-as-directory file) "index.org")
  7090. file))
  7091. (a-m-a-p (assq 'auto-mode apps))
  7092. (dfile (downcase file))
  7093. ;; Reconstruct the original link from the PATH, LINE and
  7094. ;; SEARCH args.
  7095. (link (cond (line (concat file "::" (number-to-string line)))
  7096. (search (concat file "::" search))
  7097. (t file)))
  7098. (dlink (downcase link))
  7099. (ext
  7100. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7101. (match-string 1 dfile)))
  7102. (save-position-maybe
  7103. (let ((old-buffer (current-buffer))
  7104. (old-pos (point))
  7105. (old-mode major-mode))
  7106. (lambda ()
  7107. (and (derived-mode-p 'org-mode)
  7108. (eq old-mode 'org-mode)
  7109. (or (not (eq old-buffer (current-buffer)))
  7110. (not (eq old-pos (point))))
  7111. (org-mark-ring-push old-pos old-buffer)))))
  7112. cmd link-match-data)
  7113. (cond
  7114. ((member in-emacs '((16) system))
  7115. (setq cmd (cdr (assq 'system apps))))
  7116. (in-emacs (setq cmd 'emacs))
  7117. (t
  7118. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7119. (and dirp (cdr (assq 'directory apps)))
  7120. ;; First, try matching against apps-dlink if we
  7121. ;; get a match here, store the match data for
  7122. ;; later.
  7123. (let ((match (assoc-default dlink apps-dlink
  7124. 'string-match)))
  7125. (if match
  7126. (progn (setq link-match-data (match-data))
  7127. match)
  7128. (progn (setq in-emacs (or in-emacs line search))
  7129. nil))) ; if we have no match in apps-dlink,
  7130. ; always open the file in emacs if line or search
  7131. ; is given (for backwards compatibility)
  7132. (assoc-default dfile
  7133. (org--file-apps-regexp-alist apps a-m-a-p)
  7134. 'string-match)
  7135. (cdr (assoc ext apps))
  7136. (cdr (assq t apps))))))
  7137. (when (eq cmd 'system)
  7138. (setq cmd (cdr (assq 'system apps))))
  7139. (when (eq cmd 'default)
  7140. (setq cmd (cdr (assoc t apps))))
  7141. (when (eq cmd 'mailcap)
  7142. (require 'mailcap)
  7143. (mailcap-parse-mailcaps)
  7144. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7145. (command (mailcap-mime-info mime-type)))
  7146. (if (stringp command)
  7147. (setq cmd command)
  7148. (setq cmd 'emacs))))
  7149. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7150. (not (file-exists-p file))
  7151. (not org-open-non-existing-files))
  7152. (user-error "No such file: %s" file))
  7153. (cond
  7154. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7155. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7156. (while (string-match "['\"]%s['\"]" cmd)
  7157. (setq cmd (replace-match "%s" t t cmd)))
  7158. (setq cmd (replace-regexp-in-string
  7159. "%s"
  7160. (shell-quote-argument (convert-standard-filename file))
  7161. cmd
  7162. nil t))
  7163. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7164. (save-match-data
  7165. (let ((match-index 1)
  7166. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7167. (set-match-data link-match-data)
  7168. (while (<= match-index number-of-groups)
  7169. (let ((regex (concat "%" (number-to-string match-index)))
  7170. (replace-with (match-string match-index dlink)))
  7171. (while (string-match regex cmd)
  7172. (setq cmd (replace-match replace-with t t cmd))))
  7173. (setq match-index (+ match-index 1)))))
  7174. (save-window-excursion
  7175. (message "Running %s...done" cmd)
  7176. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7177. ;; and exit immediately. Use pipe connection type instead of pty to
  7178. ;; avoid killing children processes with SIGHUP when temporary terminal
  7179. ;; session is finished.
  7180. ;;
  7181. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7182. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7183. ;; error messages.
  7184. (let ((process-connection-type nil))
  7185. (start-process-shell-command cmd nil cmd))
  7186. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7187. ((or (stringp cmd)
  7188. (eq cmd 'emacs))
  7189. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7190. (widen)
  7191. (cond (line (org-goto-line line)
  7192. (when (derived-mode-p 'org-mode) (org-fold-reveal)))
  7193. (search (condition-case err
  7194. (org-link-search search)
  7195. ;; Save position before error-ing out so user
  7196. ;; can easily move back to the original buffer.
  7197. (error (funcall save-position-maybe)
  7198. (error (nth 1 err)))))))
  7199. ((functionp cmd)
  7200. (save-match-data
  7201. (set-match-data link-match-data)
  7202. (condition-case nil
  7203. (funcall cmd file link)
  7204. ;; FIXME: Remove this check when most default installations
  7205. ;; of Emacs have at least Org 9.0.
  7206. ((debug wrong-number-of-arguments wrong-type-argument
  7207. invalid-function)
  7208. (user-error "Please see Org News for version 9.0 about \
  7209. `org-file-apps'--Lisp error: %S" cmd)))))
  7210. ((consp cmd)
  7211. ;; FIXME: Remove this check when most default installations of
  7212. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7213. ;; fall back to `org-link-frame-setup' for an old usage of
  7214. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7215. (user-error "Please see Org News for version 9.0 about \
  7216. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7217. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7218. (funcall save-position-maybe)))
  7219. ;;;###autoload
  7220. (defun org-open-at-point-global ()
  7221. "Follow a link or a time-stamp like Org mode does.
  7222. Also follow links and emails as seen by `thing-at-point'.
  7223. This command can be called in any mode to follow an external
  7224. link or a time-stamp that has Org mode syntax. Its behavior
  7225. is undefined when called on internal links like fuzzy links.
  7226. Raise a user error when there is nothing to follow."
  7227. (interactive)
  7228. (let ((tap-url (thing-at-point 'url))
  7229. (tap-email (thing-at-point 'email)))
  7230. (cond ((org-in-regexp org-link-any-re)
  7231. (org-link-open-from-string (match-string-no-properties 0)))
  7232. ((or (org-in-regexp org-ts-regexp-both nil t)
  7233. (org-in-regexp org-tsr-regexp-both nil t))
  7234. (org-follow-timestamp-link))
  7235. (tap-url (org-link-open-from-string tap-url))
  7236. (tap-email (org-link-open-from-string
  7237. (concat "mailto:" tap-email)))
  7238. (t (user-error "No link found")))))
  7239. (defvar org-open-at-point-functions nil
  7240. "Hook that is run when following a link at point.
  7241. Functions in this hook must return t if they identify and follow
  7242. a link at point. If they don't find anything interesting at point,
  7243. they must return nil.")
  7244. (defun org-open-at-point (&optional arg)
  7245. "Open link, timestamp, footnote or tags at point.
  7246. When point is on a link, follow it. Normally, files will be
  7247. opened by an appropriate application. If the optional prefix
  7248. argument ARG is non-nil, Emacs will visit the file. With
  7249. a double prefix argument, try to open outside of Emacs, in the
  7250. application the system uses for this file type.
  7251. When point is on a timestamp, open the agenda at the day
  7252. specified.
  7253. When point is a footnote definition, move to the first reference
  7254. found. If it is on a reference, move to the associated
  7255. definition.
  7256. When point is on a headline, display a list of every link in the
  7257. entry, so it is possible to pick one, or all, of them. If point
  7258. is on a tag, call `org-tags-view' instead.
  7259. On top of syntactically correct links, this function also tries
  7260. to open links and time-stamps in comments, node properties, and
  7261. keywords if point is on something looking like a timestamp or
  7262. a link."
  7263. (interactive "P")
  7264. (org-load-modules-maybe)
  7265. (setq org-window-config-before-follow-link (current-window-configuration))
  7266. (org-remove-occur-highlights nil nil t)
  7267. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  7268. (let* ((context
  7269. ;; Only consider supported types, even if they are not the
  7270. ;; closest one.
  7271. (org-element-lineage
  7272. (org-element-context)
  7273. '(citation citation-reference clock comment comment-block
  7274. footnote-definition footnote-reference headline
  7275. inline-src-block inlinetask keyword link node-property
  7276. planning src-block timestamp)
  7277. t))
  7278. (type (org-element-type context))
  7279. (value (org-element-property :value context)))
  7280. (cond
  7281. ((not type) (user-error "No link found"))
  7282. ;; No valid link at point. For convenience, look if something
  7283. ;; looks like a link under point in some specific places.
  7284. ((memq type '(comment comment-block node-property keyword))
  7285. (call-interactively #'org-open-at-point-global))
  7286. ;; On a headline or an inlinetask, but not on a timestamp,
  7287. ;; a link, a footnote reference or a citation.
  7288. ((memq type '(headline inlinetask))
  7289. (org-match-line org-complex-heading-regexp)
  7290. (let ((tags-beg (match-beginning 5))
  7291. (tags-end (match-end 5)))
  7292. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  7293. ;; On tags.
  7294. (org-tags-view
  7295. arg
  7296. (save-excursion
  7297. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  7298. (end-tag (search-forward ":" tags-end nil 2)))
  7299. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  7300. ;; Not on tags.
  7301. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  7302. (`(nil . ,_)
  7303. (require 'org-attach)
  7304. (when (org-attach-dir)
  7305. (message "Opening attachment")
  7306. (if (equal arg '(4))
  7307. (org-attach-reveal-in-emacs)
  7308. (org-attach-reveal))))
  7309. (`(,links . ,links-end)
  7310. (dolist (link (if (stringp links) (list links) links))
  7311. (search-forward link nil links-end)
  7312. (goto-char (match-beginning 0))
  7313. (org-open-at-point arg)))))))
  7314. ;; On a footnote reference or at definition's label.
  7315. ((or (eq type 'footnote-reference)
  7316. (and (eq type 'footnote-definition)
  7317. (save-excursion
  7318. ;; Do not validate action when point is on the
  7319. ;; spaces right after the footnote label, in order
  7320. ;; to be on par with behavior on links.
  7321. (skip-chars-forward " \t")
  7322. (let ((begin
  7323. (org-element-property :contents-begin context)))
  7324. (if begin (< (point) begin)
  7325. (= (org-element-property :post-affiliated context)
  7326. (line-beginning-position)))))))
  7327. (org-footnote-action))
  7328. ;; On a planning line. Check if we are really on a timestamp.
  7329. ((and (eq type 'planning)
  7330. (org-in-regexp org-ts-regexp-both nil t))
  7331. (org-follow-timestamp-link))
  7332. ;; On a clock line, make sure point is on the timestamp
  7333. ;; before opening it.
  7334. ((and (eq type 'clock)
  7335. value
  7336. (>= (point) (org-element-property :begin value))
  7337. (<= (point) (org-element-property :end value)))
  7338. (org-follow-timestamp-link))
  7339. ((eq type 'src-block) (org-babel-open-src-block-result))
  7340. ;; Do nothing on white spaces after an object.
  7341. ((>= (point)
  7342. (save-excursion
  7343. (goto-char (org-element-property :end context))
  7344. (skip-chars-backward " \t")
  7345. (point)))
  7346. (user-error "No link found"))
  7347. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  7348. ((eq type 'timestamp) (org-follow-timestamp-link))
  7349. ((eq type 'link) (org-link-open context arg))
  7350. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  7351. (t (user-error "No link found")))))
  7352. (run-hook-with-args 'org-follow-link-hook))
  7353. ;;;###autoload
  7354. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  7355. "Offer links in the current entry and return the selected link.
  7356. If there is only one link, return it.
  7357. If NTH is an integer, return the NTH link found.
  7358. If ZERO is a string, check also this string for a link, and if
  7359. there is one, return it."
  7360. (with-current-buffer buffer
  7361. (org-with-wide-buffer
  7362. (goto-char marker)
  7363. (let ((cnt ?0)
  7364. have-zero end links link c)
  7365. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  7366. (push (match-string 0 zero) links)
  7367. (setq cnt (1- cnt) have-zero t))
  7368. (save-excursion
  7369. (org-back-to-heading t)
  7370. (setq end (save-excursion (outline-next-heading) (point)))
  7371. (while (re-search-forward org-link-any-re end t)
  7372. (push (match-string 0) links))
  7373. (setq links (org-uniquify (reverse links))))
  7374. (cond
  7375. ((null links)
  7376. (message "No links"))
  7377. ((equal (length links) 1)
  7378. (setq link (car links)))
  7379. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  7380. (setq link (nth (if have-zero nth (1- nth)) links)))
  7381. (t ; we have to select a link
  7382. (save-excursion
  7383. (save-window-excursion
  7384. (delete-other-windows)
  7385. (with-output-to-temp-buffer "*Select Link*"
  7386. (dolist (l links)
  7387. (cond
  7388. ((not (string-match org-link-bracket-re l))
  7389. (princ (format "[%c] %s\n" (cl-incf cnt)
  7390. (org-unbracket-string "<" ">" l))))
  7391. ((match-end 2)
  7392. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  7393. (match-string 2 l) (match-string 1 l))))
  7394. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  7395. (match-string 1 l)))))))
  7396. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  7397. (message "Select link to open, RET to open all:")
  7398. (setq c (read-char-exclusive))
  7399. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  7400. (when (equal c ?q) (user-error "Abort"))
  7401. (if (equal c ?\C-m)
  7402. (setq link links)
  7403. (setq nth (- c ?0))
  7404. (when have-zero (setq nth (1+ nth)))
  7405. (unless (and (integerp nth) (>= (length links) nth))
  7406. (user-error "Invalid link selection"))
  7407. (setq link (nth (1- nth) links)))))
  7408. (cons link end)))))
  7409. ;;; File search
  7410. (defun org-do-occur (regexp &optional cleanup)
  7411. "Call the Emacs command `occur'.
  7412. If CLEANUP is non-nil, remove the printout of the regular expression
  7413. in the *Occur* buffer. This is useful if the regex is long and not useful
  7414. to read."
  7415. (occur regexp)
  7416. (when cleanup
  7417. (let ((cwin (selected-window)) win beg end)
  7418. (when (setq win (get-buffer-window "*Occur*"))
  7419. (select-window win))
  7420. (goto-char (point-min))
  7421. (when (re-search-forward "match[a-z]+" nil t)
  7422. (setq beg (match-end 0))
  7423. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  7424. (setq end (1- (match-beginning 0)))))
  7425. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  7426. (goto-char (point-min))
  7427. (select-window cwin))))
  7428. ;;; The Mark Ring
  7429. (defvar org-mark-ring nil
  7430. "Mark ring for positions before jumps in Org mode.")
  7431. (defvar org-mark-ring-last-goto nil
  7432. "Last position in the mark ring used to go back.")
  7433. ;; Fill and close the ring
  7434. (setq org-mark-ring nil)
  7435. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  7436. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  7437. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  7438. org-mark-ring)
  7439. (defun org-mark-ring-push (&optional pos buffer)
  7440. "Put the current position into the mark ring and rotate it.
  7441. Also push position into the Emacs mark ring. If optional
  7442. argument POS and BUFFER are not nil, mark this location instead."
  7443. (interactive)
  7444. (let ((pos (or pos (point)))
  7445. (buffer (or buffer (current-buffer))))
  7446. (with-current-buffer buffer
  7447. (org-with-point-at pos (push-mark nil t)))
  7448. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  7449. (move-marker (car org-mark-ring) pos buffer))
  7450. (message
  7451. (substitute-command-keys
  7452. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  7453. (defun org-mark-ring-goto (&optional n)
  7454. "Jump to the previous position in the mark ring.
  7455. With prefix arg N, jump back that many stored positions. When
  7456. called several times in succession, walk through the entire ring.
  7457. Org mode commands jumping to a different position in the current file,
  7458. or to another Org file, automatically push the old position onto the ring."
  7459. (interactive "p")
  7460. (let (p m)
  7461. (if (eq last-command this-command)
  7462. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  7463. (setq p org-mark-ring))
  7464. (setq org-mark-ring-last-goto p)
  7465. (setq m (car p))
  7466. (pop-to-buffer-same-window (marker-buffer m))
  7467. (goto-char m)
  7468. (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
  7469. ;;; Following specific links
  7470. (defvar org-agenda-buffer-tmp-name)
  7471. (defvar org-agenda-start-on-weekday)
  7472. (defvar org-agenda-buffer-name)
  7473. (defun org-follow-timestamp-link ()
  7474. "Open an agenda view for the time-stamp date/range at point."
  7475. ;; Avoid changing the global value.
  7476. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  7477. (cond
  7478. ((org-at-date-range-p t)
  7479. (let ((org-agenda-start-on-weekday)
  7480. (t1 (match-string 1))
  7481. (t2 (match-string 2)) tt1 tt2)
  7482. (setq tt1 (time-to-days (org-time-string-to-time t1))
  7483. tt2 (time-to-days (org-time-string-to-time t2)))
  7484. (let ((org-agenda-buffer-tmp-name
  7485. (format "*Org Agenda(a:%s)"
  7486. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  7487. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  7488. ((org-at-timestamp-p 'lax)
  7489. (let ((org-agenda-buffer-tmp-name
  7490. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  7491. (org-agenda-list nil (time-to-days (org-time-string-to-time
  7492. (substring (match-string 1) 0 10)))
  7493. 1)))
  7494. (t (error "This should not happen")))))
  7495. ;;; Following file links
  7496. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  7497. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  7498. (declare-function mailcap-mime-info
  7499. "mailcap" (string &optional request no-decode))
  7500. (defvar org-wait nil)
  7501. ;;;; Refiling
  7502. (defun org-get-org-file ()
  7503. "Read a filename, with default directory `org-directory'."
  7504. (let ((default (or org-default-notes-file remember-data-file)))
  7505. (read-file-name (format "File name [%s]: " default)
  7506. (file-name-as-directory org-directory)
  7507. default)))
  7508. (defun org-notes-order-reversed-p ()
  7509. "Check if the current file should receive notes in reversed order."
  7510. (cond
  7511. ((not org-reverse-note-order) nil)
  7512. ((eq t org-reverse-note-order) t)
  7513. ((not (listp org-reverse-note-order)) nil)
  7514. (t (catch 'exit
  7515. (dolist (entry org-reverse-note-order)
  7516. (when (string-match (car entry) buffer-file-name)
  7517. (throw 'exit (cdr entry))))))))
  7518. (defvar org-agenda-new-buffers nil
  7519. "Buffers created to visit agenda files.")
  7520. (declare-function org-string-nw-p "org-macs" (s))
  7521. ;;;; Dynamic blocks
  7522. (defun org-find-dblock (name)
  7523. "Find the first dynamic block with name NAME in the buffer.
  7524. If not found, stay at current position and return nil."
  7525. (let ((case-fold-search t) pos)
  7526. (save-excursion
  7527. (goto-char (point-min))
  7528. (setq pos (and (re-search-forward
  7529. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  7530. (match-beginning 0))))
  7531. (when pos (goto-char pos))
  7532. pos))
  7533. (defun org-create-dblock (plist)
  7534. "Create a dynamic block section, with parameters taken from PLIST.
  7535. PLIST must contain a :name entry which is used as the name of the block."
  7536. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  7537. (end-of-line 1)
  7538. (newline))
  7539. (let ((col (current-column))
  7540. (name (plist-get plist :name)))
  7541. (insert "#+BEGIN: " name)
  7542. (while plist
  7543. (if (eq (car plist) :name)
  7544. (setq plist (cddr plist))
  7545. (insert " " (prin1-to-string (pop plist)))))
  7546. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  7547. (beginning-of-line -2)))
  7548. (defun org-prepare-dblock ()
  7549. "Prepare dynamic block for refresh.
  7550. This empties the block, puts the cursor at the insert position and returns
  7551. the property list including an extra property :name with the block name."
  7552. (unless (looking-at org-dblock-start-re)
  7553. (user-error "Not at a dynamic block"))
  7554. (let* ((begdel (1+ (match-end 0)))
  7555. (name (org-no-properties (match-string 1)))
  7556. (params (append (list :name name)
  7557. (read (concat "(" (match-string 3) ")")))))
  7558. (save-excursion
  7559. (beginning-of-line 1)
  7560. (skip-chars-forward " \t")
  7561. (setq params (plist-put params :indentation-column (current-column))))
  7562. (unless (re-search-forward org-dblock-end-re nil t)
  7563. (error "Dynamic block not terminated"))
  7564. (setq params
  7565. (append params
  7566. (list :content (buffer-substring
  7567. begdel (match-beginning 0)))))
  7568. (delete-region begdel (match-beginning 0))
  7569. (goto-char begdel)
  7570. (open-line 1)
  7571. params))
  7572. (defun org-map-dblocks (&optional command)
  7573. "Apply COMMAND to all dynamic blocks in the current buffer.
  7574. If COMMAND is not given, use `org-update-dblock'."
  7575. (let ((cmd (or command 'org-update-dblock)))
  7576. (save-excursion
  7577. (goto-char (point-min))
  7578. (while (re-search-forward org-dblock-start-re nil t)
  7579. (goto-char (match-beginning 0))
  7580. (save-excursion
  7581. (condition-case nil
  7582. (funcall cmd)
  7583. (error (message "Error during update of dynamic block"))))
  7584. (unless (re-search-forward org-dblock-end-re nil t)
  7585. (error "Dynamic block not terminated"))))))
  7586. (defvar org-dynamic-block-alist nil
  7587. "Alist defining all the Org dynamic blocks.
  7588. The key is the dynamic block type name, as a string. The value
  7589. is the function used to insert the dynamic block.
  7590. Use `org-dynamic-block-define' to populate it.")
  7591. (defun org-dynamic-block-function (type)
  7592. "Return function associated to a given dynamic block type.
  7593. TYPE is the dynamic block type, as a string."
  7594. (cdr (assoc type org-dynamic-block-alist)))
  7595. (defun org-dynamic-block-types ()
  7596. "List all defined dynamic block types."
  7597. (mapcar #'car org-dynamic-block-alist))
  7598. (defun org-dynamic-block-define (type func)
  7599. "Define dynamic block TYPE with FUNC.
  7600. TYPE is a string. FUNC is the function creating the dynamic
  7601. block of such type."
  7602. (pcase (assoc type org-dynamic-block-alist)
  7603. (`nil (push (cons type func) org-dynamic-block-alist))
  7604. (def (setcdr def func))))
  7605. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  7606. "Insert a dynamic block of type TYPE.
  7607. When used interactively, select the dynamic block types among
  7608. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  7609. is non-nil, call the dynamic block function interactively."
  7610. (interactive (list (completing-read "Dynamic block: "
  7611. (org-dynamic-block-types))
  7612. t))
  7613. (pcase (org-dynamic-block-function type)
  7614. (`nil (error "No such dynamic block: %S" type))
  7615. ((and f (pred functionp))
  7616. (if interactive-p (call-interactively f) (funcall f)))
  7617. (_ (error "Invalid function for dynamic block %S" type))))
  7618. (defun org-dblock-update (&optional arg)
  7619. "User command for updating dynamic blocks.
  7620. Update the dynamic block at point. With prefix ARG, update all dynamic
  7621. blocks in the buffer."
  7622. (interactive "P")
  7623. (if arg
  7624. (org-update-all-dblocks)
  7625. (or (looking-at org-dblock-start-re)
  7626. (org-beginning-of-dblock))
  7627. (org-update-dblock)))
  7628. (defun org-update-dblock ()
  7629. "Update the dynamic block at point.
  7630. This means to empty the block, parse for parameters and then call
  7631. the correct writing function."
  7632. (interactive)
  7633. (save-excursion
  7634. (let* ((win (selected-window))
  7635. (pos (point))
  7636. (line (org-current-line))
  7637. (params (org-prepare-dblock))
  7638. (name (plist-get params :name))
  7639. (indent (plist-get params :indentation-column))
  7640. (cmd (intern (concat "org-dblock-write:" name))))
  7641. (message "Updating dynamic block `%s' at line %d..." name line)
  7642. (funcall cmd params)
  7643. (message "Updating dynamic block `%s' at line %d...done" name line)
  7644. (goto-char pos)
  7645. (when (and indent (> indent 0))
  7646. (setq indent (make-string indent ?\ ))
  7647. (save-excursion
  7648. (select-window win)
  7649. (org-beginning-of-dblock)
  7650. (forward-line 1)
  7651. (while (not (looking-at org-dblock-end-re))
  7652. (insert indent)
  7653. (beginning-of-line 2))
  7654. (when (looking-at org-dblock-end-re)
  7655. (and (looking-at "[ \t]+")
  7656. (replace-match ""))
  7657. (insert indent)))))))
  7658. (defun org-beginning-of-dblock ()
  7659. "Find the beginning of the dynamic block at point.
  7660. Error if there is no such block at point."
  7661. (let ((pos (point))
  7662. beg)
  7663. (end-of-line 1)
  7664. (if (and (re-search-backward org-dblock-start-re nil t)
  7665. (setq beg (match-beginning 0))
  7666. (re-search-forward org-dblock-end-re nil t)
  7667. (> (match-end 0) pos))
  7668. (goto-char beg)
  7669. (goto-char pos)
  7670. (error "Not in a dynamic block"))))
  7671. (defun org-update-all-dblocks ()
  7672. "Update all dynamic blocks in the buffer.
  7673. This function can be used in a hook."
  7674. (interactive)
  7675. (when (derived-mode-p 'org-mode)
  7676. (org-map-dblocks 'org-update-dblock)))
  7677. ;;;; Completion
  7678. (declare-function org-export-backend-options "ox" (cl-x) t)
  7679. (defun org-get-export-keywords ()
  7680. "Return a list of all currently understood export keywords.
  7681. Export keywords include options, block names, attributes and
  7682. keywords relative to each registered export back-end."
  7683. (let (keywords)
  7684. (dolist (backend
  7685. (bound-and-true-p org-export-registered-backends)
  7686. (delq nil keywords))
  7687. ;; Back-end name (for keywords, like #+LATEX:)
  7688. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  7689. (dolist (option-entry (org-export-backend-options backend))
  7690. ;; Back-end options.
  7691. (push (nth 1 option-entry) keywords)))))
  7692. (defconst org-options-keywords
  7693. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  7694. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  7695. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  7696. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  7697. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  7698. (defcustom org-structure-template-alist
  7699. '(("a" . "export ascii")
  7700. ("c" . "center")
  7701. ("C" . "comment")
  7702. ("e" . "example")
  7703. ("E" . "export")
  7704. ("h" . "export html")
  7705. ("l" . "export latex")
  7706. ("q" . "quote")
  7707. ("s" . "src")
  7708. ("v" . "verse"))
  7709. "An alist of keys and block types.
  7710. `org-insert-structure-template' will display a menu with this
  7711. list of templates to choose from. The block type is inserted,
  7712. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  7713. The menu keys are defined by the car of each entry in this alist.
  7714. If two entries have the keys \"a\" and \"aa\" respectively, the
  7715. former will be inserted by typing \"a TAB/RET/SPC\" and the
  7716. latter will be inserted by typing \"aa\". If an entry with the
  7717. key \"aab\" is later added, it can be inserted by typing \"ab\".
  7718. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  7719. block can be inserted by pressing TAB after the string \"<KEY\"."
  7720. :group 'org-edit-structure
  7721. :type '(repeat
  7722. (cons (string :tag "Key")
  7723. (string :tag "Template")))
  7724. :package-version '(Org . "9.2"))
  7725. (defun org--check-org-structure-template-alist (&optional checklist)
  7726. "Check whether `org-structure-template-alist' is set up correctly.
  7727. In particular, check if the Org 9.2 format is used as opposed to
  7728. previous format."
  7729. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  7730. (or (symbol-value checklist)
  7731. org-structure-template-alist))))
  7732. (when elm
  7733. (org-display-warning
  7734. (format "
  7735. Please update the entries of `%s'.
  7736. In Org 9.2 the format was changed from something like
  7737. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  7738. to something like
  7739. (\"s\" . \"src\")
  7740. Please refer to the documentation of `org-structure-template-alist'.
  7741. The following entries must be updated:
  7742. %s"
  7743. (or checklist 'org-structure-template-alist)
  7744. (pp-to-string elm))))))
  7745. (defun org--insert-structure-template-mks ()
  7746. "Present `org-structure-template-alist' with `org-mks'.
  7747. Menus are added if keys require more than one keystroke. Tabs
  7748. are added to single key entries when more than one stroke is
  7749. needed. Keys longer than two characters are reduced to two
  7750. characters."
  7751. (org--check-org-structure-template-alist)
  7752. (let* (case-fold-search
  7753. (templates (append org-structure-template-alist
  7754. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  7755. (keys (mapcar #'car templates))
  7756. (start-letters
  7757. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  7758. ;; Sort each element of `org-structure-template-alist' into
  7759. ;; sublists according to the first letter.
  7760. (superlist
  7761. (mapcar (lambda (letter)
  7762. (list letter
  7763. (cl-remove-if-not
  7764. (apply-partially #'string-match-p (concat "^" letter))
  7765. templates :key #'car)))
  7766. start-letters)))
  7767. (org-mks
  7768. (apply #'append
  7769. ;; Make an `org-mks' table. If only one element is
  7770. ;; present in a sublist, make it part of the top-menu,
  7771. ;; otherwise make a submenu according to the starting
  7772. ;; letter and populate it.
  7773. (mapcar (lambda (sublist)
  7774. (if (eq 1 (length (cadr sublist)))
  7775. (mapcar (lambda (elm)
  7776. (list (substring (car elm) 0 1)
  7777. (cdr elm) ""))
  7778. (cadr sublist))
  7779. ;; Create submenu.
  7780. (let* ((topkey (car sublist))
  7781. (elms (cadr sublist))
  7782. (keys (mapcar #'car elms))
  7783. (long (> (length elms) 3)))
  7784. (append
  7785. (list
  7786. ;; Make a description of the submenu.
  7787. (list topkey
  7788. (concat
  7789. (mapconcat #'cdr
  7790. (cl-subseq elms 0 (if long 3 (length elms)))
  7791. ", ")
  7792. (when long ", ..."))))
  7793. ;; List of entries in submenu.
  7794. (cl-mapcar #'list
  7795. (org--insert-structure-template-unique-keys keys)
  7796. (mapcar #'cdr elms)
  7797. (make-list (length elms) ""))))))
  7798. superlist))
  7799. "Select a key\n============"
  7800. "Key: ")))
  7801. (defun org--insert-structure-template-unique-keys (keys)
  7802. "Make a list of unique, two characters long elements from KEYS.
  7803. Elements of length one have a tab appended. Elements of length
  7804. two are kept as is. Longer elements are truncated to length two.
  7805. If an element cannot be made unique, an error is raised."
  7806. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  7807. menu-keys)
  7808. (dolist (key ordered-keys)
  7809. (let ((potential-key
  7810. (cl-case (length key)
  7811. (1 (concat key "\t"))
  7812. (2 key)
  7813. (otherwise
  7814. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  7815. (mapcar (apply-partially #'concat (substring key 0 1))
  7816. (split-string (substring key 1) "" t)))))))
  7817. (if (or (not potential-key) (assoc potential-key menu-keys))
  7818. (user-error "Could not make unique key for `%s'" key)
  7819. (push (cons potential-key key) menu-keys))))
  7820. (mapcar #'car
  7821. (cl-sort menu-keys #'<
  7822. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  7823. (defun org-insert-structure-template (type)
  7824. "Insert a block structure of the type #+begin_foo/#+end_foo.
  7825. Select a block from `org-structure-template-alist' then type
  7826. either RET, TAB or SPC to write the block type. With an active
  7827. region, wrap the region in the block. Otherwise, insert an empty
  7828. block."
  7829. (interactive
  7830. (list (pcase (org--insert-structure-template-mks)
  7831. (`("\t" . ,_) (read-string "Structure type: "))
  7832. (`(,_ ,choice . ,_) choice))))
  7833. (let* ((region? (use-region-p))
  7834. (region-start (and region? (region-beginning)))
  7835. (region-end (and region? (copy-marker (region-end))))
  7836. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  7837. (verbatim? (string-match-p
  7838. (concat "\\`" (regexp-opt '("example" "export" "src")))
  7839. type)))
  7840. (when region? (goto-char region-start))
  7841. (let ((column (current-indentation)))
  7842. (if (save-excursion (skip-chars-backward " \t") (bolp))
  7843. (beginning-of-line)
  7844. (insert "\n"))
  7845. (save-excursion
  7846. (indent-to column)
  7847. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  7848. (when region?
  7849. (when verbatim? (org-escape-code-in-region (point) region-end))
  7850. (goto-char region-end)
  7851. ;; Ignore empty lines at the end of the region.
  7852. (skip-chars-backward " \r\t\n")
  7853. (end-of-line))
  7854. (unless (bolp) (insert "\n"))
  7855. (indent-to column)
  7856. (insert (format "#+end_%s" (car (split-string type))))
  7857. (if (looking-at "[ \t]*$") (replace-match "")
  7858. (insert "\n"))
  7859. (when (and (eobp) (not (bolp))) (insert "\n")))
  7860. (if extended? (end-of-line)
  7861. (forward-line)
  7862. (skip-chars-forward " \t")))))
  7863. ;;;; TODO, DEADLINE, Comments
  7864. (defun org-toggle-comment ()
  7865. "Change the COMMENT state of an entry."
  7866. (interactive)
  7867. (save-excursion
  7868. (org-back-to-heading)
  7869. (let ((case-fold-search nil))
  7870. (looking-at org-complex-heading-regexp))
  7871. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  7872. (skip-chars-forward " \t")
  7873. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  7874. (if (org-in-commented-heading-p t)
  7875. (delete-region (point)
  7876. (progn (search-forward " " (line-end-position) 'move)
  7877. (skip-chars-forward " \t")
  7878. (point)))
  7879. (insert org-comment-string)
  7880. (unless (eolp) (insert " ")))))
  7881. (defvar org-last-todo-state-is-todo nil
  7882. "This is non-nil when the last TODO state change led to a TODO state.
  7883. If the last change removed the TODO tag or switched to DONE, then
  7884. this is nil.")
  7885. (defvar org-todo-setup-filter-hook nil
  7886. "Hook for functions that pre-filter todo specs.
  7887. Each function takes a todo spec and returns either nil or the spec
  7888. transformed into canonical form." )
  7889. (defvar org-todo-get-default-hook nil
  7890. "Hook for functions that get a default item for todo.
  7891. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  7892. nil or a string to be used for the todo mark." )
  7893. (defvar org-agenda-headline-snapshot-before-repeat)
  7894. (defun org-current-effective-time ()
  7895. "Return current time adjusted for `org-extend-today-until' variable."
  7896. (let* ((ct (org-current-time))
  7897. (dct (decode-time ct))
  7898. (ct1
  7899. (cond
  7900. (org-use-last-clock-out-time-as-effective-time
  7901. (or (org-clock-get-last-clock-out-time) ct))
  7902. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  7903. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  7904. (t ct))))
  7905. ct1))
  7906. (defun org-todo-yesterday (&optional arg)
  7907. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  7908. (interactive "P")
  7909. (if (eq major-mode 'org-agenda-mode)
  7910. (org-agenda-todo-yesterday arg)
  7911. (let* ((org-use-effective-time t)
  7912. (hour (nth 2 (decode-time (org-current-time))))
  7913. (org-extend-today-until (1+ hour)))
  7914. (org-todo arg))))
  7915. (defvar org-block-entry-blocking ""
  7916. "First entry preventing the TODO state change.")
  7917. (defun org-cancel-repeater ()
  7918. "Cancel a repeater by setting its numeric value to zero."
  7919. (interactive)
  7920. (save-excursion
  7921. (org-back-to-heading t)
  7922. (let ((bound1 (point))
  7923. (bound0 (save-excursion (outline-next-heading) (point))))
  7924. (when (and (re-search-forward
  7925. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  7926. org-deadline-time-regexp "\\)\\|\\("
  7927. org-ts-regexp "\\)")
  7928. bound0 t)
  7929. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  7930. bound1 t))
  7931. (replace-match "0" t nil nil 1)))))
  7932. (defvar org-state)
  7933. (defvar org-blocked-by-checkboxes)
  7934. (defun org-todo (&optional arg)
  7935. "Change the TODO state of an item.
  7936. The state of an item is given by a keyword at the start of the heading,
  7937. like
  7938. *** TODO Write paper
  7939. *** DONE Call mom
  7940. The different keywords are specified in the variable `org-todo-keywords'.
  7941. By default the available states are \"TODO\" and \"DONE\". So, for this
  7942. example: when the item starts with TODO, it is changed to DONE.
  7943. When it starts with DONE, the DONE is removed. And when neither TODO nor
  7944. DONE are present, add TODO at the beginning of the heading.
  7945. You can set up single-character keys to fast-select the new state. See the
  7946. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  7947. With `\\[universal-argument]' prefix ARG, force logging the state change \
  7948. and take a
  7949. logging note.
  7950. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  7951. next set of TODO \
  7952. keywords (nextset).
  7953. Another way to achieve this is `S-C-<right>'.
  7954. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  7955. prefix, circumvent any state blocking.
  7956. With numeric prefix arg, switch to the Nth state.
  7957. With a numeric prefix arg of 0, inhibit note taking for the change.
  7958. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  7959. When called through ELisp, arg is also interpreted in the following way:
  7960. `none' -> empty state
  7961. \"\" -> switch to empty state
  7962. `done' -> switch to DONE
  7963. `nextset' -> switch to the next set of keywords
  7964. `previousset' -> switch to the previous set of keywords
  7965. \"WAITING\" -> switch to the specified keyword, but only if it
  7966. really is a member of `org-todo-keywords'."
  7967. (interactive "P")
  7968. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  7969. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  7970. 'region-start-level 'region))
  7971. org-loop-over-headlines-in-active-region)
  7972. (org-map-entries
  7973. (lambda () (org-todo arg))
  7974. nil cl
  7975. (when (org-invisible-p) (org-end-of-subtree nil t))))
  7976. (when (equal arg '(16)) (setq arg 'nextset))
  7977. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  7978. (let ((org-blocker-hook org-blocker-hook)
  7979. commentp
  7980. case-fold-search)
  7981. (when (equal arg '(64))
  7982. (setq arg nil org-blocker-hook nil))
  7983. (when (and org-blocker-hook
  7984. (or org-inhibit-blocking
  7985. (org-entry-get nil "NOBLOCKING")))
  7986. (setq org-blocker-hook nil))
  7987. (save-excursion
  7988. (catch 'exit
  7989. (org-back-to-heading t)
  7990. (when (org-in-commented-heading-p t)
  7991. (org-toggle-comment)
  7992. (setq commentp t))
  7993. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  7994. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  7995. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  7996. (let* ((match-data (match-data))
  7997. (startpos (copy-marker (line-beginning-position)))
  7998. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  7999. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8000. (org-log-done org-log-done)
  8001. (org-log-repeat org-log-repeat)
  8002. (org-todo-log-states org-todo-log-states)
  8003. (org-inhibit-logging
  8004. (if (equal arg 0)
  8005. (progn (setq arg nil) 'note) org-inhibit-logging))
  8006. (this (match-string 1))
  8007. (hl-pos (match-beginning 0))
  8008. (head (org-get-todo-sequence-head this))
  8009. (ass (assoc head org-todo-kwd-alist))
  8010. (interpret (nth 1 ass))
  8011. (done-word (nth 3 ass))
  8012. (final-done-word (nth 4 ass))
  8013. (org-last-state (or this ""))
  8014. (completion-ignore-case t)
  8015. (member (member this org-todo-keywords-1))
  8016. (tail (cdr member))
  8017. (org-state (cond
  8018. ((eq arg 'right)
  8019. ;; Next state
  8020. (if this
  8021. (if tail (car tail) nil)
  8022. (car org-todo-keywords-1)))
  8023. ((eq arg 'left)
  8024. ;; Previous state
  8025. (unless (equal member org-todo-keywords-1)
  8026. (if this
  8027. (nth (- (length org-todo-keywords-1)
  8028. (length tail) 2)
  8029. org-todo-keywords-1)
  8030. (org-last org-todo-keywords-1))))
  8031. (arg
  8032. ;; User or caller requests a specific state.
  8033. (cond
  8034. ((equal arg "") nil)
  8035. ((eq arg 'none) nil)
  8036. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8037. ((eq arg 'nextset)
  8038. (or (car (cdr (member head org-todo-heads)))
  8039. (car org-todo-heads)))
  8040. ((eq arg 'previousset)
  8041. (let ((org-todo-heads (reverse org-todo-heads)))
  8042. (or (car (cdr (member head org-todo-heads)))
  8043. (car org-todo-heads))))
  8044. ((car (member arg org-todo-keywords-1)))
  8045. ((stringp arg)
  8046. (user-error "State `%s' not valid in this file" arg))
  8047. ((nth (1- (prefix-numeric-value arg))
  8048. org-todo-keywords-1))))
  8049. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8050. ;; Use fast selection.
  8051. (org-fast-todo-selection this))
  8052. ((null member) (or head (car org-todo-keywords-1)))
  8053. ((equal this final-done-word) nil) ;-> make empty
  8054. ((null tail) nil) ;-> first entry
  8055. ((memq interpret '(type priority))
  8056. (if (eq this-command last-command)
  8057. (car tail)
  8058. (if (> (length tail) 0)
  8059. (or done-word (car org-done-keywords))
  8060. nil)))
  8061. (t
  8062. (car tail))))
  8063. (org-state (or
  8064. (run-hook-with-args-until-success
  8065. 'org-todo-get-default-hook org-state org-last-state)
  8066. org-state))
  8067. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8068. (change-plist (list :type 'todo-state-change :from this :to org-state
  8069. :position startpos))
  8070. dolog now-done-p)
  8071. (when org-blocker-hook
  8072. (let (org-blocked-by-checkboxes block-reason)
  8073. (setq org-last-todo-state-is-todo
  8074. (not (member this org-done-keywords)))
  8075. (unless (save-excursion
  8076. (save-match-data
  8077. (org-with-wide-buffer
  8078. (run-hook-with-args-until-failure
  8079. 'org-blocker-hook change-plist))))
  8080. (setq block-reason (if org-blocked-by-checkboxes
  8081. "contained checkboxes"
  8082. (format "\"%s\"" org-block-entry-blocking)))
  8083. (if (called-interactively-p 'interactive)
  8084. (user-error "TODO state change from %s to %s blocked (by %s)"
  8085. this org-state block-reason)
  8086. ;; Fail silently.
  8087. (message "TODO state change from %s to %s blocked (by %s)"
  8088. this org-state block-reason)
  8089. (throw 'exit nil)))))
  8090. (store-match-data match-data)
  8091. (org-fold-core-ignore-modifications
  8092. (goto-char (match-beginning 0))
  8093. (replace-match "")
  8094. ;; We need to use `insert-before-markers-and-inherit'
  8095. ;; because: (1) We want to preserve the folding state
  8096. ;; text properties; (2) We do not want to make point
  8097. ;; move before new todo state when inserting a new todo
  8098. ;; into an empty heading. In (2), the above
  8099. ;; `save-excursion' is relying on markers saved before.
  8100. (insert-before-markers-and-inherit next)
  8101. (unless (org-invisible-p (line-beginning-position))
  8102. (org-fold-region (line-beginning-position)
  8103. (line-end-position)
  8104. nil)))
  8105. (cond ((and org-state (equal this org-state))
  8106. (message "TODO state was already %s" (org-trim next)))
  8107. ((not (pos-visible-in-window-p hl-pos))
  8108. (message "TODO state changed to %s" (org-trim next))))
  8109. (unless head
  8110. (setq head (org-get-todo-sequence-head org-state)
  8111. ass (assoc head org-todo-kwd-alist)
  8112. interpret (nth 1 ass)
  8113. done-word (nth 3 ass)
  8114. final-done-word (nth 4 ass)))
  8115. (when (memq arg '(nextset previousset))
  8116. (message "Keyword-Set %d/%d: %s"
  8117. (- (length org-todo-sets) -1
  8118. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8119. (length org-todo-sets)
  8120. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8121. (setq org-last-todo-state-is-todo
  8122. (not (member org-state org-done-keywords)))
  8123. (setq now-done-p (and (member org-state org-done-keywords)
  8124. (not (member this org-done-keywords))))
  8125. (and logging (org-local-logging logging))
  8126. (when (or (and (or org-todo-log-states org-log-done)
  8127. (not (eq org-inhibit-logging t))
  8128. (not (memq arg '(nextset previousset))))
  8129. force-log)
  8130. ;; We need to look at recording a time and note.
  8131. (setq dolog (or (if force-log 'note)
  8132. (nth 1 (assoc org-state org-todo-log-states))
  8133. (nth 2 (assoc this org-todo-log-states))))
  8134. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8135. (setq dolog 'time))
  8136. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8137. (and org-state
  8138. (member org-state org-not-done-keywords)
  8139. (not (member this org-not-done-keywords))))
  8140. ;; This is now a todo state and was not one before
  8141. ;; If there was a CLOSED time stamp, get rid of it.
  8142. (org-add-planning-info nil nil 'closed))
  8143. (when (and now-done-p org-log-done)
  8144. ;; It is now done, and it was not done before.
  8145. (org-add-planning-info 'closed (org-current-effective-time))
  8146. (when (and (not dolog) (eq 'note org-log-done))
  8147. (org-add-log-setup 'done org-state this 'note)))
  8148. (when (and org-state dolog)
  8149. ;; This is a non-nil state, and we need to log it.
  8150. (org-add-log-setup 'state org-state this dolog)))
  8151. ;; Fixup tag positioning.
  8152. (org-todo-trigger-tag-changes org-state)
  8153. (when org-auto-align-tags (org-align-tags))
  8154. (when org-provide-todo-statistics
  8155. (org-update-parent-todo-statistics))
  8156. (when (bound-and-true-p org-clock-out-when-done)
  8157. (org-clock-out-if-current))
  8158. (run-hooks 'org-after-todo-state-change-hook)
  8159. (when (and arg (not (member org-state org-done-keywords)))
  8160. (setq head (org-get-todo-sequence-head org-state)))
  8161. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8162. ;; Do we need to trigger a repeat?
  8163. (when now-done-p
  8164. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8165. ;; This is for the agenda, take a snapshot of the headline.
  8166. (save-match-data
  8167. (setq org-agenda-headline-snapshot-before-repeat
  8168. (org-get-heading))))
  8169. (org-auto-repeat-maybe org-state))
  8170. ;; Fixup cursor location if close to the keyword.
  8171. (when (and (outline-on-heading-p)
  8172. (not (bolp))
  8173. (save-excursion (beginning-of-line 1)
  8174. (looking-at org-todo-line-regexp))
  8175. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8176. (goto-char (or (match-end 2) (match-end 1)))
  8177. (and (looking-at " ")
  8178. (not (looking-at " *:"))
  8179. (just-one-space)))
  8180. (when org-trigger-hook
  8181. (save-excursion
  8182. (run-hook-with-args 'org-trigger-hook change-plist)))
  8183. (when commentp (org-toggle-comment))))))))
  8184. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8185. "Block turning an entry into a TODO, using the hierarchy.
  8186. This checks whether the current task should be blocked from state
  8187. changes. Such blocking occurs when:
  8188. 1. The task has children which are not all in a completed state.
  8189. 2. A task has a parent with the property :ORDERED:, and there
  8190. are siblings prior to the current task with incomplete
  8191. status.
  8192. 3. The parent of the task is blocked because it has siblings that should
  8193. be done first, or is child of a block grandparent TODO entry."
  8194. (if (not org-enforce-todo-dependencies)
  8195. t ; if locally turned off don't block
  8196. (catch 'dont-block
  8197. ;; If this is not a todo state change, or if this entry is already DONE,
  8198. ;; do not block
  8199. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8200. (member (plist-get change-plist :from)
  8201. (cons 'done org-done-keywords))
  8202. (member (plist-get change-plist :to)
  8203. (cons 'todo org-not-done-keywords))
  8204. (not (plist-get change-plist :to)))
  8205. (throw 'dont-block t))
  8206. ;; If this task has children, and any are undone, it's blocked
  8207. (save-excursion
  8208. (org-back-to-heading t)
  8209. (let ((this-level (funcall outline-level)))
  8210. (outline-next-heading)
  8211. (let ((child-level (funcall outline-level)))
  8212. (while (and (not (eobp))
  8213. (> child-level this-level))
  8214. ;; this todo has children, check whether they are all
  8215. ;; completed
  8216. (when (and (not (org-entry-is-done-p))
  8217. (org-entry-is-todo-p))
  8218. (setq org-block-entry-blocking (org-get-heading))
  8219. (throw 'dont-block nil))
  8220. (outline-next-heading)
  8221. (setq child-level (funcall outline-level))))))
  8222. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8223. ;; any previous siblings are undone, it's blocked
  8224. (save-excursion
  8225. (org-back-to-heading t)
  8226. (let* ((pos (point))
  8227. (parent-pos (and (org-up-heading-safe) (point)))
  8228. (case-fold-search nil))
  8229. (unless parent-pos (throw 'dont-block t)) ; no parent
  8230. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8231. (forward-line 1)
  8232. (re-search-forward org-not-done-heading-regexp pos t))
  8233. (setq org-block-entry-blocking (match-string 0))
  8234. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8235. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8236. (while t
  8237. (goto-char parent-pos)
  8238. (unless (looking-at org-not-done-heading-regexp)
  8239. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8240. (setq pos (point))
  8241. (setq parent-pos (and (org-up-heading-safe) (point)))
  8242. (unless parent-pos (throw 'dont-block t)) ; no parent
  8243. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8244. (forward-line 1)
  8245. (re-search-forward org-not-done-heading-regexp pos t)
  8246. (setq org-block-entry-blocking (org-get-heading)))
  8247. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8248. (defcustom org-track-ordered-property-with-tag nil
  8249. "Should the ORDERED property also be shown as a tag?
  8250. The ORDERED property decides if an entry should require subtasks to be
  8251. completed in sequence. Since a property is not very visible, setting
  8252. this option means that toggling the ORDERED property with the command
  8253. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8254. not relevant for the behavior, but it makes things more visible.
  8255. Note that toggling the tag with tags commands will not change the property
  8256. and therefore not influence behavior!
  8257. This can be t, meaning the tag ORDERED should be used. It can also be a
  8258. string to select a different tag for this task."
  8259. :group 'org-todo
  8260. :type '(choice
  8261. (const :tag "No tracking" nil)
  8262. (const :tag "Track with ORDERED tag" t)
  8263. (string :tag "Use other tag")))
  8264. (defun org-toggle-ordered-property ()
  8265. "Toggle the ORDERED property of the current entry.
  8266. For better visibility, you can track the value of this property with a tag.
  8267. See variable `org-track-ordered-property-with-tag'."
  8268. (interactive)
  8269. (let* ((t1 org-track-ordered-property-with-tag)
  8270. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  8271. (save-excursion
  8272. (org-back-to-heading)
  8273. (if (org-entry-get nil "ORDERED")
  8274. (progn
  8275. (org-delete-property "ORDERED")
  8276. (and tag (org-toggle-tag tag 'off))
  8277. (message "Subtasks can be completed in arbitrary order"))
  8278. (org-entry-put nil "ORDERED" "t")
  8279. (and tag (org-toggle-tag tag 'on))
  8280. (message "Subtasks must be completed in sequence")))))
  8281. (defun org-block-todo-from-checkboxes (change-plist)
  8282. "Block turning an entry into a TODO, using checkboxes.
  8283. This checks whether the current task should be blocked from state
  8284. changes because there are unchecked boxes in this entry."
  8285. (if (not org-enforce-todo-checkbox-dependencies)
  8286. t ; if locally turned off don't block
  8287. (catch 'dont-block
  8288. ;; If this is not a todo state change, or if this entry is already DONE,
  8289. ;; do not block
  8290. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8291. (member (plist-get change-plist :from)
  8292. (cons 'done org-done-keywords))
  8293. (member (plist-get change-plist :to)
  8294. (cons 'todo org-not-done-keywords))
  8295. (not (plist-get change-plist :to)))
  8296. (throw 'dont-block t))
  8297. ;; If this task has checkboxes that are not checked, it's blocked
  8298. (save-excursion
  8299. (org-back-to-heading t)
  8300. (let ((beg (point)) end)
  8301. (outline-next-heading)
  8302. (setq end (point))
  8303. (goto-char beg)
  8304. (when (org-list-search-forward
  8305. (concat (org-item-beginning-re)
  8306. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  8307. "\\[[- ]\\]")
  8308. end t)
  8309. (when (boundp 'org-blocked-by-checkboxes)
  8310. (setq org-blocked-by-checkboxes t))
  8311. (throw 'dont-block nil))))
  8312. t))) ; do not block
  8313. (defun org-entry-blocked-p ()
  8314. "Non-nil if entry at point is blocked."
  8315. (and (not (org-entry-get nil "NOBLOCKING"))
  8316. (member (org-entry-get nil "TODO") org-not-done-keywords)
  8317. (not (run-hook-with-args-until-failure
  8318. 'org-blocker-hook
  8319. (list :type 'todo-state-change
  8320. :position (point)
  8321. :from 'todo
  8322. :to 'done)))))
  8323. (defun org-update-statistics-cookies (all)
  8324. "Update the statistics cookie, either from TODO or from checkboxes.
  8325. This should be called with the cursor in a line with a statistics
  8326. cookie. When called with a \\[universal-argument] prefix, update
  8327. all statistics cookies in the buffer."
  8328. (interactive "P")
  8329. (if all
  8330. (progn
  8331. (org-update-checkbox-count 'all)
  8332. (org-map-region 'org-update-parent-todo-statistics
  8333. (point-min) (point-max)))
  8334. (if (not (org-at-heading-p))
  8335. (org-update-checkbox-count)
  8336. (let ((pos (point-marker))
  8337. end l1 l2)
  8338. (ignore-errors (org-back-to-heading t))
  8339. (if (not (org-at-heading-p))
  8340. (org-update-checkbox-count)
  8341. (setq l1 (org-outline-level))
  8342. (setq end
  8343. (save-excursion
  8344. (outline-next-heading)
  8345. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  8346. (point)))
  8347. (if (and (save-excursion
  8348. (re-search-forward
  8349. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  8350. (not (save-excursion
  8351. (re-search-forward
  8352. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  8353. (org-update-checkbox-count)
  8354. (if (and l2 (> l2 l1))
  8355. (progn
  8356. (goto-char end)
  8357. (org-update-parent-todo-statistics))
  8358. (goto-char pos)
  8359. (beginning-of-line 1)
  8360. (while (re-search-forward
  8361. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  8362. (point-at-eol) t)
  8363. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  8364. (goto-char pos)
  8365. (move-marker pos nil)))))
  8366. (defvar org-entry-property-inherited-from) ;; defined below
  8367. (defun org-update-parent-todo-statistics ()
  8368. "Update any statistics cookie in the parent of the current headline.
  8369. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  8370. the entire subtree and this will travel up the hierarchy and update
  8371. statistics everywhere."
  8372. (let* ((prop (save-excursion
  8373. (org-up-heading-safe)
  8374. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  8375. (recursive (or (not org-hierarchical-todo-statistics)
  8376. (and prop (string-match "\\<recursive\\>" prop))))
  8377. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  8378. 0))
  8379. (first t)
  8380. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  8381. level ltoggle l1 new ndel
  8382. (cnt-all 0) (cnt-done 0) is-percent kwd
  8383. checkbox-beg cookie-present)
  8384. (catch 'exit
  8385. (save-excursion
  8386. (beginning-of-line 1)
  8387. (setq ltoggle (funcall outline-level))
  8388. ;; Three situations are to consider:
  8389. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  8390. ;; to the top-level ancestor on the headline;
  8391. ;; 2. If parent has "recursive" property, repeat up to the
  8392. ;; headline setting that property, taking inheritance into
  8393. ;; account;
  8394. ;; 3. Else, move up to direct parent and proceed only once.
  8395. (while (and (setq level (org-up-heading-safe))
  8396. (or recursive first)
  8397. (>= (point) lim))
  8398. (setq first nil cookie-present nil)
  8399. (unless (and level
  8400. (not (string-match
  8401. "\\<checkbox\\>"
  8402. (downcase (or (org-entry-get nil "COOKIE_DATA")
  8403. "")))))
  8404. (throw 'exit nil))
  8405. (while (re-search-forward box-re (point-at-eol) t)
  8406. (setq cnt-all 0 cnt-done 0 cookie-present t)
  8407. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  8408. (save-match-data
  8409. (unless (outline-next-heading) (throw 'exit nil))
  8410. (while (and (looking-at org-complex-heading-regexp)
  8411. (> (setq l1 (length (match-string 1))) level))
  8412. (setq kwd (and (or recursive (= l1 ltoggle))
  8413. (match-string 2)))
  8414. (if (or (eq org-provide-todo-statistics 'all-headlines)
  8415. (and (eq org-provide-todo-statistics t)
  8416. (or (member kwd org-done-keywords)))
  8417. (and (listp org-provide-todo-statistics)
  8418. (stringp (car org-provide-todo-statistics))
  8419. (or (member kwd org-provide-todo-statistics)
  8420. (member kwd org-done-keywords)))
  8421. (and (listp org-provide-todo-statistics)
  8422. (listp (car org-provide-todo-statistics))
  8423. (or (member kwd (car org-provide-todo-statistics))
  8424. (and (member kwd org-done-keywords)
  8425. (member kwd (cadr org-provide-todo-statistics))))))
  8426. (setq cnt-all (1+ cnt-all))
  8427. (and (eq org-provide-todo-statistics t)
  8428. kwd
  8429. (setq cnt-all (1+ cnt-all))))
  8430. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  8431. (member kwd org-done-keywords))
  8432. (and (listp org-provide-todo-statistics)
  8433. (listp (car org-provide-todo-statistics))
  8434. (member kwd org-done-keywords)
  8435. (member kwd (cadr org-provide-todo-statistics)))
  8436. (and (listp org-provide-todo-statistics)
  8437. (stringp (car org-provide-todo-statistics))
  8438. (member kwd org-done-keywords)))
  8439. (setq cnt-done (1+ cnt-done)))
  8440. (outline-next-heading)))
  8441. (setq new
  8442. (if is-percent
  8443. (format "[%d%%]" (floor (* 100.0 cnt-done)
  8444. (max 1 cnt-all)))
  8445. (format "[%d/%d]" cnt-done cnt-all))
  8446. ndel (- (match-end 0) checkbox-beg))
  8447. (goto-char checkbox-beg)
  8448. (insert new)
  8449. (delete-region (point) (+ (point) ndel))
  8450. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  8451. (when cookie-present
  8452. (run-hook-with-args 'org-after-todo-statistics-hook
  8453. cnt-done (- cnt-all cnt-done))))))
  8454. (run-hooks 'org-todo-statistics-hook)))
  8455. (defvar org-after-todo-statistics-hook nil
  8456. "Hook that is called after a TODO statistics cookie has been updated.
  8457. Each function is called with two arguments: the number of not-done entries
  8458. and the number of done entries.
  8459. For example, the following function, when added to this hook, will switch
  8460. an entry to DONE when all children are done, and back to TODO when new
  8461. entries are set to a TODO status. Note that this hook is only called
  8462. when there is a statistics cookie in the headline!
  8463. (defun org-summary-todo (n-done n-not-done)
  8464. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  8465. (let (org-log-done org-log-states) ; turn off logging
  8466. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  8467. (defvar org-todo-statistics-hook nil
  8468. "Hook that is run whenever Org thinks TODO statistics should be updated.
  8469. This hook runs even if there is no statistics cookie present, in which case
  8470. `org-after-todo-statistics-hook' would not run.")
  8471. (defun org-todo-trigger-tag-changes (state)
  8472. "Apply the changes defined in `org-todo-state-tags-triggers'."
  8473. (let ((l org-todo-state-tags-triggers)
  8474. changes)
  8475. (when (or (not state) (equal state ""))
  8476. (setq changes (append changes (cdr (assoc "" l)))))
  8477. (when (and (stringp state) (> (length state) 0))
  8478. (setq changes (append changes (cdr (assoc state l)))))
  8479. (when (member state org-not-done-keywords)
  8480. (setq changes (append changes (cdr (assq 'todo l)))))
  8481. (when (member state org-done-keywords)
  8482. (setq changes (append changes (cdr (assq 'done l)))))
  8483. (dolist (c changes)
  8484. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  8485. (defun org-local-logging (value)
  8486. "Get logging settings from a property VALUE."
  8487. ;; Directly set the variables, they are already local.
  8488. (setq org-log-done nil
  8489. org-log-repeat nil
  8490. org-todo-log-states nil)
  8491. (dolist (w (split-string value))
  8492. (let (a)
  8493. (cond
  8494. ((setq a (assoc w org-startup-options))
  8495. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  8496. (set (nth 1 a) (nth 2 a))))
  8497. ((setq a (org-extract-log-state-settings w))
  8498. (and (member (car a) org-todo-keywords-1)
  8499. (push a org-todo-log-states)))))))
  8500. (defun org-get-todo-sequence-head (kwd)
  8501. "Return the head of the TODO sequence to which KWD belongs.
  8502. If KWD is not set, check if there is a text property remembering the
  8503. right sequence."
  8504. (let (p)
  8505. (cond
  8506. ((not kwd)
  8507. (or (get-text-property (point-at-bol) 'org-todo-head)
  8508. (progn
  8509. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  8510. nil (point-at-eol)))
  8511. (get-text-property p 'org-todo-head))))
  8512. ((not (member kwd org-todo-keywords-1))
  8513. (car org-todo-keywords-1))
  8514. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  8515. (defun org-fast-todo-selection (&optional current-state)
  8516. "Fast TODO keyword selection with single keys.
  8517. Returns the new TODO keyword, or nil if no state change should occur.
  8518. When CURRENT-STATE is given and selection letters are not unique globally,
  8519. prefer a state in the current sequence over on in another sequence."
  8520. (let* ((fulltable org-todo-key-alist)
  8521. (head (org-get-todo-sequence-head current-state))
  8522. (done-keywords org-done-keywords) ;; needed for the faces.
  8523. (maxlen (apply 'max (mapcar
  8524. (lambda (x)
  8525. (if (stringp (car x)) (string-width (car x)) 0))
  8526. fulltable)))
  8527. (expert (equal org-use-fast-todo-selection 'expert))
  8528. (prompt "")
  8529. (fwidth (+ maxlen 3 1 3))
  8530. (ncol (/ (- (window-width) 4) fwidth))
  8531. tg cnt e c tbl subtable
  8532. groups ingroup in-current-sequence)
  8533. (save-excursion
  8534. (save-window-excursion
  8535. (if expert
  8536. (set-buffer (get-buffer-create " *Org todo*"))
  8537. (delete-other-windows)
  8538. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  8539. (org-switch-to-buffer-other-window " *Org todo*"))
  8540. (erase-buffer)
  8541. (setq-local org-done-keywords done-keywords)
  8542. (setq tbl fulltable cnt 0)
  8543. (while (setq e (pop tbl))
  8544. (cond
  8545. ((equal e '(:startgroup))
  8546. (push '() groups) (setq ingroup t)
  8547. (unless (= cnt 0)
  8548. (setq cnt 0)
  8549. (insert "\n"))
  8550. (setq prompt (concat prompt "{"))
  8551. (insert "{ "))
  8552. ((equal e '(:endgroup))
  8553. (setq ingroup nil cnt 0 in-current-sequence nil)
  8554. (setq prompt (concat prompt "}"))
  8555. (insert "}\n"))
  8556. ((equal e '(:newline))
  8557. (unless (= cnt 0)
  8558. (setq cnt 0)
  8559. (insert "\n")
  8560. (setq e (car tbl))
  8561. (while (equal (car tbl) '(:newline))
  8562. (insert "\n")
  8563. (setq tbl (cdr tbl)))))
  8564. (t
  8565. (setq tg (car e) c (cdr e))
  8566. (if (equal tg head) (setq in-current-sequence t))
  8567. (when ingroup (push tg (car groups)))
  8568. (when in-current-sequence (push e subtable))
  8569. (setq tg (org-add-props tg nil 'face
  8570. (org-get-todo-face tg)))
  8571. (when (and (= cnt 0) (not ingroup)) (insert " "))
  8572. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  8573. (insert "[" c "] " tg (make-string
  8574. (- fwidth 4 (length tg)) ?\ ))
  8575. (when (and (= (setq cnt (1+ cnt)) ncol)
  8576. ;; Avoid lines with just a closing delimiter.
  8577. (not (equal (car tbl) '(:endgroup))))
  8578. (insert "\n")
  8579. (when ingroup (insert " "))
  8580. (setq cnt 0)))))
  8581. (insert "\n")
  8582. (goto-char (point-min))
  8583. (unless expert (org-fit-window-to-buffer))
  8584. (message (concat "[a-z..]:Set [SPC]:clear"
  8585. (if expert (concat "\n" prompt) "")))
  8586. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  8587. (setq subtable (nreverse subtable))
  8588. (cond
  8589. ((or (= c ?\C-g)
  8590. (and (= c ?q) (not (rassoc c fulltable))))
  8591. (setq quit-flag t))
  8592. ((= c ?\ ) nil)
  8593. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  8594. tg (car e))
  8595. tg)
  8596. (t (setq quit-flag t)))))))
  8597. (defun org-entry-is-todo-p ()
  8598. (member (org-get-todo-state) org-not-done-keywords))
  8599. (defun org-entry-is-done-p ()
  8600. (member (org-get-todo-state) org-done-keywords))
  8601. (defun org-get-todo-state ()
  8602. "Return the TODO keyword of the current subtree."
  8603. (save-excursion
  8604. (org-back-to-heading t)
  8605. (and (let ((case-fold-search nil))
  8606. (looking-at org-todo-line-regexp))
  8607. (match-end 2)
  8608. (match-string 2))))
  8609. (defun org-at-date-range-p (&optional inactive-ok)
  8610. "Non-nil if point is inside a date range.
  8611. When optional argument INACTIVE-OK is non-nil, also consider
  8612. inactive time ranges.
  8613. When this function returns a non-nil value, match data is set
  8614. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  8615. on INACTIVE-OK."
  8616. (interactive)
  8617. (save-excursion
  8618. (catch 'exit
  8619. (let ((pos (point)))
  8620. (skip-chars-backward "^[<\r\n")
  8621. (skip-chars-backward "<[")
  8622. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8623. (>= (match-end 0) pos)
  8624. (throw 'exit t))
  8625. (skip-chars-backward "^<[\r\n")
  8626. (skip-chars-backward "<[")
  8627. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  8628. (>= (match-end 0) pos)
  8629. (throw 'exit t)))
  8630. nil)))
  8631. (defun org-get-repeat (&optional timestamp)
  8632. "Check if there is a time-stamp with repeater in this entry.
  8633. Return the repeater, as a string, or nil. Also return nil when
  8634. this function is called before first heading.
  8635. When optional argument TIMESTAMP is a string, extract the
  8636. repeater from there instead."
  8637. (save-match-data
  8638. (cond
  8639. (timestamp
  8640. (and (string-match org-repeat-re timestamp)
  8641. (match-string-no-properties 1 timestamp)))
  8642. ((org-before-first-heading-p) nil)
  8643. (t
  8644. (save-excursion
  8645. (org-back-to-heading t)
  8646. (let ((end (org-entry-end-position)))
  8647. (catch :repeat
  8648. (while (re-search-forward org-repeat-re end t)
  8649. (when (save-match-data (org-at-timestamp-p 'agenda))
  8650. (throw :repeat (match-string-no-properties 1)))))))))))
  8651. (defvar org-last-changed-timestamp)
  8652. (defvar org-last-inserted-timestamp)
  8653. (defvar org-log-post-message)
  8654. (defvar org-log-note-purpose)
  8655. (defvar org-log-note-how nil)
  8656. (defvar org-log-note-extra)
  8657. (defvar org-log-setup nil)
  8658. (defun org-auto-repeat-maybe (done-word)
  8659. "Check if the current headline contains a repeated time-stamp.
  8660. If yes, set TODO state back to what it was and change the base date
  8661. of repeating deadline/scheduled time stamps to new date.
  8662. This function is run automatically after each state change to a DONE state."
  8663. (let* ((repeat (org-get-repeat))
  8664. (aa (assoc org-last-state org-todo-kwd-alist))
  8665. (interpret (nth 1 aa))
  8666. (head (nth 2 aa))
  8667. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  8668. (msg "Entry repeats: ")
  8669. (org-log-done nil)
  8670. (org-todo-log-states nil)
  8671. (end (copy-marker (org-entry-end-position))))
  8672. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  8673. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  8674. (let ((to-state
  8675. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  8676. (and (stringp org-todo-repeat-to-state)
  8677. org-todo-repeat-to-state)
  8678. (and org-todo-repeat-to-state org-last-state))))
  8679. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  8680. to-state)
  8681. ((eq interpret 'type) org-last-state)
  8682. (head)
  8683. (t 'none))))
  8684. (org-back-to-heading t)
  8685. (org-add-planning-info nil nil 'closed)
  8686. ;; When `org-log-repeat' is non-nil or entry contains
  8687. ;; a clock, set LAST_REPEAT property.
  8688. (when (or org-log-repeat
  8689. (catch :clock
  8690. (save-excursion
  8691. (while (re-search-forward org-clock-line-re end t)
  8692. (when (org-at-clock-log-p) (throw :clock t))))))
  8693. (org-entry-put nil "LAST_REPEAT" (format-time-string
  8694. (org-time-stamp-format t t))))
  8695. (when org-log-repeat
  8696. (if org-log-setup
  8697. ;; We are already setup for some record.
  8698. (when (eq org-log-repeat 'note)
  8699. ;; Make sure we take a note, not only a time stamp.
  8700. (setq org-log-note-how 'note))
  8701. ;; Set up for taking a record.
  8702. (org-add-log-setup 'state
  8703. (or done-word (car org-done-keywords))
  8704. org-last-state
  8705. org-log-repeat)))
  8706. ;; Time-stamps without a repeater are usually skipped. However,
  8707. ;; a SCHEDULED time-stamp without one is removed, as they are no
  8708. ;; longer relevant.
  8709. (save-excursion
  8710. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  8711. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  8712. (org-remove-timestamp-with-keyword org-scheduled-string))))
  8713. ;; Update every time-stamp with a repeater in the entry.
  8714. (let ((planning-re (regexp-opt
  8715. (list org-scheduled-string org-deadline-string))))
  8716. (while (re-search-forward org-repeat-re end t)
  8717. (let* ((ts (match-string 0))
  8718. (type (if (not (org-at-planning-p)) "Plain:"
  8719. (save-excursion
  8720. (re-search-backward
  8721. planning-re (line-beginning-position) t)
  8722. (match-string 0)))))
  8723. (when (and (org-at-timestamp-p 'agenda)
  8724. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  8725. (let ((n (string-to-number (match-string 2 ts)))
  8726. (what (match-string 3 ts)))
  8727. (when (equal what "w") (setq n (* n 7) what "d"))
  8728. (when (and (equal what "h")
  8729. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  8730. ts)))
  8731. (user-error
  8732. "Cannot repeat in %d hour(s) because no hour has been set"
  8733. n))
  8734. ;; Preparation, see if we need to modify the start
  8735. ;; date for the change.
  8736. (when (match-end 1)
  8737. (let ((time (save-match-data (org-time-string-to-time ts)))
  8738. (repeater-type (match-string 1 ts)))
  8739. (cond
  8740. ((equal "." repeater-type)
  8741. ;; Shift starting date to today, or now if
  8742. ;; repeater is by hours.
  8743. (if (equal what "h")
  8744. (org-timestamp-change
  8745. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  8746. (org-timestamp-change
  8747. (- (org-today) (time-to-days time)) 'day)))
  8748. ((equal "+" repeater-type)
  8749. (let ((nshiftmax 10)
  8750. (nshift 0))
  8751. (while (or (= nshift 0)
  8752. (not (time-less-p nil time)))
  8753. (when (= nshiftmax (cl-incf nshift))
  8754. (or (y-or-n-p
  8755. (format "%d repeater intervals were not \
  8756. enough to shift date past today. Continue? "
  8757. nshift))
  8758. (user-error "Abort")))
  8759. (org-timestamp-change n (cdr (assoc what whata)))
  8760. (org-in-regexp org-ts-regexp3)
  8761. (setq ts (match-string 1))
  8762. (setq time
  8763. (save-match-data
  8764. (org-time-string-to-time ts)))))
  8765. (org-timestamp-change (- n) (cdr (assoc what whata)))
  8766. ;; Rematch, so that we have everything in place
  8767. ;; for the real shift.
  8768. (org-in-regexp org-ts-regexp3)
  8769. (setq ts (match-string 1))
  8770. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  8771. ts)))))
  8772. (save-excursion
  8773. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  8774. (setq msg
  8775. (concat msg type " " org-last-changed-timestamp " ")))))))
  8776. (run-hooks 'org-todo-repeat-hook)
  8777. (setq org-log-post-message msg)
  8778. (message msg))))
  8779. (defun org-show-todo-tree (arg)
  8780. "Make a compact tree which shows all headlines marked with TODO.
  8781. The tree will show the lines where the regexp matches, and all higher
  8782. headlines above the match.
  8783. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  8784. With a numeric prefix N, construct a sparse tree for the Nth element
  8785. of `org-todo-keywords-1'."
  8786. (interactive "P")
  8787. (let ((case-fold-search nil)
  8788. (kwd-re
  8789. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  8790. ((equal arg '(4))
  8791. (let ((kwd
  8792. (completing-read "Keyword (or KWD1|KWD2|...): "
  8793. (mapcar #'list org-todo-keywords-1))))
  8794. (concat "\\("
  8795. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  8796. "\\)\\>")))
  8797. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  8798. (regexp-quote (nth (1- (prefix-numeric-value arg))
  8799. org-todo-keywords-1)))
  8800. (t (user-error "Invalid prefix argument: %s" arg)))))
  8801. (message "%d TODO entries found"
  8802. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  8803. (defun org--deadline-or-schedule (arg type time)
  8804. "Insert DEADLINE or SCHEDULE information in current entry.
  8805. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  8806. `org-schedule' for information about ARG and TIME arguments."
  8807. (org-fold-core-ignore-modifications
  8808. (let* ((deadline? (eq type 'deadline))
  8809. (keyword (if deadline? org-deadline-string org-scheduled-string))
  8810. (log (if deadline? org-log-redeadline org-log-reschedule))
  8811. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  8812. (old-date-time (and old-date (org-time-string-to-time old-date)))
  8813. ;; Save repeater cookie from either TIME or current scheduled
  8814. ;; time stamp. We are going to insert it back at the end of
  8815. ;; the process.
  8816. (repeater (or (and (org-string-nw-p time)
  8817. ;; We use `org-ts-regexp-both' because we
  8818. ;; need to tell the difference between a
  8819. ;; real repeater and a time delta, e.g.
  8820. ;; "+2d".
  8821. (string-match-p org-ts-regexp-both time)
  8822. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8823. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8824. time)
  8825. (match-string 1 time))
  8826. (and (org-string-nw-p old-date)
  8827. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  8828. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  8829. old-date)
  8830. (match-string 1 old-date)))))
  8831. (pcase arg
  8832. (`(4)
  8833. (if (not old-date)
  8834. (message (if deadline? "Entry had no deadline to remove"
  8835. "Entry was not scheduled"))
  8836. (when (and old-date log)
  8837. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  8838. nil old-date log))
  8839. (org-remove-timestamp-with-keyword keyword)
  8840. (message (if deadline? "Entry no longer has a deadline."
  8841. "Entry is no longer scheduled."))))
  8842. (`(16)
  8843. (save-excursion
  8844. (org-back-to-heading t)
  8845. (let ((regexp (if deadline? org-deadline-time-regexp
  8846. org-scheduled-time-regexp)))
  8847. (if (not (re-search-forward regexp (line-end-position 2) t))
  8848. (user-error (if deadline? "No deadline information to update"
  8849. "No scheduled information to update"))
  8850. (let* ((rpl0 (match-string 1))
  8851. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  8852. (msg (if deadline? "Warn starting from" "Delay until")))
  8853. (replace-match
  8854. (concat keyword
  8855. " <" rpl
  8856. (format " -%dd"
  8857. (abs (- (time-to-days
  8858. (save-match-data
  8859. (org-read-date
  8860. nil t nil msg old-date-time)))
  8861. (time-to-days old-date-time))))
  8862. ">") t t))))))
  8863. (_
  8864. (org-add-planning-info type time 'closed)
  8865. (when (and old-date
  8866. log
  8867. (not (equal old-date org-last-inserted-timestamp)))
  8868. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  8869. org-last-inserted-timestamp
  8870. old-date
  8871. log))
  8872. (when repeater
  8873. (save-excursion
  8874. (org-back-to-heading t)
  8875. (when (re-search-forward
  8876. (concat keyword " " org-last-inserted-timestamp)
  8877. (line-end-position 2)
  8878. t)
  8879. (goto-char (1- (match-end 0)))
  8880. (insert-and-inherit " " repeater)
  8881. (setq org-last-inserted-timestamp
  8882. (concat (substring org-last-inserted-timestamp 0 -1)
  8883. " " repeater
  8884. (substring org-last-inserted-timestamp -1))))))
  8885. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  8886. org-last-inserted-timestamp))))))
  8887. (defun org-deadline (arg &optional time)
  8888. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  8889. When called interactively, this command pops up the Emacs calendar to let
  8890. the user select a date.
  8891. With one universal prefix argument, remove any deadline from the item.
  8892. With two universal prefix arguments, prompt for a warning delay.
  8893. With argument TIME, set the deadline at the corresponding date. TIME
  8894. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8895. (interactive "P")
  8896. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8897. (org-map-entries
  8898. (lambda () (org--deadline-or-schedule arg 'deadline time))
  8899. nil
  8900. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8901. 'region-start-level
  8902. 'region)
  8903. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8904. (org--deadline-or-schedule arg 'deadline time)))
  8905. (defun org-schedule (arg &optional time)
  8906. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  8907. When called interactively, this command pops up the Emacs calendar to let
  8908. the user select a date.
  8909. With one universal prefix argument, remove any scheduling date from the item.
  8910. With two universal prefix arguments, prompt for a delay cookie.
  8911. With argument TIME, scheduled at the corresponding date. TIME can
  8912. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  8913. (interactive "P")
  8914. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8915. (org-map-entries
  8916. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  8917. nil
  8918. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8919. 'region-start-level
  8920. 'region)
  8921. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  8922. (org--deadline-or-schedule arg 'scheduled time)))
  8923. (defun org-get-scheduled-time (pom &optional inherit)
  8924. "Get the scheduled time as a time tuple, of a format suitable
  8925. for calling org-schedule with, or if there is no scheduling,
  8926. returns nil."
  8927. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  8928. (when time
  8929. (org-time-string-to-time time))))
  8930. (defun org-get-deadline-time (pom &optional inherit)
  8931. "Get the deadline as a time tuple, of a format suitable for
  8932. calling org-deadline with, or if there is no scheduling, returns
  8933. nil."
  8934. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  8935. (when time
  8936. (org-time-string-to-time time))))
  8937. (defun org-remove-timestamp-with-keyword (keyword)
  8938. "Remove all time stamps with KEYWORD in the current entry."
  8939. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  8940. beg)
  8941. (save-excursion
  8942. (org-back-to-heading t)
  8943. (setq beg (point))
  8944. (outline-next-heading)
  8945. (while (re-search-backward re beg t)
  8946. (replace-match "")
  8947. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  8948. (equal (char-before) ?\ ))
  8949. (backward-delete-char 1)
  8950. (when (string-match "^[ \t]*$" (buffer-substring
  8951. (point-at-bol) (point-at-eol)))
  8952. (delete-region (point-at-bol)
  8953. (min (point-max) (1+ (point-at-eol))))))))))
  8954. (defvar org-time-was-given) ; dynamically scoped parameter
  8955. (defvar org-end-time-was-given) ; dynamically scoped parameter
  8956. (defun org-at-planning-p ()
  8957. "Non-nil when point is on a planning info line."
  8958. ;; This is as accurate and faster than `org-element-at-point' since
  8959. ;; planning info location is fixed in the section.
  8960. (or (let ((cached (org-element-at-point nil 'cached)))
  8961. (and cached
  8962. (eq 'planning (org-element-type cached))))
  8963. (org-with-wide-buffer
  8964. (beginning-of-line)
  8965. (and (looking-at-p org-planning-line-re)
  8966. (eq (point)
  8967. (ignore-errors
  8968. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  8969. (org-back-to-heading t)
  8970. (org-with-limited-levels (org-back-to-heading t)))
  8971. (line-beginning-position 2)))))))
  8972. (defun org-add-planning-info (what &optional time &rest remove)
  8973. "Insert new timestamp with keyword in the planning line.
  8974. WHAT indicates what kind of time stamp to add. It is a symbol
  8975. among `closed', `deadline', `scheduled' and nil. TIME indicates
  8976. the time to use. If none is given, the user is prompted for
  8977. a date. REMOVE indicates what kind of entries to remove. An old
  8978. WHAT entry will also be removed."
  8979. (org-fold-core-ignore-modifications
  8980. (let (org-time-was-given org-end-time-was-given default-time default-input)
  8981. (when (and (memq what '(scheduled deadline))
  8982. (or (not time)
  8983. (and (stringp time)
  8984. (string-match "^[-+]+[0-9]" time))))
  8985. ;; Try to get a default date/time from existing timestamp
  8986. (save-excursion
  8987. (org-back-to-heading t)
  8988. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  8989. (when (re-search-forward (if (eq what 'scheduled)
  8990. org-scheduled-time-regexp
  8991. org-deadline-time-regexp)
  8992. end t)
  8993. (setq ts (match-string 1)
  8994. default-time (org-time-string-to-time ts)
  8995. default-input (and ts (org-get-compact-tod ts)))))))
  8996. (when what
  8997. (setq time
  8998. (if (stringp time)
  8999. ;; This is a string (relative or absolute), set
  9000. ;; proper date.
  9001. (apply #'encode-time
  9002. (org-read-date-analyze
  9003. time default-time (decode-time default-time)))
  9004. ;; If necessary, get the time from the user
  9005. (or time (org-read-date nil 'to-time nil
  9006. (cl-case what
  9007. (deadline "DEADLINE")
  9008. (scheduled "SCHEDULED")
  9009. (otherwise nil))
  9010. default-time default-input)))))
  9011. (org-with-wide-buffer
  9012. (org-back-to-heading t)
  9013. (let ((planning? (save-excursion
  9014. (forward-line)
  9015. (looking-at-p org-planning-line-re))))
  9016. (cond
  9017. (planning?
  9018. (forward-line)
  9019. ;; Move to current indentation.
  9020. (skip-chars-forward " \t")
  9021. ;; Check if we have to remove something.
  9022. (dolist (type (if what (cons what remove) remove))
  9023. (save-excursion
  9024. (when (re-search-forward
  9025. (cl-case type
  9026. (closed org-closed-time-regexp)
  9027. (deadline org-deadline-time-regexp)
  9028. (scheduled org-scheduled-time-regexp)
  9029. (otherwise (error "Invalid planning type: %s" type)))
  9030. (line-end-position)
  9031. t)
  9032. ;; Delete until next keyword or end of line.
  9033. (delete-region
  9034. (match-beginning 0)
  9035. (if (re-search-forward org-keyword-time-not-clock-regexp
  9036. (line-end-position)
  9037. t)
  9038. (match-beginning 0)
  9039. (line-end-position))))))
  9040. ;; If there is nothing more to add and no more keyword is
  9041. ;; left, remove the line completely.
  9042. (if (and (looking-at-p "[ \t]*$") (not what))
  9043. (delete-region (line-end-position 0)
  9044. (line-end-position))
  9045. ;; If we removed last keyword, do not leave trailing white
  9046. ;; space at the end of line.
  9047. (let ((p (point)))
  9048. (save-excursion
  9049. (end-of-line)
  9050. (unless (= (skip-chars-backward " \t" p) 0)
  9051. (delete-region (point) (line-end-position)))))))
  9052. (what
  9053. (end-of-line)
  9054. (insert-and-inherit "\n")
  9055. (when org-adapt-indentation
  9056. (indent-to-column (1+ (org-outline-level)))))
  9057. (t nil)))
  9058. (when what
  9059. ;; Insert planning keyword.
  9060. (insert-and-inherit (cl-case what
  9061. (closed org-closed-string)
  9062. (deadline org-deadline-string)
  9063. (scheduled org-scheduled-string)
  9064. (otherwise (error "Invalid planning type: %s" what)))
  9065. " ")
  9066. ;; Insert associated timestamp.
  9067. (let ((ts (org-insert-time-stamp
  9068. time
  9069. (or org-time-was-given
  9070. (and (eq what 'closed) org-log-done-with-time))
  9071. (eq what 'closed)
  9072. nil nil (list org-end-time-was-given))))
  9073. (unless (eolp) (insert " "))
  9074. ts))))))
  9075. (defvar org-log-note-marker (make-marker)
  9076. "Marker pointing at the entry where the note is to be inserted.")
  9077. (defvar org-log-note-purpose nil)
  9078. (defvar org-log-note-state nil)
  9079. (defvar org-log-note-previous-state nil)
  9080. (defvar org-log-note-extra nil)
  9081. (defvar org-log-note-window-configuration nil)
  9082. (defvar org-log-note-return-to (make-marker))
  9083. (defvar org-log-note-effective-time nil
  9084. "Remembered current time.
  9085. So that dynamically scoped `org-extend-today-until' affects
  9086. timestamps in state change log.")
  9087. (defvar org-log-post-message nil
  9088. "Message to be displayed after a log note has been stored.
  9089. The auto-repeater uses this.")
  9090. (defun org-add-note ()
  9091. "Add a note to the current entry.
  9092. This is done in the same way as adding a state change note."
  9093. (interactive)
  9094. (org-add-log-setup 'note))
  9095. (defun org-log-beginning (&optional create)
  9096. "Return expected start of log notes in current entry.
  9097. When optional argument CREATE is non-nil, the function creates
  9098. a drawer to store notes, if necessary. Returned position ignores
  9099. narrowing."
  9100. (org-with-wide-buffer
  9101. (let ((drawer (org-log-into-drawer)))
  9102. (cond
  9103. (drawer
  9104. (org-end-of-meta-data)
  9105. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9106. (end (if (org-at-heading-p) (point)
  9107. (save-excursion (outline-next-heading) (point))))
  9108. (case-fold-search t))
  9109. (catch 'exit
  9110. ;; Try to find existing drawer.
  9111. (while (re-search-forward regexp end t)
  9112. (let ((element (org-element-at-point)))
  9113. (when (eq (org-element-type element) 'drawer)
  9114. (let ((cend (org-element-property :contents-end element)))
  9115. (when (and (not org-log-states-order-reversed) cend)
  9116. (goto-char cend)))
  9117. (throw 'exit nil))))
  9118. ;; No drawer found. Create one, if permitted.
  9119. (when create
  9120. ;; Avoid situation when we insert drawer right before
  9121. ;; first "*". Otherwise, if the previous heading is
  9122. ;; folded, we are inserting after visible newline at
  9123. ;; the end of the fold, thus breaking the fold
  9124. ;; continuity.
  9125. (when (org-at-heading-p) (backward-char))
  9126. (org-fold-core-ignore-modifications
  9127. (unless (bolp) (insert-and-inherit "\n"))
  9128. (let ((beg (point)))
  9129. (insert-and-inherit ":" drawer ":\n:END:\n")
  9130. (org-indent-region beg (point))
  9131. (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  9132. (end-of-line -1))))
  9133. (t
  9134. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9135. (skip-chars-forward " \t\n")
  9136. (beginning-of-line)
  9137. (unless org-log-states-order-reversed
  9138. (org-skip-over-state-notes)
  9139. (skip-chars-backward " \t\n")
  9140. (beginning-of-line 2)))))
  9141. (if (bolp) (point) (line-beginning-position 2))))
  9142. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9143. "Set up the post command hook to take a note.
  9144. If this is about to TODO state change, the new state is expected in STATE.
  9145. HOW is an indicator what kind of note should be created.
  9146. EXTRA is additional text that will be inserted into the notes buffer."
  9147. (move-marker org-log-note-marker (point))
  9148. (setq org-log-note-purpose purpose
  9149. org-log-note-state state
  9150. org-log-note-previous-state prev-state
  9151. org-log-note-how how
  9152. org-log-note-extra extra
  9153. org-log-note-effective-time (org-current-effective-time)
  9154. org-log-setup t)
  9155. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9156. (defun org-skip-over-state-notes ()
  9157. "Skip past the list of State notes in an entry."
  9158. (when (ignore-errors (goto-char (org-in-item-p)))
  9159. (let* ((struct (org-list-struct))
  9160. (prevs (org-list-prevs-alist struct))
  9161. (regexp
  9162. (concat "[ \t]*- +"
  9163. (replace-regexp-in-string
  9164. " +" " +"
  9165. (org-replace-escapes
  9166. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9167. `(("%d" . ,org-ts-regexp-inactive)
  9168. ("%D" . ,org-ts-regexp)
  9169. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9170. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9171. ("%t" . ,org-ts-regexp-inactive)
  9172. ("%T" . ,org-ts-regexp)
  9173. ("%u" . ".*?")
  9174. ("%U" . ".*?")))))))
  9175. (while (looking-at-p regexp)
  9176. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9177. (org-list-get-item-end (point) struct)))))))
  9178. (defun org-add-log-note (&optional _purpose)
  9179. "Pop up a window for taking a note, and add this note later."
  9180. (remove-hook 'post-command-hook 'org-add-log-note)
  9181. (setq org-log-setup nil)
  9182. (setq org-log-note-window-configuration (current-window-configuration))
  9183. (delete-other-windows)
  9184. (move-marker org-log-note-return-to (point))
  9185. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9186. (goto-char org-log-note-marker)
  9187. (org-switch-to-buffer-other-window "*Org Note*")
  9188. (erase-buffer)
  9189. (if (memq org-log-note-how '(time state))
  9190. (org-store-log-note)
  9191. (let ((org-inhibit-startup t)) (org-mode))
  9192. (insert (format "# Insert note for %s.
  9193. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9194. (cl-case org-log-note-purpose
  9195. (clock-out "stopped clock")
  9196. (done "closed todo item")
  9197. (reschedule "rescheduling")
  9198. (delschedule "no longer scheduled")
  9199. (redeadline "changing deadline")
  9200. (deldeadline "removing deadline")
  9201. (refile "refiling")
  9202. (note "this entry")
  9203. (state
  9204. (format "state change from \"%s\" to \"%s\""
  9205. (or org-log-note-previous-state "")
  9206. (or org-log-note-state "")))
  9207. (t (error "This should not happen")))))
  9208. (when org-log-note-extra (insert org-log-note-extra))
  9209. (setq-local org-finish-function 'org-store-log-note)
  9210. (run-hooks 'org-log-buffer-setup-hook)))
  9211. (defvar org-note-abort nil) ; dynamically scoped
  9212. (defun org-store-log-note ()
  9213. "Finish taking a log note, and insert it to where it belongs."
  9214. (let ((txt (prog1 (buffer-string)
  9215. (kill-buffer)))
  9216. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9217. lines)
  9218. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9219. (setq txt (replace-match "" t t txt)))
  9220. (when (string-match "\\s-+\\'" txt)
  9221. (setq txt (replace-match "" t t txt)))
  9222. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9223. (when (org-string-nw-p note)
  9224. (setq note
  9225. (org-replace-escapes
  9226. note
  9227. (list (cons "%u" (user-login-name))
  9228. (cons "%U" user-full-name)
  9229. (cons "%t" (format-time-string
  9230. (org-time-stamp-format 'long 'inactive)
  9231. org-log-note-effective-time))
  9232. (cons "%T" (format-time-string
  9233. (org-time-stamp-format 'long nil)
  9234. org-log-note-effective-time))
  9235. (cons "%d" (format-time-string
  9236. (org-time-stamp-format nil 'inactive)
  9237. org-log-note-effective-time))
  9238. (cons "%D" (format-time-string
  9239. (org-time-stamp-format nil nil)
  9240. org-log-note-effective-time))
  9241. (cons "%s" (cond
  9242. ((not org-log-note-state) "")
  9243. ((string-match-p org-ts-regexp
  9244. org-log-note-state)
  9245. (format "\"[%s]\""
  9246. (substring org-log-note-state 1 -1)))
  9247. (t (format "\"%s\"" org-log-note-state))))
  9248. (cons "%S"
  9249. (cond
  9250. ((not org-log-note-previous-state) "")
  9251. ((string-match-p org-ts-regexp
  9252. org-log-note-previous-state)
  9253. (format "\"[%s]\""
  9254. (substring
  9255. org-log-note-previous-state 1 -1)))
  9256. (t (format "\"%s\""
  9257. org-log-note-previous-state)))))))
  9258. (when lines (setq note (concat note " \\\\")))
  9259. (push note lines))
  9260. (when (and lines (not org-note-abort))
  9261. (with-current-buffer (marker-buffer org-log-note-marker)
  9262. (org-fold-core-ignore-modifications
  9263. (org-with-wide-buffer
  9264. ;; Find location for the new note.
  9265. (goto-char org-log-note-marker)
  9266. (set-marker org-log-note-marker nil)
  9267. ;; Note associated to a clock is to be located right after
  9268. ;; the clock. Do not move point.
  9269. (unless (eq org-log-note-purpose 'clock-out)
  9270. (goto-char (org-log-beginning t)))
  9271. ;; Make sure point is at the beginning of an empty line.
  9272. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  9273. ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  9274. ;; In an existing list, add a new item at the top level.
  9275. ;; Otherwise, indent line like a regular one.
  9276. (let ((itemp (org-in-item-p)))
  9277. (if itemp
  9278. (indent-line-to
  9279. (let ((struct (save-excursion
  9280. (goto-char itemp) (org-list-struct))))
  9281. (org-list-get-ind (org-list-get-top-point struct) struct)))
  9282. (org-indent-line)))
  9283. (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  9284. (let ((ind (org-list-item-body-column (line-beginning-position))))
  9285. (dolist (line lines)
  9286. (insert-and-inherit "\n")
  9287. (indent-line-to ind)
  9288. (insert-and-inherit line)))
  9289. (message "Note stored")
  9290. (org-back-to-heading t))))))
  9291. ;; Don't add undo information when called from `org-agenda-todo'.
  9292. (set-window-configuration org-log-note-window-configuration)
  9293. (with-current-buffer (marker-buffer org-log-note-return-to)
  9294. (goto-char org-log-note-return-to))
  9295. (move-marker org-log-note-return-to nil)
  9296. (when org-log-post-message (message "%s" org-log-post-message)))
  9297. (defun org-remove-empty-drawer-at (pos)
  9298. "Remove an empty drawer at position POS.
  9299. POS may also be a marker."
  9300. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  9301. (org-with-wide-buffer
  9302. (goto-char pos)
  9303. (let ((drawer (org-element-at-point)))
  9304. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  9305. (not (org-element-property :contents-begin drawer)))
  9306. (delete-region (org-element-property :begin drawer)
  9307. (progn (goto-char (org-element-property :end drawer))
  9308. (skip-chars-backward " \r\t\n")
  9309. (forward-line)
  9310. (point))))))))
  9311. (defvar org-ts-type nil)
  9312. (defun org-sparse-tree (&optional arg type)
  9313. "Create a sparse tree, prompt for the details.
  9314. This command can create sparse trees. You first need to select the type
  9315. of match used to create the tree:
  9316. t Show all TODO entries.
  9317. T Show entries with a specific TODO keyword.
  9318. m Show entries selected by a tags/property match.
  9319. p Enter a property name and its value (both with completion on existing
  9320. names/values) and show entries with that property.
  9321. r Show entries matching a regular expression (`/' can be used as well).
  9322. b Show deadlines and scheduled items before a date.
  9323. a Show deadlines and scheduled items after a date.
  9324. d Show deadlines due within `org-deadline-warning-days'.
  9325. D Show deadlines and scheduled items between a date range."
  9326. (interactive "P")
  9327. (setq type (or type org-sparse-tree-default-date-type))
  9328. (setq org-ts-type type)
  9329. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  9330. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  9331. [c]ycle through date types: %s"
  9332. (cl-case type
  9333. (all "all timestamps")
  9334. (scheduled "only scheduled")
  9335. (deadline "only deadline")
  9336. (active "only active timestamps")
  9337. (inactive "only inactive timestamps")
  9338. (closed "with a closed time-stamp")
  9339. (otherwise "scheduled/deadline")))
  9340. (let ((answer (read-char-exclusive)))
  9341. (cl-case answer
  9342. (?c
  9343. (org-sparse-tree
  9344. arg
  9345. (cadr
  9346. (memq type '(nil all scheduled deadline active inactive closed)))))
  9347. (?d (call-interactively 'org-check-deadlines))
  9348. (?b (call-interactively 'org-check-before-date))
  9349. (?a (call-interactively 'org-check-after-date))
  9350. (?D (call-interactively 'org-check-dates-range))
  9351. (?t (call-interactively 'org-show-todo-tree))
  9352. (?T (org-show-todo-tree '(4)))
  9353. (?m (call-interactively 'org-match-sparse-tree))
  9354. ((?p ?P)
  9355. (let* ((kwd (completing-read
  9356. "Property: " (mapcar #'list (org-buffer-property-keys))))
  9357. (value (completing-read
  9358. "Value: " (mapcar #'list (org-property-values kwd)))))
  9359. (unless (string-match "\\`{.*}\\'" value)
  9360. (setq value (concat "\"" value "\"")))
  9361. (org-match-sparse-tree arg (concat kwd "=" value))))
  9362. ((?r ?R ?/) (call-interactively 'org-occur))
  9363. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  9364. (defvar-local org-occur-highlights nil
  9365. "List of overlays used for occur matches.")
  9366. (defvar-local org-occur-parameters nil
  9367. "Parameters of the active org-occur calls.
  9368. This is a list, each call to org-occur pushes as cons cell,
  9369. containing the regular expression and the callback, onto the list.
  9370. The list can contain several entries if `org-occur' has been called
  9371. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  9372. will only contain one set of parameters. When the highlights are
  9373. removed (for example with `C-c C-c', or with the next edit (depending
  9374. on `org-remove-highlights-with-change'), this variable is emptied
  9375. as well.")
  9376. (defun org-occur (regexp &optional keep-previous callback)
  9377. "Make a compact tree showing all matches of REGEXP.
  9378. The tree will show the lines where the regexp matches, and any other context
  9379. defined in `org-fold-show-context-detail', which see.
  9380. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  9381. done by a previous call to `org-occur' will be kept, to allow stacking of
  9382. calls to this command.
  9383. Optional argument CALLBACK can be a function of no argument. In this case,
  9384. it is called with point at the end of the match, match data being set
  9385. accordingly. Current match is shown only if the return value is non-nil.
  9386. The function must neither move point nor alter narrowing."
  9387. (interactive "sRegexp: \nP")
  9388. (when (equal regexp "")
  9389. (user-error "Regexp cannot be empty"))
  9390. (unless keep-previous
  9391. (org-remove-occur-highlights nil nil t))
  9392. (push (cons regexp callback) org-occur-parameters)
  9393. (let ((cnt 0))
  9394. (save-excursion
  9395. (goto-char (point-min))
  9396. (when (or (not keep-previous) ; do not want to keep
  9397. (not org-occur-highlights)) ; no previous matches
  9398. ;; hide everything
  9399. (org-cycle-overview))
  9400. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  9401. (isearch-no-upper-case-p regexp t)
  9402. org-occur-case-fold-search)))
  9403. (while (re-search-forward regexp nil t)
  9404. (when (or (not callback)
  9405. (save-match-data (funcall callback)))
  9406. (setq cnt (1+ cnt))
  9407. (when org-highlight-sparse-tree-matches
  9408. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  9409. (org-fold-show-context 'occur-tree)))))
  9410. (when org-remove-highlights-with-change
  9411. (add-hook 'before-change-functions 'org-remove-occur-highlights
  9412. nil 'local))
  9413. (unless org-sparse-tree-open-archived-trees
  9414. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9415. (run-hooks 'org-occur-hook)
  9416. (when (called-interactively-p 'interactive)
  9417. (message "%d match(es) for regexp %s" cnt regexp))
  9418. cnt))
  9419. (defun org-occur-next-match (&optional n _reset)
  9420. "Function for `next-error-function' to find sparse tree matches.
  9421. N is the number of matches to move, when negative move backwards.
  9422. This function always goes back to the starting point when no
  9423. match is found."
  9424. (let* ((limit (if (< n 0) (point-min) (point-max)))
  9425. (search-func (if (< n 0)
  9426. 'previous-single-char-property-change
  9427. 'next-single-char-property-change))
  9428. (n (abs n))
  9429. (pos (point))
  9430. p1)
  9431. (catch 'exit
  9432. (while (setq p1 (funcall search-func (point) 'org-type))
  9433. (when (equal p1 limit)
  9434. (goto-char pos)
  9435. (user-error "No more matches"))
  9436. (when (equal (get-char-property p1 'org-type) 'org-occur)
  9437. (setq n (1- n))
  9438. (when (= n 0)
  9439. (goto-char p1)
  9440. (throw 'exit (point))))
  9441. (goto-char p1))
  9442. (goto-char p1)
  9443. (user-error "No more matches"))))
  9444. (defun org-highlight-new-match (beg end)
  9445. "Highlight from BEG to END and mark the highlight is an occur headline."
  9446. (let ((ov (make-overlay beg end)))
  9447. (overlay-put ov 'face 'secondary-selection)
  9448. (overlay-put ov 'org-type 'org-occur)
  9449. (push ov org-occur-highlights)))
  9450. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  9451. "Remove the occur highlights from the buffer.
  9452. BEG and END are ignored. If NOREMOVE is nil, remove this function
  9453. from the `before-change-functions' in the current buffer."
  9454. (interactive)
  9455. (unless org-inhibit-highlight-removal
  9456. (mapc #'delete-overlay org-occur-highlights)
  9457. (setq org-occur-highlights nil)
  9458. (setq org-occur-parameters nil)
  9459. (unless noremove
  9460. (remove-hook 'before-change-functions
  9461. 'org-remove-occur-highlights 'local))))
  9462. ;;;; Priorities
  9463. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  9464. "Regular expression matching the priority indicator.
  9465. A priority indicator can be e.g. [#A] or [#1].
  9466. This regular expression matches these groups:
  9467. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  9468. 1 : the priority cookie, e.g. \"[#A]\"
  9469. 2 : the value of the priority cookie, e.g. \"A\".")
  9470. (defun org-priority-up ()
  9471. "Increase the priority of the current item."
  9472. (interactive)
  9473. (org-priority 'up))
  9474. (defun org-priority-down ()
  9475. "Decrease the priority of the current item."
  9476. (interactive)
  9477. (org-priority 'down))
  9478. (defun org-priority (&optional action show)
  9479. "Change the priority of an item.
  9480. When called interactively with a `\\[universal-argument]' prefix,
  9481. show the priority in the minibuffer instead of changing it.
  9482. When called programmatically, ACTION can be `set', `up', `down',
  9483. or a character."
  9484. (interactive "P")
  9485. (when show
  9486. ;; Deprecation warning inserted for Org 9.2; once enough time has
  9487. ;; passed the SHOW argument should be removed.
  9488. (warn "`org-priority' called with deprecated SHOW argument"))
  9489. (if (equal action '(4))
  9490. (org-priority-show)
  9491. (unless org-priority-enable-commands
  9492. (user-error "Priority commands are disabled"))
  9493. (setq action (or action 'set))
  9494. (let ((nump (< org-priority-lowest 65))
  9495. current new news have remove)
  9496. (save-excursion
  9497. (org-back-to-heading t)
  9498. (when (looking-at org-priority-regexp)
  9499. (let ((ms (match-string 2)))
  9500. (setq current (org-priority-to-value ms)
  9501. have t)))
  9502. (cond
  9503. ((eq action 'remove)
  9504. (setq remove t new ?\ ))
  9505. ((or (eq action 'set)
  9506. (integerp action))
  9507. (if (not (eq action 'set))
  9508. (setq new action)
  9509. (setq
  9510. new
  9511. (if nump
  9512. (let* ((msg (format "Priority %s-%s, SPC to remove: "
  9513. (number-to-string org-priority-highest)
  9514. (number-to-string org-priority-lowest)))
  9515. (s (if (< 9 org-priority-lowest)
  9516. (read-string msg)
  9517. (message msg)
  9518. (char-to-string (read-char-exclusive)))))
  9519. (if (equal s " ") ?\s (string-to-number s)))
  9520. (progn (message "Priority %c-%c, SPC to remove: "
  9521. org-priority-highest org-priority-lowest)
  9522. (save-match-data
  9523. (setq new (read-char-exclusive)))))))
  9524. (when (and (= (upcase org-priority-highest) org-priority-highest)
  9525. (= (upcase org-priority-lowest) org-priority-lowest))
  9526. (setq new (upcase new)))
  9527. (cond ((equal new ?\s) (setq remove t))
  9528. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  9529. (user-error
  9530. (if nump
  9531. "Priority must be between `%s' and `%s'"
  9532. "Priority must be between `%c' and `%c'")
  9533. org-priority-highest org-priority-lowest))))
  9534. ((eq action 'up)
  9535. (setq new (if have
  9536. (1- current) ; normal cycling
  9537. ;; last priority was empty
  9538. (if (eq last-command this-command)
  9539. org-priority-lowest ; wrap around empty to lowest
  9540. ;; default
  9541. (if org-priority-start-cycle-with-default
  9542. org-priority-default
  9543. (1- org-priority-default))))))
  9544. ((eq action 'down)
  9545. (setq new (if have
  9546. (1+ current) ; normal cycling
  9547. ;; last priority was empty
  9548. (if (eq last-command this-command)
  9549. org-priority-highest ; wrap around empty to highest
  9550. ;; default
  9551. (if org-priority-start-cycle-with-default
  9552. org-priority-default
  9553. (1+ org-priority-default))))))
  9554. (t (user-error "Invalid action")))
  9555. (when (or (< (upcase new) org-priority-highest)
  9556. (> (upcase new) org-priority-lowest))
  9557. (if (and (memq action '(up down))
  9558. (not have) (not (eq last-command this-command)))
  9559. ;; `new' is from default priority
  9560. (error
  9561. "The default can not be set, see `org-priority-default' why")
  9562. ;; normal cycling: `new' is beyond highest/lowest priority
  9563. ;; and is wrapped around to the empty priority
  9564. (setq remove t)))
  9565. ;; Numerical priorities are limited to 64, beyond that number,
  9566. ;; assume the priority cookie is a character.
  9567. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  9568. (if have
  9569. (if remove
  9570. (replace-match "" t t nil 1)
  9571. (replace-match news t t nil 2))
  9572. (if remove
  9573. (user-error "No priority cookie found in line")
  9574. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  9575. (if (match-end 2)
  9576. (progn
  9577. (goto-char (match-end 2))
  9578. (insert " [#" news "]"))
  9579. (goto-char (match-beginning 3))
  9580. (insert "[#" news "] "))))
  9581. (org-align-tags))
  9582. (if remove
  9583. (message "Priority removed")
  9584. (message "Priority of current item set to %s" news)))))
  9585. (defalias 'org-show-priority 'org-priority-show)
  9586. (defun org-priority-show ()
  9587. "Show the priority of the current item.
  9588. This priority is composed of the main priority given with the [#A] cookies,
  9589. and by additional input from the age of a schedules or deadline entry."
  9590. (interactive)
  9591. (let ((pri (if (eq major-mode 'org-agenda-mode)
  9592. (org-get-at-bol 'priority)
  9593. (save-excursion
  9594. (save-match-data
  9595. (beginning-of-line)
  9596. (and (looking-at org-heading-regexp)
  9597. (org-get-priority (match-string 0))))))))
  9598. (message "Priority is %d" (if pri pri -1000))))
  9599. (defun org-get-priority (s)
  9600. "Find priority cookie and return priority.
  9601. S is a string against which you can match `org-priority-regexp'.
  9602. If `org-priority-get-priority-function' is set to a custom
  9603. function, use it. Otherwise process S and output the priority
  9604. value, an integer."
  9605. (save-match-data
  9606. (if (functionp org-priority-get-priority-function)
  9607. (funcall org-priority-get-priority-function s)
  9608. (if (not (string-match org-priority-regexp s))
  9609. (* 1000 (- org-priority-lowest org-priority-default))
  9610. (* 1000 (- org-priority-lowest
  9611. (org-priority-to-value (match-string 2 s))))))))
  9612. ;;;; Tags
  9613. (defvar org-agenda-archives-mode)
  9614. (defvar org-map-continue-from nil
  9615. "Position from where mapping should continue.
  9616. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  9617. (defvar org-scanner-tags nil
  9618. "The current tag list while the tags scanner is running.")
  9619. (defvar org-trust-scanner-tags nil
  9620. "Should `org-get-tags' use the tags for the scanner.
  9621. This is for internal dynamical scoping only.
  9622. When this is non-nil, the function `org-get-tags' will return the value
  9623. of `org-scanner-tags' instead of building the list by itself. This
  9624. can lead to large speed-ups when the tags scanner is used in a file with
  9625. many entries, and when the list of tags is retrieved, for example to
  9626. obtain a list of properties. Building the tags list for each entry in such
  9627. a file becomes an N^2 operation - but with this variable set, it scales
  9628. as N.")
  9629. (defvar org--matcher-tags-todo-only nil)
  9630. (defun org-scan-tags (action matcher todo-only &optional start-level)
  9631. "Scan headline tags with inheritance and produce output ACTION.
  9632. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  9633. or `agenda' to produce an entry list for an agenda view. It can also be
  9634. a Lisp form or a function that should be called at each matched headline, in
  9635. this case the return value is a list of all return values from these calls.
  9636. MATCHER is a function accepting three arguments, returning
  9637. a non-nil value whenever a given set of tags qualifies a headline
  9638. for inclusion. See `org-make-tags-matcher' for more information.
  9639. As a special case, it can also be set to t (respectively nil) in
  9640. order to match all (respectively none) headline.
  9641. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  9642. included in the output.
  9643. START-LEVEL can be a string with asterisks, reducing the scope to
  9644. headlines matching this string."
  9645. (require 'org-agenda)
  9646. (let* ((re (concat "^"
  9647. (if start-level
  9648. ;; Get the correct level to match
  9649. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9650. org-outline-regexp)
  9651. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  9652. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  9653. (props (list 'face 'default
  9654. 'done-face 'org-agenda-done
  9655. 'undone-face 'default
  9656. 'mouse-face 'highlight
  9657. 'org-not-done-regexp org-not-done-regexp
  9658. 'org-todo-regexp org-todo-regexp
  9659. 'org-complex-heading-regexp org-complex-heading-regexp
  9660. 'help-echo
  9661. (format "mouse-2 or RET jump to Org file %S"
  9662. (abbreviate-file-name
  9663. (or (buffer-file-name (buffer-base-buffer))
  9664. (buffer-name (buffer-base-buffer)))))))
  9665. (org-map-continue-from nil)
  9666. lspos tags tags-list
  9667. (tags-alist (list (cons 0 org-file-tags)))
  9668. (llast 0) rtn rtn1 level category i txt
  9669. todo marker entry priority
  9670. ts-date ts-date-type ts-date-pair)
  9671. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  9672. (setq action (list 'lambda nil action)))
  9673. (save-excursion
  9674. (goto-char (point-min))
  9675. (when (eq action 'sparse-tree)
  9676. (org-cycle-overview)
  9677. (org-remove-occur-highlights))
  9678. (if (org-element--cache-active-p)
  9679. (let ((fast-re (concat "^"
  9680. (if start-level
  9681. ;; Get the correct level to match
  9682. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  9683. org-outline-regexp))))
  9684. (org-element-cache-map
  9685. (lambda (el)
  9686. (goto-char (org-element-property :begin el))
  9687. (setq todo (org-element-property :todo-keyword el)
  9688. level (org-element-property :level el)
  9689. category (org-entry-get-with-inheritance "CATEGORY" nil el)
  9690. tags-list (org-get-tags el)
  9691. org-scanner-tags tags-list)
  9692. (when (eq action 'agenda)
  9693. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9694. ts-date (car ts-date-pair)
  9695. ts-date-type (cdr ts-date-pair)))
  9696. (catch :skip
  9697. (when (and
  9698. ;; eval matcher only when the todo condition is OK
  9699. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9700. (if (functionp matcher)
  9701. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9702. (funcall matcher todo tags-list level))
  9703. matcher))
  9704. ;; Call the skipper, but return t if it does not
  9705. ;; skip, so that the `and' form continues evaluating.
  9706. (progn
  9707. (unless (eq action 'sparse-tree) (org-agenda-skip el))
  9708. t)
  9709. ;; Check if timestamps are deselecting this entry
  9710. (or (not todo-only)
  9711. (and (member todo org-todo-keywords-1)
  9712. (or (not org-agenda-tags-todo-honor-ignore-options)
  9713. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9714. ;; select this headline
  9715. (cond
  9716. ((eq action 'sparse-tree)
  9717. (and org-highlight-sparse-tree-matches
  9718. (org-get-heading) (match-end 0)
  9719. (org-highlight-new-match
  9720. (match-beginning 1) (match-end 1)))
  9721. (org-fold-show-context 'tags-tree))
  9722. ((eq action 'agenda)
  9723. (let* ((effort (org-entry-get (point) org-effort-property))
  9724. (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  9725. (setq txt (org-agenda-format-item
  9726. ""
  9727. ;; Add `effort' and `effort-minutes'
  9728. ;; properties for prefix format.
  9729. (org-add-props
  9730. (concat
  9731. (if (eq org-tags-match-list-sublevels 'indented)
  9732. (make-string (1- level) ?.) "")
  9733. (org-get-heading))
  9734. nil
  9735. 'effort effort
  9736. 'effort-minutes effort-minutes)
  9737. (make-string level ?\s)
  9738. category
  9739. tags-list)
  9740. priority (org-get-priority txt))
  9741. ;; Now add `effort' and `effort-minutes' to
  9742. ;; full agenda line.
  9743. (setq txt (org-add-props txt nil
  9744. 'effort effort
  9745. 'effort-minutes effort-minutes)))
  9746. (goto-char (org-element-property :begin el))
  9747. (setq marker (org-agenda-new-marker))
  9748. (org-add-props txt props
  9749. 'org-marker marker 'org-hd-marker marker 'org-category category
  9750. 'todo-state todo
  9751. 'ts-date ts-date
  9752. 'priority priority
  9753. 'type (concat "tagsmatch" ts-date-type))
  9754. (push txt rtn))
  9755. ((functionp action)
  9756. (setq org-map-continue-from nil)
  9757. (save-excursion
  9758. (setq rtn1 (funcall action))
  9759. (push rtn1 rtn)))
  9760. (t (user-error "Invalid action")))
  9761. ;; if we are to skip sublevels, jump to end of subtree
  9762. (unless org-tags-match-list-sublevels
  9763. (goto-char (1- (org-element-property :end el))))))
  9764. ;; Get the correct position from where to continue
  9765. (when org-map-continue-from
  9766. (setq org-element-cache-map-continue-from org-map-continue-from)
  9767. (goto-char org-map-continue-from))
  9768. ;; Return nil.
  9769. nil)
  9770. :next-re fast-re
  9771. :fail-re fast-re
  9772. :narrow t))
  9773. (while (let (case-fold-search)
  9774. (re-search-forward re nil t))
  9775. (setq org-map-continue-from nil)
  9776. (catch :skip
  9777. ;; Ignore closing parts of inline tasks.
  9778. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  9779. (throw :skip t))
  9780. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  9781. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  9782. (goto-char (setq lspos (match-beginning 0)))
  9783. (setq level (org-reduced-level (org-outline-level))
  9784. category (org-get-category))
  9785. (when (eq action 'agenda)
  9786. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  9787. ts-date (car ts-date-pair)
  9788. ts-date-type (cdr ts-date-pair)))
  9789. (setq i llast llast level)
  9790. ;; remove tag lists from same and sublevels
  9791. (while (>= i level)
  9792. (when (setq entry (assoc i tags-alist))
  9793. (setq tags-alist (delete entry tags-alist)))
  9794. (setq i (1- i)))
  9795. ;; add the next tags
  9796. (when tags
  9797. (setq tags (org-split-string tags ":")
  9798. tags-alist
  9799. (cons (cons level tags) tags-alist)))
  9800. ;; compile tags for current headline
  9801. (setq tags-list
  9802. (if org-use-tag-inheritance
  9803. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  9804. tags)
  9805. org-scanner-tags tags-list)
  9806. (when org-use-tag-inheritance
  9807. (setcdr (car tags-alist)
  9808. (mapcar (lambda (x)
  9809. (setq x (copy-sequence x))
  9810. (org-add-prop-inherited x))
  9811. (cdar tags-alist))))
  9812. (when (and tags org-use-tag-inheritance
  9813. (or (not (eq t org-use-tag-inheritance))
  9814. org-tags-exclude-from-inheritance))
  9815. ;; Selective inheritance, remove uninherited ones.
  9816. (setcdr (car tags-alist)
  9817. (org-remove-uninherited-tags (cdar tags-alist))))
  9818. (when (and
  9819. ;; eval matcher only when the todo condition is OK
  9820. (and (or (not todo-only) (member todo org-todo-keywords-1))
  9821. (if (functionp matcher)
  9822. (let ((case-fold-search t) (org-trust-scanner-tags t))
  9823. (funcall matcher todo tags-list level))
  9824. matcher))
  9825. ;; Call the skipper, but return t if it does not
  9826. ;; skip, so that the `and' form continues evaluating.
  9827. (progn
  9828. (unless (eq action 'sparse-tree) (org-agenda-skip))
  9829. t)
  9830. ;; Check if timestamps are deselecting this entry
  9831. (or (not todo-only)
  9832. (and (member todo org-todo-keywords-1)
  9833. (or (not org-agenda-tags-todo-honor-ignore-options)
  9834. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  9835. ;; select this headline
  9836. (cond
  9837. ((eq action 'sparse-tree)
  9838. (and org-highlight-sparse-tree-matches
  9839. (org-get-heading) (match-end 0)
  9840. (org-highlight-new-match
  9841. (match-beginning 1) (match-end 1)))
  9842. (org-fold-show-context 'tags-tree))
  9843. ((eq action 'agenda)
  9844. (setq txt (org-agenda-format-item
  9845. ""
  9846. (concat
  9847. (if (eq org-tags-match-list-sublevels 'indented)
  9848. (make-string (1- level) ?.) "")
  9849. (org-get-heading))
  9850. (make-string level ?\s)
  9851. category
  9852. tags-list)
  9853. priority (org-get-priority txt))
  9854. (goto-char lspos)
  9855. (setq marker (org-agenda-new-marker))
  9856. (org-add-props txt props
  9857. 'org-marker marker 'org-hd-marker marker 'org-category category
  9858. 'todo-state todo
  9859. 'ts-date ts-date
  9860. 'priority priority
  9861. 'type (concat "tagsmatch" ts-date-type))
  9862. (push txt rtn))
  9863. ((functionp action)
  9864. (setq org-map-continue-from nil)
  9865. (save-excursion
  9866. (setq rtn1 (funcall action))
  9867. (push rtn1 rtn)))
  9868. (t (user-error "Invalid action")))
  9869. ;; if we are to skip sublevels, jump to end of subtree
  9870. (unless org-tags-match-list-sublevels
  9871. (org-end-of-subtree t)
  9872. (backward-char 1))))
  9873. ;; Get the correct position from where to continue
  9874. (if org-map-continue-from
  9875. (goto-char org-map-continue-from)
  9876. (and (= (point) lspos) (end-of-line 1))))))
  9877. (when (and (eq action 'sparse-tree)
  9878. (not org-sparse-tree-open-archived-trees))
  9879. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  9880. (nreverse rtn)))
  9881. (defun org-remove-uninherited-tags (tags)
  9882. "Remove all tags that are not inherited from the list TAGS."
  9883. (cond
  9884. ((eq org-use-tag-inheritance t)
  9885. (if org-tags-exclude-from-inheritance
  9886. (org-delete-all org-tags-exclude-from-inheritance tags)
  9887. tags))
  9888. ((not org-use-tag-inheritance) nil)
  9889. ((stringp org-use-tag-inheritance)
  9890. (delq nil (mapcar
  9891. (lambda (x)
  9892. (if (and (string-match org-use-tag-inheritance x)
  9893. (not (member x org-tags-exclude-from-inheritance)))
  9894. x nil))
  9895. tags)))
  9896. ((listp org-use-tag-inheritance)
  9897. (delq nil (mapcar
  9898. (lambda (x)
  9899. (if (member x org-use-tag-inheritance) x nil))
  9900. tags)))))
  9901. (defun org-match-sparse-tree (&optional todo-only match)
  9902. "Create a sparse tree according to tags string MATCH.
  9903. MATCH is a string with match syntax. It can contain a selection
  9904. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  9905. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  9906. those. See the manual for details.
  9907. If optional argument TODO-ONLY is non-nil, only select lines that
  9908. are also TODO tasks."
  9909. (interactive "P")
  9910. (org-agenda-prepare-buffers (list (current-buffer)))
  9911. (let ((org--matcher-tags-todo-only todo-only))
  9912. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  9913. org--matcher-tags-todo-only)))
  9914. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  9915. (defvar org-cached-props nil)
  9916. (defun org-cached-entry-get (pom property)
  9917. (if (or (eq t org-use-property-inheritance)
  9918. (and (stringp org-use-property-inheritance)
  9919. (let ((case-fold-search t))
  9920. (string-match-p org-use-property-inheritance property)))
  9921. (and (listp org-use-property-inheritance)
  9922. (member-ignore-case property org-use-property-inheritance)))
  9923. ;; Caching is not possible, check it directly.
  9924. (org-entry-get pom property 'inherit)
  9925. ;; Get all properties, so we can do complicated checks easily.
  9926. (cdr (assoc-string property
  9927. (or org-cached-props
  9928. (setq org-cached-props (org-entry-properties pom)))
  9929. t))))
  9930. (defun org-global-tags-completion-table (&optional files)
  9931. "Return the list of all tags in all agenda buffer/files.
  9932. Optional FILES argument is a list of files which can be used
  9933. instead of the agenda files."
  9934. (save-excursion
  9935. (org-uniquify
  9936. (delq nil
  9937. (apply #'append
  9938. (mapcar
  9939. (lambda (file)
  9940. (set-buffer (find-file-noselect file))
  9941. (org--tag-add-to-alist
  9942. (org-get-buffer-tags)
  9943. (mapcar (lambda (x)
  9944. (and (stringp (car-safe x))
  9945. (list (car-safe x))))
  9946. org-current-tag-alist)))
  9947. (if (car-safe files) files
  9948. (org-agenda-files))))))))
  9949. (defun org-make-tags-matcher (match &optional only-local-tags)
  9950. "Create the TAGS/TODO matcher form for the selection string MATCH.
  9951. Returns a cons of the selection string MATCH and a function
  9952. implementing the matcher.
  9953. The matcher is to be called at an Org entry, with point on the
  9954. headline, and returns non-nil if the entry matches the selection
  9955. string MATCH. It must be called with three arguments: the TODO
  9956. keyword at the entry (or nil if none), the list of all tags at
  9957. the entry including inherited ones and the reduced level of the
  9958. headline. Additionally, the category of the entry, if any, must
  9959. be specified as the text property `org-category' on the headline.
  9960. This function sets the variable `org--matcher-tags-todo-only' to
  9961. a non-nil value if the matcher restricts matching to TODO
  9962. entries, otherwise it is not touched.
  9963. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  9964. table, only get buffer tags.
  9965. See also `org-scan-tags'."
  9966. (unless match
  9967. ;; Get a new match request, with completion against the global
  9968. ;; tags table and the local tags in current buffer.
  9969. (let ((org-last-tags-completion-table
  9970. (org--tag-add-to-alist
  9971. (org-get-buffer-tags)
  9972. (unless only-local-tags
  9973. (org-global-tags-completion-table)))))
  9974. (setq match
  9975. (completing-read
  9976. "Match: "
  9977. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  9978. (let ((match0 match)
  9979. (re (concat
  9980. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  9981. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  9982. "\\([<>=]\\{1,2\\}\\)"
  9983. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  9984. "\\|" org-tag-re "\\)"))
  9985. (start 0)
  9986. tagsmatch todomatch tagsmatcher todomatcher)
  9987. ;; Expand group tags.
  9988. (setq match (org-tags-expand match))
  9989. ;; Check if there is a TODO part of this match, which would be the
  9990. ;; part after a "/". To make sure that this slash is not part of
  9991. ;; a property value to be matched against, we also check that
  9992. ;; there is no / after that slash. First, find the last slash.
  9993. (let ((s 0))
  9994. (while (string-match "/+" match s)
  9995. (setq start (match-beginning 0))
  9996. (setq s (match-end 0))))
  9997. (if (and (string-match "/+" match start)
  9998. (not (string-match-p "\"" match start)))
  9999. ;; Match contains also a TODO-matching request.
  10000. (progn
  10001. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10002. (setq todomatch (substring match (match-end 0)))
  10003. (when (string-prefix-p "!" todomatch)
  10004. (setq org--matcher-tags-todo-only t)
  10005. (setq todomatch (substring todomatch 1)))
  10006. (when (string-match "\\`\\s-*\\'" todomatch)
  10007. (setq todomatch nil)))
  10008. ;; Only matching tags.
  10009. (setq tagsmatch match)
  10010. (setq todomatch nil))
  10011. ;; Make the tags matcher.
  10012. (when (org-string-nw-p tagsmatch)
  10013. (let ((orlist nil)
  10014. (orterms (org-split-string tagsmatch "|"))
  10015. term)
  10016. (while (setq term (pop orterms))
  10017. (while (and (equal (substring term -1) "\\") orterms)
  10018. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10019. (while (string-match re term)
  10020. (let* ((rest (substring term (match-end 0)))
  10021. (minus (and (match-end 1)
  10022. (equal (match-string 1 term) "-")))
  10023. (tag (save-match-data
  10024. (replace-regexp-in-string
  10025. "\\\\-" "-" (match-string 2 term))))
  10026. (regexp (eq (string-to-char tag) ?{))
  10027. (levelp (match-end 4))
  10028. (propp (match-end 5))
  10029. (mm
  10030. (cond
  10031. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10032. (levelp
  10033. `(,(org-op-to-function (match-string 3 term))
  10034. level
  10035. ,(string-to-number (match-string 4 term))))
  10036. (propp
  10037. (let* ((gv (pcase (upcase (match-string 5 term))
  10038. ("CATEGORY"
  10039. '(org-get-category (point)))
  10040. ("TODO" 'todo)
  10041. (p `(org-cached-entry-get nil ,p))))
  10042. (pv (match-string 7 term))
  10043. (regexp (eq (string-to-char pv) ?{))
  10044. (strp (eq (string-to-char pv) ?\"))
  10045. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10046. (po (org-op-to-function (match-string 6 term)
  10047. (if timep 'time strp))))
  10048. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10049. (when timep (setq pv (org-matcher-time pv)))
  10050. (cond ((and regexp (eq po '/=))
  10051. `(not (string-match ,pv (or ,gv ""))))
  10052. (regexp `(string-match ,pv (or ,gv "")))
  10053. (strp `(,po (or ,gv "") ,pv))
  10054. (t
  10055. `(,po
  10056. (string-to-number (or ,gv ""))
  10057. ,(string-to-number pv))))))
  10058. (t `(member ,tag tags-list)))))
  10059. (push (if minus `(not ,mm) mm) tagsmatcher)
  10060. (setq term rest)))
  10061. (push `(and ,@tagsmatcher) orlist)
  10062. (setq tagsmatcher nil))
  10063. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10064. ;; Make the TODO matcher.
  10065. (when (org-string-nw-p todomatch)
  10066. (let ((orlist nil))
  10067. (dolist (term (org-split-string todomatch "|"))
  10068. (while (string-match re term)
  10069. (let* ((minus (and (match-end 1)
  10070. (equal (match-string 1 term) "-")))
  10071. (kwd (match-string 2 term))
  10072. (regexp (eq (string-to-char kwd) ?{))
  10073. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10074. `(equal todo ,kwd))))
  10075. (push (if minus `(not ,mm) mm) todomatcher))
  10076. (setq term (substring term (match-end 0))))
  10077. (push (if (> (length todomatcher) 1)
  10078. (cons 'and todomatcher)
  10079. (car todomatcher))
  10080. orlist)
  10081. (setq todomatcher nil))
  10082. (setq todomatcher (cons 'or orlist))))
  10083. ;; Return the string and function of the matcher. If no
  10084. ;; tags-specific or todo-specific matcher exists, match
  10085. ;; everything.
  10086. (let ((matcher (if (and tagsmatcher todomatcher)
  10087. `(and ,tagsmatcher ,todomatcher)
  10088. (or tagsmatcher todomatcher t))))
  10089. (when org--matcher-tags-todo-only
  10090. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10091. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10092. (defun org--tags-expand-group (group tag-groups expanded)
  10093. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10094. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10095. an accumulator used in recursive calls."
  10096. (dolist (tag group)
  10097. (unless (member tag expanded)
  10098. (let ((group (assoc tag tag-groups)))
  10099. (push tag expanded)
  10100. (when group
  10101. (setq expanded
  10102. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10103. expanded)
  10104. (defun org-tags-expand (match &optional single-as-list)
  10105. "Expand group tags in MATCH.
  10106. This replaces every group tag in MATCH with a regexp tag search.
  10107. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10108. will be replaced like this:
  10109. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10110. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10111. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10112. Replacing by a regexp preserves the structure of the match.
  10113. E.g., this expansion
  10114. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10115. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10116. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10117. A group tag in MATCH can contain regular expressions of its own.
  10118. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10119. will be replaced like this:
  10120. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10121. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10122. assumed to be a single group tag, and the function will return
  10123. the list of tags in this group."
  10124. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10125. (let ((tag-groups
  10126. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10127. (cond
  10128. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10129. (org-group-tags
  10130. (let* ((case-fold-search t)
  10131. (tag-syntax org-mode-syntax-table)
  10132. (group-keys (mapcar #'car tag-groups))
  10133. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10134. (return-match match))
  10135. ;; Mark regexp-expressions in the match-expression so that we
  10136. ;; do not replace them later on.
  10137. (let ((s 0))
  10138. (while (string-match "{.+?}" return-match s)
  10139. (setq s (match-end 0))
  10140. (add-text-properties
  10141. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10142. ;; @ and _ are allowed as word-components in tags.
  10143. (modify-syntax-entry ?@ "w" tag-syntax)
  10144. (modify-syntax-entry ?_ "w" tag-syntax)
  10145. ;; For each tag token found in MATCH, compute a regexp and it
  10146. (with-syntax-table tag-syntax
  10147. (replace-regexp-in-string
  10148. key-regexp
  10149. (lambda (m)
  10150. (if (get-text-property (match-beginning 2) 'regexp m)
  10151. m ;regexp tag: ignore
  10152. (let* ((operator (match-string 1 m))
  10153. (tag-token (let ((tag (match-string 2 m)))
  10154. (list tag)))
  10155. regexp-tags regular-tags)
  10156. ;; Partition tags between regexp and regular tags.
  10157. ;; Remove curly bracket syntax from regexp tags.
  10158. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10159. (save-match-data
  10160. (if (string-match "{\\(.+?\\)}" tag)
  10161. (push (match-string 1 tag) regexp-tags)
  10162. (push tag regular-tags))))
  10163. ;; Replace tag token by the appropriate regexp.
  10164. ;; Regular tags need to be regexp-quoted, whereas
  10165. ;; regexp-tags are inserted as-is.
  10166. (let ((regular (regexp-opt regular-tags))
  10167. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10168. (concat operator
  10169. (cond
  10170. ((null regular-tags) (format "{%s}" regexp))
  10171. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10172. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10173. return-match
  10174. t t))))
  10175. (t match))))
  10176. (defun org-op-to-function (op &optional stringp)
  10177. "Turn an operator into the appropriate function."
  10178. (setq op
  10179. (cond
  10180. ((equal op "<" ) '(< org-string< org-time<))
  10181. ((equal op ">" ) '(> org-string> org-time>))
  10182. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10183. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10184. ((member op '("=" "==")) '(= string= org-time=))
  10185. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10186. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10187. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10188. (defvar org-tags-overlay (make-overlay 1 1))
  10189. (delete-overlay org-tags-overlay)
  10190. (defun org-add-prop-inherited (s)
  10191. (add-text-properties 0 (length s) '(inherited t) s)
  10192. s)
  10193. (defun org-toggle-tag (tag &optional onoff)
  10194. "Toggle the tag TAG for the current line.
  10195. If ONOFF is `on' or `off', don't toggle but set to this state."
  10196. (save-excursion
  10197. (org-back-to-heading t)
  10198. (let ((current
  10199. ;; Reverse the tags list so any new tag is appended to the
  10200. ;; current list of tags.
  10201. (nreverse (org-get-tags nil t)))
  10202. res)
  10203. (pcase onoff
  10204. (`off (setq current (delete tag current)))
  10205. ((or `on (guard (not (member tag current))))
  10206. (setq res t)
  10207. (cl-pushnew tag current :test #'equal))
  10208. (_ (setq current (delete tag current))))
  10209. (org-set-tags (nreverse current))
  10210. res)))
  10211. (defun org--align-tags-here (to-col)
  10212. "Align tags on the current headline to TO-COL.
  10213. Assume point is on a headline. Preserve point when aligning
  10214. tags."
  10215. (when (org-match-line org-tag-line-re)
  10216. (let* ((tags-start (match-beginning 1))
  10217. (blank-start (save-excursion
  10218. (goto-char tags-start)
  10219. (skip-chars-backward " \t")
  10220. (point)))
  10221. (new (max (if (>= to-col 0) to-col
  10222. (- (abs to-col) (string-width (match-string 1))))
  10223. ;; Introduce at least one space after the heading
  10224. ;; or the stars.
  10225. (save-excursion
  10226. (goto-char blank-start)
  10227. (1+ (current-column)))))
  10228. (current
  10229. (save-excursion (goto-char tags-start) (current-column)))
  10230. (origin (point-marker))
  10231. (column (current-column))
  10232. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10233. (when (/= new current)
  10234. (delete-region blank-start tags-start)
  10235. (goto-char blank-start)
  10236. (let ((indent-tabs-mode nil)) (indent-to new))
  10237. ;; Try to move back to original position. If point was in the
  10238. ;; blanks before the tags, ORIGIN marker is of no use because
  10239. ;; it now points to BLANK-START. Use COLUMN instead.
  10240. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10241. (defun org-set-tags-command (&optional arg)
  10242. "Set the tags for the current visible entry.
  10243. When called with `\\[universal-argument]' prefix argument ARG, \
  10244. realign all tags
  10245. in the current buffer.
  10246. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10247. unconditionally do not
  10248. offer the fast tag selection interface.
  10249. If a region is active, set tags in the region according to the
  10250. setting of `org-loop-over-headlines-in-active-region'.
  10251. This function is for interactive use only;
  10252. in Lisp code use `org-set-tags' instead."
  10253. (interactive "P")
  10254. (let ((org-use-fast-tag-selection
  10255. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10256. (cond
  10257. ((equal '(4) arg) (org-align-tags t))
  10258. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10259. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10260. (org-map-entries
  10261. #'org-set-tags-command
  10262. nil
  10263. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10264. 'region-start-level
  10265. 'region)
  10266. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10267. (t
  10268. (save-excursion
  10269. (org-back-to-heading)
  10270. (let* ((all-tags (org-get-tags))
  10271. (table (setq org-last-tags-completion-table
  10272. (org--tag-add-to-alist
  10273. (and org-complete-tags-always-offer-all-agenda-tags
  10274. (org-global-tags-completion-table
  10275. (org-agenda-files)))
  10276. (or org-current-tag-alist (org-get-buffer-tags)))))
  10277. (current-tags
  10278. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10279. all-tags))
  10280. (inherited-tags
  10281. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10282. all-tags))
  10283. (tags
  10284. (replace-regexp-in-string
  10285. ;; Ignore all forbidden characters in tags.
  10286. "[^[:alnum:]_@#%]+" ":"
  10287. (if (or (eq t org-use-fast-tag-selection)
  10288. (and org-use-fast-tag-selection
  10289. (delq nil (mapcar #'cdr table))))
  10290. (org-fast-tag-selection
  10291. current-tags
  10292. inherited-tags
  10293. table
  10294. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10295. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10296. (crm-separator "[ \t]*:[ \t]*"))
  10297. (mapconcat #'identity
  10298. (completing-read-multiple
  10299. "Tags: "
  10300. org-last-tags-completion-table
  10301. nil nil (org-make-tag-string current-tags)
  10302. 'org-tags-history)
  10303. ":"))))))
  10304. (org-set-tags tags)))))
  10305. ;; `save-excursion' may not replace the point at the right
  10306. ;; position.
  10307. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10308. (looking-at-p " "))
  10309. (forward-char))))
  10310. (defun org-align-tags (&optional all)
  10311. "Align tags in current entry.
  10312. When optional argument ALL is non-nil, align all tags in the
  10313. visible part of the buffer."
  10314. (let ((get-indent-column
  10315. (lambda ()
  10316. (let ((offset (if (bound-and-true-p org-indent-mode)
  10317. (* (1- org-indent-indentation-per-level)
  10318. (1- (org-current-level)))
  10319. 0)))
  10320. (+ org-tags-column
  10321. (if (> org-tags-column 0) (- offset) offset))))))
  10322. (if (and (not all) (org-at-heading-p))
  10323. (org--align-tags-here (funcall get-indent-column))
  10324. (save-excursion
  10325. (if all
  10326. (progn
  10327. (goto-char (point-min))
  10328. (while (re-search-forward org-tag-line-re nil t)
  10329. (org--align-tags-here (funcall get-indent-column))))
  10330. (org-back-to-heading t)
  10331. (org--align-tags-here (funcall get-indent-column)))))))
  10332. (defun org-set-tags (tags)
  10333. "Set the tags of the current entry to TAGS, replacing current tags.
  10334. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10335. If TAGS is nil or the empty string, all tags are removed.
  10336. This function assumes point is on a headline."
  10337. (org-with-wide-buffer
  10338. (org-fold-core-ignore-modifications
  10339. (let ((tags (pcase tags
  10340. ((pred listp) tags)
  10341. ((pred stringp) (split-string (org-trim tags) ":" t))
  10342. (_ (error "Invalid tag specification: %S" tags))))
  10343. (old-tags (org-get-tags nil t))
  10344. (tags-change? nil))
  10345. (when (functionp org-tags-sort-function)
  10346. (setq tags (sort tags org-tags-sort-function)))
  10347. (setq tags-change? (not (equal tags old-tags)))
  10348. (when tags-change?
  10349. ;; Delete previous tags and any trailing white space.
  10350. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10351. (line-end-position)))
  10352. (skip-chars-backward " \t")
  10353. (delete-region (point) (line-end-position))
  10354. ;; Deleting white spaces may break an otherwise empty headline.
  10355. ;; Re-introduce one space in this case.
  10356. (unless (org-at-heading-p) (insert " "))
  10357. (when tags
  10358. (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  10359. ;; When text is being inserted on an invisible region
  10360. ;; boundary, it can be inadvertently sucked into
  10361. ;; invisibility.
  10362. (unless (org-invisible-p (line-beginning-position))
  10363. (org-fold-region (point) (line-end-position) nil 'outline))))
  10364. ;; Align tags, if any.
  10365. (when tags (org-align-tags))
  10366. (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  10367. (defun org-change-tag-in-region (beg end tag off)
  10368. "Add or remove TAG for each entry in the region.
  10369. This works in the agenda, and also in an Org buffer."
  10370. (interactive
  10371. (list (region-beginning) (region-end)
  10372. (let ((org-last-tags-completion-table
  10373. (if (derived-mode-p 'org-mode)
  10374. (org--tag-add-to-alist
  10375. (org-get-buffer-tags)
  10376. (org-global-tags-completion-table))
  10377. (org-global-tags-completion-table))))
  10378. (completing-read
  10379. "Tag: " org-last-tags-completion-table nil nil nil
  10380. 'org-tags-history))
  10381. (progn
  10382. (message "[s]et or [r]emove? ")
  10383. (equal (read-char-exclusive) ?r))))
  10384. (when (fboundp 'deactivate-mark) (deactivate-mark))
  10385. (let ((agendap (equal major-mode 'org-agenda-mode))
  10386. l1 l2 m buf pos newhead (cnt 0))
  10387. (goto-char end)
  10388. (setq l2 (1- (org-current-line)))
  10389. (goto-char beg)
  10390. (setq l1 (org-current-line))
  10391. (cl-loop for l from l1 to l2 do
  10392. (org-goto-line l)
  10393. (setq m (get-text-property (point) 'org-hd-marker))
  10394. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  10395. (and agendap m))
  10396. (setq buf (if agendap (marker-buffer m) (current-buffer))
  10397. pos (if agendap m (point)))
  10398. (with-current-buffer buf
  10399. (save-excursion
  10400. (save-restriction
  10401. (goto-char pos)
  10402. (setq cnt (1+ cnt))
  10403. (org-toggle-tag tag (if off 'off 'on))
  10404. (setq newhead (org-get-heading)))))
  10405. (and agendap (org-agenda-change-all-lines newhead m))))
  10406. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  10407. (defun org-tags-completion-function (string _predicate &optional flag)
  10408. "Complete tag STRING.
  10409. FLAG specifies the type of completion operation to perform. This
  10410. function is passed as a collection function to `completing-read',
  10411. which see."
  10412. (let ((completion-ignore-case nil) ;tags are case-sensitive
  10413. (confirm (lambda (x) (stringp (car x))))
  10414. (prefix ""))
  10415. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  10416. (setq prefix (match-string 1 string))
  10417. (setq string (match-string 2 string)))
  10418. (pcase flag
  10419. (`t (all-completions string org-last-tags-completion-table confirm))
  10420. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  10421. (`nil
  10422. (pcase (try-completion string org-last-tags-completion-table confirm)
  10423. ((and completion (pred stringp))
  10424. (concat prefix
  10425. completion
  10426. (if (and org-add-colon-after-tag-completion
  10427. (assoc completion org-last-tags-completion-table))
  10428. ":"
  10429. "")))
  10430. (completion completion)))
  10431. (_ nil))))
  10432. (defun org-fast-tag-insert (kwd tags face &optional end)
  10433. "Insert KWD, and the TAGS, the latter with face FACE.
  10434. Also insert END."
  10435. (insert (format "%-12s" (concat kwd ":"))
  10436. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  10437. (or end "")))
  10438. (defun org-fast-tag-show-exit (flag)
  10439. (save-excursion
  10440. (org-goto-line 3)
  10441. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  10442. (replace-match ""))
  10443. (when flag
  10444. (end-of-line 1)
  10445. (org-move-to-column (- (window-width) 19) t)
  10446. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  10447. (defun org-set-current-tags-overlay (current prefix)
  10448. "Add an overlay to CURRENT tag with PREFIX."
  10449. (let ((s (org-make-tag-string current)))
  10450. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  10451. (org-overlay-display org-tags-overlay (concat prefix s))))
  10452. (defvar org-last-tag-selection-key nil)
  10453. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  10454. "Fast tag selection with single keys.
  10455. CURRENT is the current list of tags in the headline, INHERITED is the
  10456. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  10457. possibly with grouping information. TODO-TABLE is a similar table with
  10458. TODO keywords, should these have keys assigned to them.
  10459. If the keys are nil, a-z are automatically assigned.
  10460. Returns the new tags string, or nil to not change the current settings."
  10461. (let* ((fulltable (append table todo-table))
  10462. (maxlen (if (null fulltable) 0
  10463. (apply #'max
  10464. (mapcar (lambda (x)
  10465. (if (stringp (car x)) (string-width (car x))
  10466. 0))
  10467. fulltable))))
  10468. (buf (current-buffer))
  10469. (expert (eq org-fast-tag-selection-single-key 'expert))
  10470. (tab-tags nil)
  10471. (fwidth (+ maxlen 3 1 3))
  10472. (ncol (/ (- (window-width) 4) fwidth))
  10473. (i-face 'org-done)
  10474. (c-face 'org-todo)
  10475. tg cnt e c char c1 c2 ntable tbl rtn
  10476. ov-start ov-end ov-prefix
  10477. (exit-after-next org-fast-tag-selection-single-key)
  10478. (done-keywords org-done-keywords)
  10479. groups ingroup intaggroup)
  10480. (save-excursion
  10481. (beginning-of-line)
  10482. (if (looking-at org-tag-line-re)
  10483. (setq ov-start (match-beginning 1)
  10484. ov-end (match-end 1)
  10485. ov-prefix "")
  10486. (setq ov-start (1- (point-at-eol))
  10487. ov-end (1+ ov-start))
  10488. (skip-chars-forward "^\n\r")
  10489. (setq ov-prefix
  10490. (concat
  10491. (buffer-substring (1- (point)) (point))
  10492. (if (> (current-column) org-tags-column)
  10493. " "
  10494. (make-string (- org-tags-column (current-column)) ?\ ))))))
  10495. (move-overlay org-tags-overlay ov-start ov-end)
  10496. (save-excursion
  10497. (save-window-excursion
  10498. (if expert
  10499. (set-buffer (get-buffer-create " *Org tags*"))
  10500. (delete-other-windows)
  10501. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  10502. (org-switch-to-buffer-other-window " *Org tags*"))
  10503. (erase-buffer)
  10504. (setq-local org-done-keywords done-keywords)
  10505. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  10506. (org-fast-tag-insert "Current" current c-face "\n\n")
  10507. (org-fast-tag-show-exit exit-after-next)
  10508. (org-set-current-tags-overlay current ov-prefix)
  10509. (setq tbl fulltable char ?a cnt 0)
  10510. (while (setq e (pop tbl))
  10511. (cond
  10512. ((eq (car e) :startgroup)
  10513. (push '() groups) (setq ingroup t)
  10514. (unless (zerop cnt)
  10515. (setq cnt 0)
  10516. (insert "\n"))
  10517. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  10518. ((eq (car e) :endgroup)
  10519. (setq ingroup nil cnt 0)
  10520. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  10521. ((eq (car e) :startgrouptag)
  10522. (setq intaggroup t)
  10523. (unless (zerop cnt)
  10524. (setq cnt 0)
  10525. (insert "\n"))
  10526. (insert "[ "))
  10527. ((eq (car e) :endgrouptag)
  10528. (setq intaggroup nil cnt 0)
  10529. (insert "]\n"))
  10530. ((equal e '(:newline))
  10531. (unless (zerop cnt)
  10532. (setq cnt 0)
  10533. (insert "\n")
  10534. (setq e (car tbl))
  10535. (while (equal (car tbl) '(:newline))
  10536. (insert "\n")
  10537. (setq tbl (cdr tbl)))))
  10538. ((equal e '(:grouptags)) (insert " : "))
  10539. (t
  10540. (setq tg (copy-sequence (car e)) c2 nil)
  10541. (if (cdr e)
  10542. (setq c (cdr e))
  10543. ;; automatically assign a character.
  10544. (setq c1 (string-to-char
  10545. (downcase (substring
  10546. tg (if (= (string-to-char tg) ?@) 1 0)))))
  10547. (if (or (rassoc c1 ntable) (rassoc c1 table))
  10548. (while (or (rassoc char ntable) (rassoc char table))
  10549. (setq char (1+ char)))
  10550. (setq c2 c1))
  10551. (setq c (or c2 char)))
  10552. (when ingroup (push tg (car groups)))
  10553. (setq tg (org-add-props tg nil 'face
  10554. (cond
  10555. ((not (assoc tg table))
  10556. (org-get-todo-face tg))
  10557. ((member tg current) c-face)
  10558. ((member tg inherited) i-face))))
  10559. (when (equal (caar tbl) :grouptags)
  10560. (org-add-props tg nil 'face 'org-tag-group))
  10561. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  10562. (insert "[" c "] " tg (make-string
  10563. (- fwidth 4 (length tg)) ?\ ))
  10564. (push (cons tg c) ntable)
  10565. (when (= (cl-incf cnt) ncol)
  10566. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  10567. (insert "\n")
  10568. (when (or ingroup intaggroup) (insert " ")))
  10569. (setq cnt 0)))))
  10570. (setq ntable (nreverse ntable))
  10571. (insert "\n")
  10572. (goto-char (point-min))
  10573. (unless expert (org-fit-window-to-buffer))
  10574. (setq rtn
  10575. (catch 'exit
  10576. (while t
  10577. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  10578. (if (not groups) "no " "")
  10579. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  10580. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  10581. (setq org-last-tag-selection-key c)
  10582. (cond
  10583. ((= c ?\r) (throw 'exit t))
  10584. ((= c ?!)
  10585. (setq groups (not groups))
  10586. (goto-char (point-min))
  10587. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  10588. ((= c ?\C-c)
  10589. (if (not expert)
  10590. (org-fast-tag-show-exit
  10591. (setq exit-after-next (not exit-after-next)))
  10592. (setq expert nil)
  10593. (delete-other-windows)
  10594. (set-window-buffer (split-window-vertically) " *Org tags*")
  10595. (org-switch-to-buffer-other-window " *Org tags*")
  10596. (org-fit-window-to-buffer)))
  10597. ((or (= c ?\C-g)
  10598. (and (= c ?q) (not (rassoc c ntable))))
  10599. (delete-overlay org-tags-overlay)
  10600. (setq quit-flag t))
  10601. ((= c ?\ )
  10602. (setq current nil)
  10603. (when exit-after-next (setq exit-after-next 'now)))
  10604. ((= c ?\t)
  10605. (condition-case nil
  10606. (unless tab-tags
  10607. (setq tab-tags
  10608. (delq nil
  10609. (mapcar (lambda (x)
  10610. (let ((item (car-safe x)))
  10611. (and (stringp item)
  10612. (list item))))
  10613. (org--tag-add-to-alist
  10614. (with-current-buffer buf
  10615. (org-get-buffer-tags))
  10616. table))))))
  10617. (setq tg (completing-read "Tag: " tab-tags))
  10618. (when (string-match "\\S-" tg)
  10619. (cl-pushnew (list tg) tab-tags :test #'equal)
  10620. (if (member tg current)
  10621. (setq current (delete tg current))
  10622. (push tg current)))
  10623. (when exit-after-next (setq exit-after-next 'now)))
  10624. ((setq e (rassoc c todo-table) tg (car e))
  10625. (with-current-buffer buf
  10626. (save-excursion (org-todo tg)))
  10627. (when exit-after-next (setq exit-after-next 'now)))
  10628. ((setq e (rassoc c ntable) tg (car e))
  10629. (if (member tg current)
  10630. (setq current (delete tg current))
  10631. (cl-loop for g in groups do
  10632. (when (member tg g)
  10633. (dolist (x g) (setq current (delete x current)))))
  10634. (push tg current))
  10635. (when exit-after-next (setq exit-after-next 'now))))
  10636. ;; Create a sorted list
  10637. (setq current
  10638. (sort current
  10639. (lambda (a b)
  10640. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  10641. (when (eq exit-after-next 'now) (throw 'exit t))
  10642. (goto-char (point-min))
  10643. (beginning-of-line 2)
  10644. (delete-region (point) (point-at-eol))
  10645. (org-fast-tag-insert "Current" current c-face)
  10646. (org-set-current-tags-overlay current ov-prefix)
  10647. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  10648. (while (re-search-forward tag-re nil t)
  10649. (let ((tag (match-string 1)))
  10650. (add-text-properties
  10651. (match-beginning 1) (match-end 1)
  10652. (list 'face
  10653. (cond
  10654. ((member tag current) c-face)
  10655. ((member tag inherited) i-face)
  10656. (t 'default)))))))
  10657. (goto-char (point-min)))))
  10658. (delete-overlay org-tags-overlay)
  10659. (if rtn
  10660. (mapconcat 'identity current ":")
  10661. nil)))))
  10662. (defun org-make-tag-string (tags)
  10663. "Return string associated to TAGS.
  10664. TAGS is a list of strings."
  10665. (if (null tags) ""
  10666. (format ":%s:" (mapconcat #'identity tags ":"))))
  10667. (defun org--get-local-tags ()
  10668. "Return list of tags for the current headline.
  10669. Assume point is at the beginning of the headline."
  10670. (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  10671. (cached-tags (org-element-property :tags cached)))
  10672. (if cached
  10673. ;; If we do not explicitly copy the result, reference would
  10674. ;; be returned and cache element might be modified directly.
  10675. (mapcar #'copy-sequence cached-tags)
  10676. ;; Parse tags manually.
  10677. (and (looking-at org-tag-line-re)
  10678. (split-string (match-string-no-properties 2) ":" t)))))
  10679. (defun org-get-tags (&optional pos-or-element local)
  10680. "Get the list of tags specified in the current headline.
  10681. When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  10682. POS.
  10683. According to `org-use-tag-inheritance', tags may be inherited
  10684. from parent headlines, and from the whole document, through
  10685. `org-file-tags'. In this case, the returned list of tags
  10686. contains tags in this order: file tags, tags inherited from
  10687. parent headlines, local tags. If a tag appears multiple times,
  10688. only the most local tag is returned.
  10689. However, when optional argument LOCAL is non-nil, only return
  10690. tags specified at the headline.
  10691. Inherited tags have the `inherited' text property."
  10692. (save-match-data
  10693. (if (and org-trust-scanner-tags
  10694. (or (not pos-or-element) (eq pos-or-element (point)))
  10695. (not local))
  10696. org-scanner-tags
  10697. (org-with-point-at (unless (org-element-type pos-or-element)
  10698. (or pos-or-element (point)))
  10699. (unless (or (org-element-type pos-or-element)
  10700. (org-before-first-heading-p))
  10701. (org-back-to-heading t))
  10702. (let ((ltags (if (org-element-type pos-or-element)
  10703. (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  10704. (org--get-local-tags)))
  10705. itags)
  10706. (if (or local (not org-use-tag-inheritance)) ltags
  10707. (let ((cached (and (org-element--cache-active-p)
  10708. (if (org-element-type pos-or-element)
  10709. (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  10710. (org-element-at-point nil 'cached)))))
  10711. (if cached
  10712. (while (setq cached (org-element-property :parent cached))
  10713. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10714. ;; If we do explicitly copy the result, reference would
  10715. ;; be returned and cache element might be modified directly.
  10716. (mapcar #'copy-sequence (org-element-property :tags cached)))
  10717. itags)))
  10718. (while (org-up-heading-safe)
  10719. (setq itags (nconc (mapcar #'org-add-prop-inherited
  10720. (org--get-local-tags))
  10721. itags)))))
  10722. (setq itags (append org-file-tags itags))
  10723. (nreverse
  10724. (delete-dups
  10725. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  10726. (defun org-get-buffer-tags ()
  10727. "Get a table of all tags used in the buffer, for completion."
  10728. (if (org-element--cache-active-p)
  10729. ;; `org-element-cache-map' is about 2x faster compared to regexp
  10730. ;; search.
  10731. (let ((hashed (make-hash-table :test #'equal)))
  10732. (org-element-cache-map
  10733. (lambda (el)
  10734. (dolist (tag (org-element-property :tags el))
  10735. (puthash (list tag) t hashed))))
  10736. (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  10737. (hash-table-keys hashed))
  10738. (org-with-point-at 1
  10739. (let (tags)
  10740. (while (re-search-forward org-tag-line-re nil t)
  10741. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  10742. tags)))
  10743. (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  10744. ;;;; The mapping API
  10745. (defvar org-agenda-skip-comment-trees)
  10746. (defvar org-agenda-skip-function)
  10747. (defun org-map-entries (func &optional match scope &rest skip)
  10748. "Call FUNC at each headline selected by MATCH in SCOPE.
  10749. FUNC is a function or a Lisp form. The function will be called without
  10750. arguments, with the cursor positioned at the beginning of the headline.
  10751. The return values of all calls to the function will be collected and
  10752. returned as a list.
  10753. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  10754. does not need to preserve point. After evaluation, the cursor will be
  10755. moved to the end of the line (presumably of the headline of the
  10756. processed entry) and search continues from there. Under some
  10757. circumstances, this may not produce the wanted results. For example,
  10758. if you have removed (e.g. archived) the current (sub)tree it could
  10759. mean that the next entry will be skipped entirely. In such cases, you
  10760. can specify the position from where search should continue by making
  10761. FUNC set the variable `org-map-continue-from' to the desired buffer
  10762. position.
  10763. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  10764. Only headlines that are matched by this query will be considered during
  10765. the iteration. When MATCH is nil or t, all headlines will be
  10766. visited by the iteration.
  10767. SCOPE determines the scope of this command. It can be any of:
  10768. nil The current buffer, respecting the restriction if any
  10769. tree The subtree started with the entry at point
  10770. region The entries within the active region, if any
  10771. region-start-level
  10772. The entries within the active region, but only those at
  10773. the same level than the first one.
  10774. file The current buffer, without restriction
  10775. file-with-archives
  10776. The current buffer, and any archives associated with it
  10777. agenda All agenda files
  10778. agenda-with-archives
  10779. All agenda files with any archive files associated with them
  10780. \(file1 file2 ...)
  10781. If this is a list, all files in the list will be scanned
  10782. The remaining args are treated as settings for the skipping facilities of
  10783. the scanner. The following items can be given here:
  10784. archive skip trees with the archive tag
  10785. comment skip trees with the COMMENT keyword
  10786. function or Emacs Lisp form:
  10787. will be used as value for `org-agenda-skip-function', so
  10788. whenever the function returns a position, FUNC will not be
  10789. called for that entry and search will continue from the
  10790. position returned
  10791. If your function needs to retrieve the tags including inherited tags
  10792. at the *current* entry, you can use the value of the variable
  10793. `org-scanner-tags' which will be much faster than getting the value
  10794. with `org-get-tags'. If your function gets properties with
  10795. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  10796. to t around the call to `org-entry-properties' to get the same speedup.
  10797. Note that if your function moves around to retrieve tags and properties at
  10798. a *different* entry, you cannot use these techniques."
  10799. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  10800. (not (org-region-active-p)))
  10801. (let* ((org-agenda-archives-mode nil) ; just to make sure
  10802. (org-agenda-skip-archived-trees (memq 'archive skip))
  10803. (org-agenda-skip-comment-trees (memq 'comment skip))
  10804. (org-agenda-skip-function
  10805. (car (org-delete-all '(comment archive) skip)))
  10806. (org-tags-match-list-sublevels t)
  10807. (start-level (eq scope 'region-start-level))
  10808. matcher res
  10809. org-todo-keywords-for-agenda
  10810. org-done-keywords-for-agenda
  10811. org-todo-keyword-alist-for-agenda
  10812. org-tag-alist-for-agenda
  10813. org--matcher-tags-todo-only)
  10814. (cond
  10815. ((eq match t) (setq matcher t))
  10816. ((eq match nil) (setq matcher t))
  10817. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  10818. (save-excursion
  10819. (save-restriction
  10820. (cond ((eq scope 'tree)
  10821. (org-back-to-heading t)
  10822. (org-narrow-to-subtree)
  10823. (setq scope nil))
  10824. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  10825. (org-region-active-p))
  10826. ;; If needed, set start-level to a string like "2"
  10827. (when start-level
  10828. (save-excursion
  10829. (goto-char (region-beginning))
  10830. (unless (org-at-heading-p) (outline-next-heading))
  10831. (setq start-level (org-current-level))))
  10832. (narrow-to-region (region-beginning)
  10833. (save-excursion
  10834. (goto-char (region-end))
  10835. (unless (and (bolp) (org-at-heading-p))
  10836. (outline-next-heading))
  10837. (point)))
  10838. (setq scope nil)))
  10839. (if (not scope)
  10840. (progn
  10841. (org-agenda-prepare-buffers
  10842. (and buffer-file-name (list buffer-file-name)))
  10843. (setq res
  10844. (org-scan-tags
  10845. func matcher org--matcher-tags-todo-only start-level)))
  10846. ;; Get the right scope
  10847. (cond
  10848. ((and scope (listp scope) (symbolp (car scope)))
  10849. (setq scope (eval scope t)))
  10850. ((eq scope 'agenda)
  10851. (setq scope (org-agenda-files t)))
  10852. ((eq scope 'agenda-with-archives)
  10853. (setq scope (org-agenda-files t))
  10854. (setq scope (org-add-archive-files scope)))
  10855. ((eq scope 'file)
  10856. (setq scope (and buffer-file-name (list buffer-file-name))))
  10857. ((eq scope 'file-with-archives)
  10858. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  10859. (org-agenda-prepare-buffers scope)
  10860. (dolist (file scope)
  10861. (with-current-buffer (org-find-base-buffer-visiting file)
  10862. (org-with-wide-buffer
  10863. (goto-char (point-min))
  10864. (setq res
  10865. (append
  10866. res
  10867. (org-scan-tags
  10868. func matcher org--matcher-tags-todo-only)))))))))
  10869. res)))
  10870. ;;; Properties API
  10871. (defconst org-special-properties
  10872. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  10873. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  10874. "The special properties valid in Org mode.
  10875. These are properties that are not defined in the property drawer,
  10876. but in some other way.")
  10877. (defconst org-default-properties
  10878. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  10879. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  10880. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  10881. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  10882. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  10883. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  10884. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  10885. "Some properties that are used by Org mode for various purposes.
  10886. Being in this list makes sure that they are offered for completion.")
  10887. (defun org--valid-property-p (property)
  10888. "Non-nil when string PROPERTY is a valid property name."
  10889. (not
  10890. (or (equal property "")
  10891. (string-match-p "\\s-" property))))
  10892. (defun org--update-property-plist (key val props)
  10893. "Associate KEY to VAL in alist PROPS.
  10894. Modifications are made by side-effect. Return new alist."
  10895. (let* ((appending (string= (substring key -1) "+"))
  10896. (key (if appending (substring key 0 -1) key))
  10897. (old (assoc-string key props t)))
  10898. (if (not old) (cons (cons key val) props)
  10899. (setcdr old (if appending (concat (cdr old) " " val) val))
  10900. props)))
  10901. (defun org-get-property-block (&optional beg force)
  10902. "Return the (beg . end) range of the body of the property drawer.
  10903. BEG is the beginning of the current subtree or the beginning of
  10904. the document if before the first headline. If it is not given,
  10905. it will be found. If the drawer does not exist, create it if
  10906. FORCE is non-nil, or return nil."
  10907. (org-with-wide-buffer
  10908. (let ((beg (cond (beg (goto-char beg))
  10909. ((or (not (featurep 'org-inlinetask))
  10910. (org-inlinetask-in-task-p))
  10911. (org-back-to-heading-or-point-min t) (point))
  10912. (t (org-with-limited-levels
  10913. (org-back-to-heading-or-point-min t))
  10914. (point)))))
  10915. ;; Move point to its position according to its positional rules.
  10916. (cond ((org-before-first-heading-p)
  10917. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  10918. (t (forward-line)
  10919. (when (looking-at-p org-planning-line-re) (forward-line))))
  10920. (cond ((looking-at org-property-drawer-re)
  10921. (forward-line)
  10922. (cons (point) (progn (goto-char (match-end 0))
  10923. (line-beginning-position))))
  10924. (force
  10925. (goto-char beg)
  10926. (org-insert-property-drawer)
  10927. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  10928. (line-beginning-position))))
  10929. (cons pos pos)))))))
  10930. (defun org-at-property-drawer-p ()
  10931. "Non-nil when point is at the first line of a property drawer."
  10932. (org-with-wide-buffer
  10933. (beginning-of-line)
  10934. (and (looking-at org-property-drawer-re)
  10935. (or (bobp)
  10936. (progn
  10937. (forward-line -1)
  10938. (cond ((org-at-heading-p))
  10939. ((looking-at org-planning-line-re)
  10940. (forward-line -1)
  10941. (org-at-heading-p))
  10942. ((looking-at org-comment-regexp)
  10943. (forward-line -1)
  10944. (while (and (not (bobp)) (looking-at org-comment-regexp))
  10945. (forward-line -1))
  10946. (looking-at org-comment-regexp))
  10947. (t nil)))))))
  10948. (defun org-at-property-p ()
  10949. "Non-nil when point is inside a property drawer.
  10950. See `org-property-re' for match data, if applicable."
  10951. (save-excursion
  10952. (beginning-of-line)
  10953. (and (looking-at org-property-re)
  10954. (let ((property-drawer (save-match-data (org-get-property-block))))
  10955. (and property-drawer
  10956. (>= (point) (car property-drawer))
  10957. (< (point) (cdr property-drawer)))))))
  10958. (defun org-property-action ()
  10959. "Do an action on properties."
  10960. (interactive)
  10961. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  10962. (let ((c (read-char-exclusive)))
  10963. (cl-case c
  10964. (?s (call-interactively #'org-set-property))
  10965. (?d (call-interactively #'org-delete-property))
  10966. (?D (call-interactively #'org-delete-property-globally))
  10967. (?c (call-interactively #'org-compute-property-at-point))
  10968. (otherwise (user-error "No such property action %c" c)))))
  10969. (defun org-inc-effort ()
  10970. "Increment the value of the effort property in the current entry."
  10971. (interactive)
  10972. (org-set-effort t))
  10973. (defvar org-clock-effort) ; Defined in org-clock.el.
  10974. (defvar org-clock-current-task) ; Defined in org-clock.el.
  10975. (defun org-set-effort (&optional increment value)
  10976. "Set the effort property of the current entry.
  10977. If INCREMENT is non-nil, set the property to the next allowed
  10978. value. Otherwise, if optional argument VALUE is provided, use
  10979. it. Eventually, prompt for the new value if none of the previous
  10980. variables is set."
  10981. (interactive "P")
  10982. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  10983. (current (org-entry-get nil org-effort-property))
  10984. (value
  10985. (cond
  10986. (increment
  10987. (unless allowed (user-error "Allowed effort values are not set"))
  10988. (or (cl-caadr (member (list current) allowed))
  10989. (user-error "Unknown value %S among allowed values" current)))
  10990. (value
  10991. (if (stringp value) value
  10992. (error "Invalid effort value: %S" value)))
  10993. (t
  10994. (let ((must-match
  10995. (and allowed
  10996. (not (get-text-property 0 'org-unrestricted
  10997. (caar allowed))))))
  10998. (completing-read "Effort: " allowed nil must-match))))))
  10999. ;; Test whether the value can be interpreted as a duration before
  11000. ;; inserting it in the buffer:
  11001. (org-duration-to-minutes value)
  11002. ;; Maybe update the effort value:
  11003. (unless (equal current value)
  11004. (org-entry-put nil org-effort-property value))
  11005. (unless (org-element--cache-active-p)
  11006. (org-refresh-property '((effort . identity)
  11007. (effort-minutes . org-duration-to-minutes))
  11008. value))
  11009. (when (equal (org-get-heading t t t t)
  11010. (bound-and-true-p org-clock-current-task))
  11011. (setq org-clock-effort value)
  11012. (org-clock-update-mode-line))
  11013. (message "%s is now %s" org-effort-property value)))
  11014. (defun org-entry-properties (&optional pom which)
  11015. "Get all properties of the current entry.
  11016. When POM is a buffer position, get all properties from the entry
  11017. there instead.
  11018. This includes the TODO keyword, the tags, time strings for
  11019. deadline, scheduled, and clocking, and any additional properties
  11020. defined in the entry.
  11021. If WHICH is nil or `all', get all properties. If WHICH is
  11022. `special' or `standard', only get that subclass. If WHICH is
  11023. a string, only get that property.
  11024. Return value is an alist. Keys are properties, as upcased
  11025. strings."
  11026. (org-with-point-at pom
  11027. (when (and (derived-mode-p 'org-mode)
  11028. (org-back-to-heading-or-point-min t))
  11029. (catch 'exit
  11030. (let* ((beg (point))
  11031. (specific (and (stringp which) (upcase which)))
  11032. (which (cond ((not specific) which)
  11033. ((member specific org-special-properties) 'special)
  11034. (t 'standard)))
  11035. props)
  11036. ;; Get the special properties, like TODO and TAGS.
  11037. (when (memq which '(nil all special))
  11038. (when (or (not specific) (string= specific "CLOCKSUM"))
  11039. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11040. (when clocksum
  11041. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11042. props)))
  11043. (when specific (throw 'exit props)))
  11044. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11045. (let ((clocksumt (get-text-property (point)
  11046. :org-clock-minutes-today)))
  11047. (when clocksumt
  11048. (push (cons "CLOCKSUM_T"
  11049. (org-duration-from-minutes clocksumt))
  11050. props)))
  11051. (when specific (throw 'exit props)))
  11052. (when (or (not specific) (string= specific "ITEM"))
  11053. (let ((case-fold-search nil))
  11054. (when (looking-at org-complex-heading-regexp)
  11055. (push (cons "ITEM"
  11056. (let ((title (match-string-no-properties 4)))
  11057. (if (org-string-nw-p title)
  11058. (org-remove-tabs title)
  11059. "")))
  11060. props)))
  11061. (when specific (throw 'exit props)))
  11062. (when (or (not specific) (string= specific "TODO"))
  11063. (let ((case-fold-search nil))
  11064. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11065. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11066. (when specific (throw 'exit props)))
  11067. (when (or (not specific) (string= specific "PRIORITY"))
  11068. (push (cons "PRIORITY"
  11069. (if (looking-at org-priority-regexp)
  11070. (match-string-no-properties 2)
  11071. (char-to-string org-priority-default)))
  11072. props)
  11073. (when specific (throw 'exit props)))
  11074. (when (or (not specific) (string= specific "FILE"))
  11075. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11076. props)
  11077. (when specific (throw 'exit props)))
  11078. (when (or (not specific) (string= specific "TAGS"))
  11079. (let ((tags (org-get-tags nil t)))
  11080. (when tags
  11081. (push (cons "TAGS" (org-make-tag-string tags))
  11082. props)))
  11083. (when specific (throw 'exit props)))
  11084. (when (or (not specific) (string= specific "ALLTAGS"))
  11085. (let ((tags (org-get-tags)))
  11086. (when tags
  11087. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11088. props)))
  11089. (when specific (throw 'exit props)))
  11090. (when (or (not specific) (string= specific "BLOCKED"))
  11091. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11092. (when specific (throw 'exit props)))
  11093. (when (or (not specific)
  11094. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11095. (forward-line)
  11096. (when (looking-at-p org-planning-line-re)
  11097. (end-of-line)
  11098. (let ((bol (line-beginning-position))
  11099. ;; Backward compatibility: time keywords used to
  11100. ;; be configurable (before 8.3). Make sure we
  11101. ;; get the correct keyword.
  11102. (key-assoc `(("CLOSED" . ,org-closed-string)
  11103. ("DEADLINE" . ,org-deadline-string)
  11104. ("SCHEDULED" . ,org-scheduled-string))))
  11105. (dolist (pair (if specific (list (assoc specific key-assoc))
  11106. key-assoc))
  11107. (save-excursion
  11108. (when (search-backward (cdr pair) bol t)
  11109. (goto-char (match-end 0))
  11110. (skip-chars-forward " \t")
  11111. (and (looking-at org-ts-regexp-both)
  11112. (push (cons (car pair)
  11113. (match-string-no-properties 0))
  11114. props)))))))
  11115. (when specific (throw 'exit props)))
  11116. (when (or (not specific)
  11117. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11118. (let ((find-ts
  11119. (lambda (end ts)
  11120. ;; Fix next time-stamp before END. TS is the
  11121. ;; list of time-stamps found so far.
  11122. (let ((ts ts)
  11123. (regexp (cond
  11124. ((string= specific "TIMESTAMP")
  11125. org-ts-regexp)
  11126. ((string= specific "TIMESTAMP_IA")
  11127. org-ts-regexp-inactive)
  11128. ((assoc "TIMESTAMP_IA" ts)
  11129. org-ts-regexp)
  11130. ((assoc "TIMESTAMP" ts)
  11131. org-ts-regexp-inactive)
  11132. (t org-ts-regexp-both))))
  11133. (catch 'next
  11134. (while (re-search-forward regexp end t)
  11135. (backward-char)
  11136. (let ((object (org-element-context)))
  11137. ;; Accept to match timestamps in node
  11138. ;; properties, too.
  11139. (when (memq (org-element-type object)
  11140. '(node-property timestamp))
  11141. (let ((type
  11142. (org-element-property :type object)))
  11143. (cond
  11144. ((and (memq type '(active active-range))
  11145. (not (equal specific "TIMESTAMP_IA")))
  11146. (unless (assoc "TIMESTAMP" ts)
  11147. (push (cons "TIMESTAMP"
  11148. (org-element-property
  11149. :raw-value object))
  11150. ts)
  11151. (when specific (throw 'exit ts))))
  11152. ((and (memq type '(inactive inactive-range))
  11153. (not (string= specific "TIMESTAMP")))
  11154. (unless (assoc "TIMESTAMP_IA" ts)
  11155. (push (cons "TIMESTAMP_IA"
  11156. (org-element-property
  11157. :raw-value object))
  11158. ts)
  11159. (when specific (throw 'exit ts))))))
  11160. ;; Both timestamp types are found,
  11161. ;; move to next part.
  11162. (when (= (length ts) 2) (throw 'next ts)))))
  11163. ts)))))
  11164. (goto-char beg)
  11165. ;; First look for timestamps within headline.
  11166. (let ((ts (funcall find-ts (line-end-position) nil)))
  11167. (if (= (length ts) 2) (setq props (nconc ts props))
  11168. ;; Then find timestamps in the section, skipping
  11169. ;; planning line.
  11170. (let ((end (save-excursion (outline-next-heading))))
  11171. (forward-line)
  11172. (when (looking-at-p org-planning-line-re) (forward-line))
  11173. (setq props (nconc (funcall find-ts end ts) props))))))))
  11174. ;; Get the standard properties, like :PROP:.
  11175. (when (memq which '(nil all standard))
  11176. ;; If we are looking after a specific property, delegate
  11177. ;; to `org-entry-get', which is faster. However, make an
  11178. ;; exception for "CATEGORY", since it can be also set
  11179. ;; through keywords (i.e. #+CATEGORY).
  11180. (if (and specific (not (equal specific "CATEGORY")))
  11181. (let ((value (org-entry-get beg specific nil t)))
  11182. (throw 'exit (and value (list (cons specific value)))))
  11183. (let ((range (org-get-property-block beg)))
  11184. (when range
  11185. (let ((end (cdr range)) seen-base)
  11186. (goto-char (car range))
  11187. ;; Unlike to `org--update-property-plist', we
  11188. ;; handle the case where base values is found
  11189. ;; after its extension. We also forbid standard
  11190. ;; properties to be named as special properties.
  11191. (while (re-search-forward org-property-re end t)
  11192. (let* ((key (upcase (match-string-no-properties 2)))
  11193. (extendp (string-match-p "\\+\\'" key))
  11194. (key-base (if extendp (substring key 0 -1) key))
  11195. (value (match-string-no-properties 3)))
  11196. (cond
  11197. ((member-ignore-case key-base org-special-properties))
  11198. (extendp
  11199. (setq props
  11200. (org--update-property-plist key value props)))
  11201. ((member key seen-base))
  11202. (t (push key seen-base)
  11203. (let ((p (assoc-string key props t)))
  11204. (if p (setcdr p (concat value " " (cdr p)))
  11205. (push (cons key value) props))))))))))))
  11206. (unless (assoc "CATEGORY" props)
  11207. (push (cons "CATEGORY" (org-get-category beg)) props)
  11208. (when (string= specific "CATEGORY") (throw 'exit props)))
  11209. ;; Return value.
  11210. props)))))
  11211. (defun org--property-local-values (property literal-nil &optional element)
  11212. "Return value for PROPERTY in current entry or ELEMENT.
  11213. Value is a list whose car is the base value for PROPERTY and cdr
  11214. a list of accumulated values. Return nil if neither is found in
  11215. the entry. Also return nil when PROPERTY is set to \"nil\",
  11216. unless LITERAL-NIL is non-nil."
  11217. (let ((element (or element
  11218. (and (org-element--cache-active-p)
  11219. (org-element-at-point nil 'cached)))))
  11220. (if element
  11221. (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  11222. (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  11223. (base-value (if literal-nil base-value (org-not-nil base-value)))
  11224. (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  11225. (extra-value (if (listp extra-value) extra-value (list extra-value)))
  11226. (value (cons base-value extra-value)))
  11227. (and (not (equal value '(nil))) value))
  11228. (let ((range (org-get-property-block)))
  11229. (when range
  11230. (goto-char (car range))
  11231. (let* ((case-fold-search t)
  11232. (end (cdr range))
  11233. (value
  11234. ;; Base value.
  11235. (save-excursion
  11236. (let ((v (and (re-search-forward
  11237. (org-re-property property nil t) end t)
  11238. (match-string-no-properties 3))))
  11239. (list (if literal-nil v (org-not-nil v)))))))
  11240. ;; Find additional values.
  11241. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11242. (while (re-search-forward property+ end t)
  11243. (push (match-string-no-properties 3) value)))
  11244. ;; Return final values.
  11245. (and (not (equal value '(nil))) (nreverse value))))))))
  11246. (defun org--property-global-or-keyword-value (property literal-nil)
  11247. "Return value for PROPERTY as defined by global properties or by keyword.
  11248. Return value is a string. Return nil if property is not set
  11249. globally or by keyword. Also return nil when PROPERTY is set to
  11250. \"nil\", unless LITERAL-NIL is non-nil."
  11251. (let ((global
  11252. (cdr (or (assoc-string property org-keyword-properties t)
  11253. (assoc-string property org-global-properties t)
  11254. (assoc-string property org-global-properties-fixed t)))))
  11255. (if literal-nil global (org-not-nil global))))
  11256. (defun org-entry-get (pom property &optional inherit literal-nil)
  11257. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11258. If INHERIT is non-nil and the entry does not have the property,
  11259. then also check higher levels of the hierarchy. If INHERIT is
  11260. the symbol `selective', use inheritance only if the setting in
  11261. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11262. If the property is present but empty, the return value is the
  11263. empty string. If the property is not present at all, nil is
  11264. returned. In any other case, return the value as a string.
  11265. Search is case-insensitive.
  11266. If LITERAL-NIL is set, return the string value \"nil\" as
  11267. a string, do not interpret it as the list atom nil. This is used
  11268. for inheritance when a \"nil\" value can supersede a non-nil
  11269. value higher up the hierarchy."
  11270. (org-with-point-at pom
  11271. (cond
  11272. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11273. ;; We need a special property. Use `org-entry-properties' to
  11274. ;; retrieve it, but specify the wanted property.
  11275. (cdr (assoc-string property (org-entry-properties nil property))))
  11276. ((and inherit
  11277. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11278. (org-entry-get-with-inheritance property literal-nil))
  11279. (t
  11280. (let* ((local (org--property-local-values property literal-nil))
  11281. (value (and local (mapconcat #'identity
  11282. (delq nil local)
  11283. (org--property-get-separator property)))))
  11284. (if literal-nil value (org-not-nil value)))))))
  11285. (defun org-property-or-variable-value (var &optional inherit)
  11286. "Check if there is a property fixing the value of VAR.
  11287. If yes, return this value. If not, return the current value of the variable."
  11288. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11289. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11290. (read prop)
  11291. (symbol-value var))))
  11292. (defun org-entry-delete (pom property)
  11293. "Delete PROPERTY from entry at point-or-marker POM.
  11294. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11295. non-nil when a property was removed."
  11296. (org-with-point-at pom
  11297. (pcase (org-get-property-block)
  11298. (`(,begin . ,origin)
  11299. (let* ((end (copy-marker origin))
  11300. (re (org-re-property
  11301. (concat (regexp-quote property) "\\+?") t t)))
  11302. (goto-char begin)
  11303. (while (re-search-forward re end t)
  11304. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11305. ;; If drawer is empty, remove it altogether.
  11306. (when (= begin end)
  11307. (delete-region (line-beginning-position 0)
  11308. (line-beginning-position 2)))
  11309. ;; Return non-nil if some property was removed.
  11310. (prog1 (/= end origin) (set-marker end nil))))
  11311. (_ nil))))
  11312. ;; Multi-values properties are properties that contain multiple values
  11313. ;; These values are assumed to be single words, separated by whitespace.
  11314. (defun org-entry-add-to-multivalued-property (pom property value)
  11315. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11316. (let* ((old (org-entry-get pom property))
  11317. (values (and old (split-string old))))
  11318. (setq value (org-entry-protect-space value))
  11319. (unless (member value values)
  11320. (setq values (append values (list value)))
  11321. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11322. (defun org-entry-remove-from-multivalued-property (pom property value)
  11323. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11324. (let* ((old (org-entry-get pom property))
  11325. (values (and old (split-string old))))
  11326. (setq value (org-entry-protect-space value))
  11327. (when (member value values)
  11328. (setq values (delete value values))
  11329. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11330. (defun org-entry-member-in-multivalued-property (pom property value)
  11331. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11332. (let* ((old (org-entry-get pom property))
  11333. (values (and old (split-string old))))
  11334. (setq value (org-entry-protect-space value))
  11335. (member value values)))
  11336. (defun org-entry-get-multivalued-property (pom property)
  11337. "Return a list of values in a multivalued property."
  11338. (let* ((value (org-entry-get pom property))
  11339. (values (and value (split-string value))))
  11340. (mapcar #'org-entry-restore-space values)))
  11341. (defun org-entry-put-multivalued-property (pom property &rest values)
  11342. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11343. VALUES should be a list of strings. Spaces will be protected."
  11344. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11345. (let* ((value (org-entry-get pom property))
  11346. (values (and value (split-string value))))
  11347. (mapcar #'org-entry-restore-space values)))
  11348. (defun org-entry-protect-space (s)
  11349. "Protect spaces and newline in string S."
  11350. (while (string-match " " s)
  11351. (setq s (replace-match "%20" t t s)))
  11352. (while (string-match "\n" s)
  11353. (setq s (replace-match "%0A" t t s)))
  11354. s)
  11355. (defun org-entry-restore-space (s)
  11356. "Restore spaces and newline in string S."
  11357. (while (string-match "%20" s)
  11358. (setq s (replace-match " " t t s)))
  11359. (while (string-match "%0A" s)
  11360. (setq s (replace-match "\n" t t s)))
  11361. s)
  11362. (defvar org-entry-property-inherited-from (make-marker)
  11363. "Marker pointing to the entry from where a property was inherited.
  11364. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11365. location of the entry where the inheritance search matched. If there was
  11366. no match, the marker will point nowhere.
  11367. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11368. is set.")
  11369. (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  11370. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11371. The search will stop at the first ancestor which has the property defined.
  11372. If the value found is \"nil\", return nil to show that the property
  11373. should be considered as undefined (this is the meaning of nil here).
  11374. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11375. (move-marker org-entry-property-inherited-from nil)
  11376. (org-with-wide-buffer
  11377. (let (value at-bob-no-heading)
  11378. (catch 'exit
  11379. (let ((element (or element
  11380. (and (org-element--cache-active-p)
  11381. (org-element-at-point nil 'cached))))
  11382. (separator (org--property-get-separator property)))
  11383. (if element
  11384. (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  11385. (while t
  11386. (let* ((v (org--property-local-values property literal-nil element))
  11387. (v (if (listp v) v (list v))))
  11388. (when v
  11389. (setq value
  11390. (concat (mapconcat #'identity (delq nil v) separator)
  11391. (and value separator)
  11392. value)))
  11393. (cond
  11394. ((car v)
  11395. (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  11396. (throw 'exit nil))
  11397. ((org-element-property :parent element)
  11398. (setq element (org-element-property :parent element)))
  11399. (t
  11400. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11401. (cond ((not global))
  11402. (value (setq value (concat global separator value)))
  11403. (t (setq value global))))
  11404. (throw 'exit nil))))))
  11405. (while t
  11406. (let ((v (org--property-local-values property literal-nil)))
  11407. (when v
  11408. (setq value
  11409. (concat (mapconcat #'identity (delq nil v) separator)
  11410. (and value separator)
  11411. value)))
  11412. (cond
  11413. ((car v)
  11414. (org-back-to-heading-or-point-min t)
  11415. (move-marker org-entry-property-inherited-from (point))
  11416. (throw 'exit nil))
  11417. ((or (org-up-heading-safe)
  11418. (and (not (bobp))
  11419. (goto-char (point-min))
  11420. nil)
  11421. ;; `org-up-heading-safe' returned nil. We are at low
  11422. ;; level heading or bob. If there is headline
  11423. ;; there, do not try to fetch its properties.
  11424. (and (bobp)
  11425. (not at-bob-no-heading)
  11426. (not (org-at-heading-p))
  11427. (setq at-bob-no-heading t))))
  11428. (t
  11429. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11430. (cond ((not global))
  11431. (value (setq value (concat global separator value)))
  11432. (t (setq value global))))
  11433. (throw 'exit nil))))))))
  11434. (if literal-nil value (org-not-nil value)))))
  11435. (defvar org-property-changed-functions nil
  11436. "Hook called when the value of a property has changed.
  11437. Each hook function should accept two arguments, the name of the property
  11438. and the new value.")
  11439. (defun org-entry-put (pom property value)
  11440. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11441. If the value is nil, it is converted to the empty string. If it
  11442. is not a string, an error is raised. Also raise an error on
  11443. invalid property names.
  11444. PROPERTY can be any regular property (see
  11445. `org-special-properties'). It can also be \"TODO\",
  11446. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11447. For the last two properties, VALUE may have any of the special
  11448. values \"earlier\" and \"later\". The function then increases or
  11449. decreases scheduled or deadline date by one day."
  11450. (cond ((null value) (setq value ""))
  11451. ((not (stringp value)) (error "Properties values should be strings"))
  11452. ((not (org--valid-property-p property))
  11453. (user-error "Invalid property name: \"%s\"" property)))
  11454. (org-no-read-only
  11455. (org-with-point-at pom
  11456. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11457. (org-back-to-heading-or-point-min t)
  11458. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11459. (let ((beg (point)))
  11460. (cond
  11461. ((equal property "TODO")
  11462. (cond ((not (org-string-nw-p value)) (setq value 'none))
  11463. ((not (member value org-todo-keywords-1))
  11464. (user-error "\"%s\" is not a valid TODO state" value)))
  11465. (org-todo value)
  11466. (org-align-tags))
  11467. ((equal property "PRIORITY")
  11468. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  11469. (org-align-tags))
  11470. ((equal property "SCHEDULED")
  11471. (forward-line)
  11472. (if (and (looking-at-p org-planning-line-re)
  11473. (re-search-forward
  11474. org-scheduled-time-regexp (line-end-position) t))
  11475. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11476. ((string= value "later") (org-timestamp-change 1 'day))
  11477. ((string= value "") (org-schedule '(4)))
  11478. (t (org-schedule nil value)))
  11479. (if (member value '("earlier" "later" ""))
  11480. (call-interactively #'org-schedule)
  11481. (org-schedule nil value))))
  11482. ((equal property "DEADLINE")
  11483. (forward-line)
  11484. (if (and (looking-at-p org-planning-line-re)
  11485. (re-search-forward
  11486. org-deadline-time-regexp (line-end-position) t))
  11487. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  11488. ((string= value "later") (org-timestamp-change 1 'day))
  11489. ((string= value "") (org-deadline '(4)))
  11490. (t (org-deadline nil value)))
  11491. (if (member value '("earlier" "later" ""))
  11492. (call-interactively #'org-deadline)
  11493. (org-deadline nil value))))
  11494. ((member property org-special-properties)
  11495. (error "The %s property cannot be set with `org-entry-put'" property))
  11496. (t
  11497. (org-fold-core-ignore-modifications
  11498. (let* ((range (org-get-property-block beg 'force))
  11499. (end (cdr range))
  11500. (case-fold-search t))
  11501. (goto-char (car range))
  11502. (if (re-search-forward (org-re-property property nil t) end t)
  11503. (progn (delete-region (match-beginning 0) (match-end 0))
  11504. (goto-char (match-beginning 0)))
  11505. (goto-char end)
  11506. (insert-and-inherit "\n")
  11507. (backward-char))
  11508. (insert-and-inherit ":" property ":")
  11509. (when value (insert-and-inherit " " value))
  11510. (org-indent-line))))))
  11511. (run-hook-with-args 'org-property-changed-functions property value))))
  11512. (defun org-buffer-property-keys (&optional specials defaults columns)
  11513. "Get all property keys in the current buffer.
  11514. When SPECIALS is non-nil, also list the special properties that
  11515. reflect things like tags and TODO state.
  11516. When DEFAULTS is non-nil, also include properties that has
  11517. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  11518. DESCRIPTION, LOCATION, and LOGGING and others.
  11519. When COLUMNS in non-nil, also include property names given in
  11520. COLUMN formats in the current buffer."
  11521. (let ((case-fold-search t)
  11522. (props (append
  11523. (and specials org-special-properties)
  11524. (and defaults (cons org-effort-property org-default-properties))
  11525. ;; Get property names from #+PROPERTY keywords as well
  11526. (mapcar (lambda (s)
  11527. (nth 0 (split-string s)))
  11528. (cdar (org-collect-keywords '("PROPERTY")))))))
  11529. (org-with-wide-buffer
  11530. (goto-char (point-min))
  11531. (while (re-search-forward org-property-start-re nil t)
  11532. (catch :skip
  11533. (let ((range (org-get-property-block)))
  11534. (unless range (throw :skip nil))
  11535. (goto-char (car range))
  11536. (let ((begin (car range))
  11537. (end (cdr range)))
  11538. ;; Make sure that found property block is not located
  11539. ;; before current point, as it would generate an infloop.
  11540. ;; It can happen, for example, in the following
  11541. ;; situation:
  11542. ;;
  11543. ;; * Headline
  11544. ;; :PROPERTIES:
  11545. ;; ...
  11546. ;; :END:
  11547. ;; *************** Inlinetask
  11548. ;; #+BEGIN_EXAMPLE
  11549. ;; :PROPERTIES:
  11550. ;; #+END_EXAMPLE
  11551. ;;
  11552. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  11553. (while (< (point) end)
  11554. (let ((p (progn (looking-at org-property-re)
  11555. (match-string-no-properties 2))))
  11556. ;; Only add true property name, not extension symbol.
  11557. (push (if (not (string-match-p "\\+\\'" p)) p
  11558. (substring p 0 -1))
  11559. props))
  11560. (forward-line))))
  11561. (outline-next-heading)))
  11562. (when columns
  11563. (goto-char (point-min))
  11564. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  11565. (let ((element (org-element-at-point)))
  11566. (when (memq (org-element-type element) '(keyword node-property))
  11567. (let ((value (org-element-property :value element))
  11568. (start 0))
  11569. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  11570. \\(?:{[^}]+}\\)?"
  11571. value start)
  11572. (setq start (match-end 0))
  11573. (let ((p (match-string-no-properties 1 value)))
  11574. (unless (member-ignore-case p org-special-properties)
  11575. (push p props))))))))))
  11576. (sort (delete-dups
  11577. (append props
  11578. ;; for each xxx_ALL property, make sure the bare
  11579. ;; xxx property is also included
  11580. (delq nil (mapcar (lambda (p)
  11581. (and (string-match-p "._ALL\\'" p)
  11582. (substring p 0 -4)))
  11583. props))))
  11584. (lambda (a b) (string< (upcase a) (upcase b))))))
  11585. (defun org-property-values (key)
  11586. "List all non-nil values of property KEY in current buffer."
  11587. (org-with-wide-buffer
  11588. (goto-char (point-min))
  11589. (let ((case-fold-search t)
  11590. (re (org-re-property key))
  11591. values)
  11592. (while (re-search-forward re nil t)
  11593. (push (org-entry-get (point) key) values))
  11594. (delete-dups values))))
  11595. (defun org-insert-property-drawer ()
  11596. "Insert a property drawer into the current entry.
  11597. Do nothing if the drawer already exists. The newly created
  11598. drawer is immediately hidden."
  11599. (org-with-wide-buffer
  11600. ;; Set point to the position where the drawer should be inserted.
  11601. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  11602. (org-back-to-heading-or-point-min t)
  11603. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  11604. (if (org-before-first-heading-p)
  11605. (while (and (org-at-comment-p) (bolp)) (forward-line))
  11606. (forward-line)
  11607. (when (looking-at-p org-planning-line-re) (forward-line)))
  11608. (unless (looking-at-p org-property-drawer-re)
  11609. ;; Make sure we start editing a line from current entry, not from
  11610. ;; next one. It prevents extending text properties or overlays
  11611. ;; belonging to the latter.
  11612. (when (and (bolp) (> (point) (point-min))) (backward-char))
  11613. (let ((begin (if (bobp) (point) (1+ (point))))
  11614. (inhibit-read-only t))
  11615. (unless (bobp) (insert "\n"))
  11616. (insert ":PROPERTIES:\n:END:")
  11617. (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  11618. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  11619. (org-indent-region begin (point))))))
  11620. (defun org-insert-drawer (&optional arg drawer)
  11621. "Insert a drawer at point.
  11622. When optional argument ARG is non-nil, insert a property drawer.
  11623. Optional argument DRAWER, when non-nil, is a string representing
  11624. drawer's name. Otherwise, the user is prompted for a name.
  11625. If a region is active, insert the drawer around that region
  11626. instead.
  11627. Point is left between drawer's boundaries."
  11628. (interactive "P")
  11629. (let* ((drawer (if arg "PROPERTIES"
  11630. (or drawer (read-from-minibuffer "Drawer: ")))))
  11631. (cond
  11632. ;; With C-u, fall back on `org-insert-property-drawer'
  11633. (arg (org-insert-property-drawer))
  11634. ;; Check validity of suggested drawer's name.
  11635. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  11636. (user-error "Invalid drawer name"))
  11637. ;; With an active region, insert a drawer at point.
  11638. ((not (org-region-active-p))
  11639. (progn
  11640. (unless (bolp) (insert "\n"))
  11641. (insert (format ":%s:\n\n:END:\n" drawer))
  11642. (forward-line -2)))
  11643. ;; Otherwise, insert the drawer at point
  11644. (t
  11645. (let ((rbeg (region-beginning))
  11646. (rend (copy-marker (region-end))))
  11647. (unwind-protect
  11648. (progn
  11649. (goto-char rbeg)
  11650. (beginning-of-line)
  11651. (when (save-excursion
  11652. (re-search-forward org-outline-regexp-bol rend t))
  11653. (user-error "Drawers cannot contain headlines"))
  11654. ;; Position point at the beginning of the first
  11655. ;; non-blank line in region. Insert drawer's opening
  11656. ;; there, then indent it.
  11657. (org-skip-whitespace)
  11658. (beginning-of-line)
  11659. (insert ":" drawer ":\n")
  11660. (forward-line -1)
  11661. (indent-for-tab-command)
  11662. ;; Move point to the beginning of the first blank line
  11663. ;; after the last non-blank line in region. Insert
  11664. ;; drawer's closing, then indent it.
  11665. (goto-char rend)
  11666. (skip-chars-backward " \r\t\n")
  11667. (insert "\n:END:")
  11668. (deactivate-mark t)
  11669. (indent-for-tab-command)
  11670. (unless (eolp) (insert "\n")))
  11671. ;; Clear marker, whatever the outcome of insertion is.
  11672. (set-marker rend nil)))))))
  11673. (defvar org-property-set-functions-alist nil
  11674. "Property set function alist.
  11675. Each entry should have the following format:
  11676. (PROPERTY . READ-FUNCTION)
  11677. The read function will be called with the same argument as
  11678. `org-completing-read'.")
  11679. (defun org-set-property-function (property)
  11680. "Get the function that should be used to set PROPERTY.
  11681. This is computed according to `org-property-set-functions-alist'."
  11682. (or (cdr (assoc property org-property-set-functions-alist))
  11683. 'org-completing-read))
  11684. (defun org-read-property-value (property &optional pom default)
  11685. "Read value for PROPERTY, as a string.
  11686. When optional argument POM is non-nil, completion uses additional
  11687. information, i.e., allowed or existing values at point or marker
  11688. POM.
  11689. Optional argument DEFAULT provides a default value for PROPERTY."
  11690. (let* ((completion-ignore-case t)
  11691. (allowed
  11692. (or (org-property-get-allowed-values nil property 'table)
  11693. (and pom (org-property-get-allowed-values pom property 'table))))
  11694. (current (org-entry-get nil property))
  11695. (prompt (format "%s value%s: "
  11696. property
  11697. (if (org-string-nw-p current)
  11698. (format " [%s]" current)
  11699. "")))
  11700. (set-function (org-set-property-function property)))
  11701. (org-trim
  11702. (if allowed
  11703. (funcall set-function
  11704. prompt allowed nil
  11705. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  11706. default nil default)
  11707. (let ((all (mapcar #'list
  11708. (append (org-property-values property)
  11709. (and pom
  11710. (org-with-point-at pom
  11711. (org-property-values property)))))))
  11712. (funcall set-function prompt all nil nil "" nil current))))))
  11713. (defvar org-last-set-property nil)
  11714. (defvar org-last-set-property-value nil)
  11715. (defun org-read-property-name ()
  11716. "Read a property name."
  11717. (let ((completion-ignore-case t)
  11718. (default-prop (or (and (org-at-property-p)
  11719. (match-string-no-properties 2))
  11720. org-last-set-property)))
  11721. (org-completing-read
  11722. (concat "Property"
  11723. (if default-prop (concat " [" default-prop "]") "")
  11724. ": ")
  11725. (mapcar #'list (org-buffer-property-keys nil t t))
  11726. nil nil nil nil default-prop)))
  11727. (defun org-set-property-and-value (use-last)
  11728. "Allow to set [PROPERTY]: [value] direction from prompt.
  11729. When use-default, don't even ask, just use the last
  11730. \"[PROPERTY]: [value]\" string from the history."
  11731. (interactive "P")
  11732. (let* ((completion-ignore-case t)
  11733. (pv (or (and use-last org-last-set-property-value)
  11734. (org-completing-read
  11735. "Enter a \"[Property]: [value]\" pair: "
  11736. nil nil nil nil nil
  11737. org-last-set-property-value)))
  11738. prop val)
  11739. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  11740. (setq prop (match-string 1 pv)
  11741. val (match-string 2 pv))
  11742. (org-set-property prop val))))
  11743. (defun org-set-property (property value)
  11744. "In the current entry, set PROPERTY to VALUE.
  11745. When called interactively, this will prompt for a property name, offering
  11746. completion on existing and default properties. And then it will prompt
  11747. for a value, offering completion either on allowed values (via an inherited
  11748. xxx_ALL property) or on existing values in other instances of this property
  11749. in the current file.
  11750. Throw an error when trying to set a property with an invalid name."
  11751. (interactive (list nil nil))
  11752. (let ((property (or property (org-read-property-name))))
  11753. ;; `org-entry-put' also makes the following check, but this one
  11754. ;; avoids polluting `org-last-set-property' and
  11755. ;; `org-last-set-property-value' needlessly.
  11756. (unless (org--valid-property-p property)
  11757. (user-error "Invalid property name: \"%s\"" property))
  11758. (let ((value (or value (org-read-property-value property)))
  11759. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  11760. (setq org-last-set-property property)
  11761. (setq org-last-set-property-value (concat property ": " value))
  11762. ;; Possibly postprocess the inserted value:
  11763. (when fn (setq value (funcall fn value)))
  11764. (unless (equal (org-entry-get nil property) value)
  11765. (org-entry-put nil property value)))))
  11766. (defun org-find-property (property &optional value)
  11767. "Find first entry in buffer that sets PROPERTY.
  11768. When optional argument VALUE is non-nil, only consider an entry
  11769. if it contains PROPERTY set to this value. If PROPERTY should be
  11770. explicitly set to nil, use string \"nil\" for VALUE.
  11771. Return position where the entry begins, or nil if there is no
  11772. such entry. If narrowing is in effect, only search the visible
  11773. part of the buffer."
  11774. (save-excursion
  11775. (goto-char (point-min))
  11776. (let ((case-fold-search t)
  11777. (re (org-re-property property nil (not value) value)))
  11778. (catch 'exit
  11779. (while (re-search-forward re nil t)
  11780. (when (if value (org-at-property-p)
  11781. (org-entry-get (point) property nil t))
  11782. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  11783. (point)))))))))
  11784. (defun org-delete-property (property)
  11785. "In the current entry, delete PROPERTY."
  11786. (interactive
  11787. (let* ((completion-ignore-case t)
  11788. (cat (org-entry-get (point) "CATEGORY"))
  11789. (props0 (org-entry-properties nil 'standard))
  11790. (props (if cat props0
  11791. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  11792. (prop (if (< 1 (length props))
  11793. (completing-read "Property: " props nil t)
  11794. (caar props))))
  11795. (list prop)))
  11796. (if (not property)
  11797. (message "No property to delete in this entry")
  11798. (org-entry-delete nil property)
  11799. (message "Property \"%s\" deleted" property)))
  11800. (defun org-delete-property-globally (property)
  11801. "Remove PROPERTY globally, from all entries.
  11802. This function ignores narrowing, if any."
  11803. (interactive
  11804. (let* ((completion-ignore-case t)
  11805. (prop (completing-read
  11806. "Globally remove property: "
  11807. (mapcar #'list (org-buffer-property-keys)))))
  11808. (list prop)))
  11809. (org-with-wide-buffer
  11810. (goto-char (point-min))
  11811. (let ((count 0)
  11812. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  11813. (while (re-search-forward re nil t)
  11814. (when (org-entry-delete (point) property) (cl-incf count)))
  11815. (message "Property \"%s\" removed from %d entries" property count))))
  11816. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  11817. (defun org-compute-property-at-point ()
  11818. "Compute the property at point.
  11819. This looks for an enclosing column format, extracts the operator and
  11820. then applies it to the property in the column format's scope."
  11821. (interactive)
  11822. (unless (org-at-property-p)
  11823. (user-error "Not at a property"))
  11824. (let ((prop (match-string-no-properties 2)))
  11825. (org-columns-get-format-and-top-level)
  11826. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  11827. (user-error "No operator defined for property %s" prop))
  11828. (org-columns-compute prop)))
  11829. (defvar org-property-allowed-value-functions nil
  11830. "Hook for functions supplying allowed values for a specific property.
  11831. The functions must take a single argument, the name of the property, and
  11832. return a flat list of allowed values. If \":ETC\" is one of
  11833. the values, this means that these values are intended as defaults for
  11834. completion, but that other values should be allowed too.
  11835. The functions must return nil if they are not responsible for this
  11836. property.")
  11837. (defun org-property-get-allowed-values (pom property &optional table)
  11838. "Get allowed values for the property PROPERTY.
  11839. When TABLE is non-nil, return an alist that can directly be used for
  11840. completion."
  11841. (let (vals)
  11842. (cond
  11843. ((equal property "TODO")
  11844. (setq vals (org-with-point-at pom
  11845. (append org-todo-keywords-1 '("")))))
  11846. ((equal property "PRIORITY")
  11847. (let ((n org-priority-lowest))
  11848. (while (>= n org-priority-highest)
  11849. (push (char-to-string n) vals)
  11850. (setq n (1- n)))))
  11851. ((equal property "CATEGORY"))
  11852. ((member property org-special-properties))
  11853. ((setq vals (run-hook-with-args-until-success
  11854. 'org-property-allowed-value-functions property)))
  11855. (t
  11856. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  11857. (when (and vals (string-match "\\S-" vals))
  11858. (setq vals (car (read-from-string (concat "(" vals ")"))))
  11859. (setq vals (mapcar (lambda (x)
  11860. (cond ((stringp x) x)
  11861. ((numberp x) (number-to-string x))
  11862. ((symbolp x) (symbol-name x))
  11863. (t "???")))
  11864. vals)))))
  11865. (when (member ":ETC" vals)
  11866. (setq vals (remove ":ETC" vals))
  11867. (org-add-props (car vals) '(org-unrestricted t)))
  11868. (if table (mapcar 'list vals) vals)))
  11869. (defun org-property-previous-allowed-value (&optional _previous)
  11870. "Switch to the next allowed value for this property."
  11871. (interactive)
  11872. (org-property-next-allowed-value t))
  11873. (defun org-property-next-allowed-value (&optional previous)
  11874. "Switch to the next allowed value for this property."
  11875. (interactive)
  11876. (unless (org-at-property-p)
  11877. (user-error "Not at a property"))
  11878. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  11879. (key (match-string 2))
  11880. (value (match-string 3))
  11881. (allowed (or (org-property-get-allowed-values (point) key)
  11882. (and (member value '("[ ]" "[-]" "[X]"))
  11883. '("[ ]" "[X]"))))
  11884. (heading (save-match-data (nth 4 (org-heading-components))))
  11885. nval)
  11886. (unless allowed
  11887. (user-error "Allowed values for this property have not been defined"))
  11888. (when previous (setq allowed (reverse allowed)))
  11889. (when (member value allowed)
  11890. (setq nval (car (cdr (member value allowed)))))
  11891. (setq nval (or nval (car allowed)))
  11892. (when (equal nval value)
  11893. (user-error "Only one allowed value for this property"))
  11894. (org-at-property-p)
  11895. (replace-match (concat " :" key ": " nval) t t)
  11896. (org-indent-line)
  11897. (beginning-of-line 1)
  11898. (skip-chars-forward " \t")
  11899. (when (equal prop org-effort-property)
  11900. (unless (org-element--cache-active-p)
  11901. (org-refresh-property
  11902. '((effort . identity)
  11903. (effort-minutes . org-duration-to-minutes))
  11904. nval))
  11905. (when (string= org-clock-current-task heading)
  11906. (setq org-clock-effort nval)
  11907. (org-clock-update-mode-line)))
  11908. (run-hook-with-args 'org-property-changed-functions key nval)))
  11909. (defun org-find-olp (path &optional this-buffer)
  11910. "Return a marker pointing to the entry at outline path OLP.
  11911. If anything goes wrong, throw an error, and if you need to do
  11912. something based on this error, you can catch it with
  11913. `condition-case'.
  11914. If THIS-BUFFER is set, the outline path does not contain a file,
  11915. only headings."
  11916. (let* ((file (if this-buffer buffer-file-name (pop path)))
  11917. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  11918. (level 1)
  11919. (lmin 1)
  11920. (lmax 1)
  11921. end found flevel)
  11922. (unless buffer (error "File not found :%s" file))
  11923. (with-current-buffer buffer
  11924. (unless (derived-mode-p 'org-mode)
  11925. (error "Buffer %s needs to be in Org mode" buffer))
  11926. (org-with-wide-buffer
  11927. (goto-char (point-min))
  11928. (dolist (heading path)
  11929. (let ((re (format org-complex-heading-regexp-format
  11930. (regexp-quote heading)))
  11931. (cnt 0))
  11932. (while (re-search-forward re end t)
  11933. (setq level (- (match-end 1) (match-beginning 1)))
  11934. (when (and (>= level lmin) (<= level lmax))
  11935. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  11936. (when (= cnt 0)
  11937. (error "Heading not found on level %d: %s" lmax heading))
  11938. (when (> cnt 1)
  11939. (error "Heading not unique on level %d: %s" lmax heading))
  11940. (goto-char found)
  11941. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  11942. (setq end (save-excursion (org-end-of-subtree t t)))))
  11943. (when (org-at-heading-p)
  11944. (point-marker))))))
  11945. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  11946. "Find node HEADING in BUFFER.
  11947. Return a marker to the heading if it was found, or nil if not.
  11948. If POS-ONLY is set, return just the position instead of a marker.
  11949. The heading text must match exact, but it may have a TODO keyword,
  11950. a priority cookie and tags in the standard locations."
  11951. (with-current-buffer (or buffer (current-buffer))
  11952. (org-with-wide-buffer
  11953. (goto-char (point-min))
  11954. (let (case-fold-search)
  11955. (when (re-search-forward
  11956. (format org-complex-heading-regexp-format
  11957. (regexp-quote heading)) nil t)
  11958. (if pos-only
  11959. (match-beginning 0)
  11960. (move-marker (make-marker) (match-beginning 0))))))))
  11961. (defun org-find-exact-heading-in-directory (heading &optional dir)
  11962. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  11963. When the target headline is found, return a marker to this location."
  11964. (let ((files (directory-files (or dir default-directory)
  11965. t "\\`[^.#].*\\.org\\'"))
  11966. visiting m buffer)
  11967. (catch 'found
  11968. (dolist (file files)
  11969. (message "trying %s" file)
  11970. (setq visiting (org-find-base-buffer-visiting file))
  11971. (setq buffer (or visiting (find-file-noselect file)))
  11972. (setq m (org-find-exact-headline-in-buffer
  11973. heading buffer))
  11974. (when (and (not m) (not visiting)) (kill-buffer buffer))
  11975. (and m (throw 'found m))))))
  11976. (defun org-find-entry-with-id (ident)
  11977. "Locate the entry that contains the ID property with exact value IDENT.
  11978. IDENT can be a string, a symbol or a number, this function will search for
  11979. the string representation of it.
  11980. Return the position where this entry starts, or nil if there is no such entry."
  11981. (interactive "sID: ")
  11982. (let ((id (cond
  11983. ((stringp ident) ident)
  11984. ((symbolp ident) (symbol-name ident))
  11985. ((numberp ident) (number-to-string ident))
  11986. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  11987. (org-with-wide-buffer (org-find-property "ID" id))))
  11988. ;;;; Timestamps
  11989. (defvar org-last-changed-timestamp nil)
  11990. (defvar org-last-inserted-timestamp nil
  11991. "The last time stamp inserted with `org-insert-time-stamp'.")
  11992. (defun org-time-stamp (arg &optional inactive)
  11993. "Prompt for a date/time and insert a time stamp.
  11994. If the user specifies a time like HH:MM or if this command is
  11995. called with at least one prefix argument, the time stamp contains
  11996. the date and the time. Otherwise, only the date is included.
  11997. All parts of a date not specified by the user are filled in from
  11998. the timestamp at point, if any, or the current date/time
  11999. otherwise.
  12000. If there is already a timestamp at the cursor, it is replaced.
  12001. With two universal prefix arguments, insert an active timestamp
  12002. with the current time without prompting the user.
  12003. When called from Lisp, the timestamp is inactive if INACTIVE is
  12004. non-nil."
  12005. (interactive "P")
  12006. (let* ((ts (cond
  12007. ((org-at-date-range-p t)
  12008. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12009. ((org-at-timestamp-p 'lax) (match-string 0))))
  12010. ;; Default time is either the timestamp at point or today.
  12011. ;; When entering a range, only the range start is considered.
  12012. (default-time (and ts (org-time-string-to-time ts)))
  12013. (default-input (and ts (org-get-compact-tod ts)))
  12014. (repeater (and ts
  12015. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12016. (match-string 0 ts)))
  12017. org-time-was-given
  12018. org-end-time-was-given
  12019. (time
  12020. (if (equal arg '(16)) (current-time)
  12021. ;; Preserve `this-command' and `last-command'.
  12022. (let ((this-command this-command)
  12023. (last-command last-command))
  12024. (org-read-date
  12025. arg 'totime nil nil default-time default-input
  12026. inactive)))))
  12027. (cond
  12028. ((and ts
  12029. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12030. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12031. (insert "--")
  12032. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12033. (ts
  12034. ;; Make sure we're on a timestamp. When in the middle of a date
  12035. ;; range, move arbitrarily to range end.
  12036. (unless (org-at-timestamp-p 'lax)
  12037. (skip-chars-forward "-")
  12038. (org-at-timestamp-p 'lax))
  12039. (replace-match "")
  12040. (setq org-last-changed-timestamp
  12041. (org-insert-time-stamp
  12042. time (or org-time-was-given arg)
  12043. inactive nil nil (list org-end-time-was-given)))
  12044. (when repeater
  12045. (backward-char)
  12046. (insert " " repeater)
  12047. (setq org-last-changed-timestamp
  12048. (concat (substring org-last-inserted-timestamp 0 -1)
  12049. " " repeater ">")))
  12050. (message "Timestamp updated"))
  12051. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12052. (t (org-insert-time-stamp
  12053. time (or org-time-was-given arg) inactive nil nil
  12054. (list org-end-time-was-given))))))
  12055. ;; FIXME: can we use this for something else, like computing time differences?
  12056. (defun org-get-compact-tod (s)
  12057. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12058. (let* ((t1 (match-string 1 s))
  12059. (h1 (string-to-number (match-string 2 s)))
  12060. (m1 (string-to-number (match-string 3 s)))
  12061. (t2 (and (match-end 4) (match-string 5 s)))
  12062. (h2 (and t2 (string-to-number (match-string 6 s))))
  12063. (m2 (and t2 (string-to-number (match-string 7 s))))
  12064. dh dm)
  12065. (if (not t2)
  12066. t1
  12067. (setq dh (- h2 h1) dm (- m2 m1))
  12068. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12069. (concat t1 "+" (number-to-string dh)
  12070. (and (/= 0 dm) (format ":%02d" dm)))))))
  12071. (defun org-time-stamp-inactive (&optional arg)
  12072. "Insert an inactive time stamp.
  12073. An inactive time stamp is enclosed in square brackets instead of
  12074. angle brackets. It is inactive in the sense that it does not
  12075. trigger agenda entries. So these are more for recording a
  12076. certain time/date.
  12077. If the user specifies a time like HH:MM or if this command is called with
  12078. at least one prefix argument, the time stamp contains the date and the time.
  12079. Otherwise, only the date is included.
  12080. When called with two universal prefix arguments, insert an inactive time stamp
  12081. with the current time without prompting the user."
  12082. (interactive "P")
  12083. (org-time-stamp arg 'inactive))
  12084. (defvar org-date-ovl (make-overlay 1 1))
  12085. (overlay-put org-date-ovl 'face 'org-date-selected)
  12086. (delete-overlay org-date-ovl)
  12087. (defvar org-ans1) ; dynamically scoped parameter
  12088. (defvar org-ans2) ; dynamically scoped parameter
  12089. (defvar org-plain-time-of-day-regexp) ; defined below
  12090. (defvar org-overriding-default-time nil) ; dynamically scoped
  12091. (defvar org-read-date-overlay nil)
  12092. (defvar org-read-date-history nil)
  12093. (defvar org-read-date-final-answer nil)
  12094. (defvar org-read-date-analyze-futurep nil)
  12095. (defvar org-read-date-analyze-forced-year nil)
  12096. (defvar org-read-date-inactive)
  12097. (defvar org-def)
  12098. (defvar org-defdecode)
  12099. (defvar org-with-time)
  12100. (defvar calendar-setup) ; Dynamically scoped.
  12101. (defun org-read-date (&optional with-time to-time from-string prompt
  12102. default-time default-input inactive)
  12103. "Read a date, possibly a time, and make things smooth for the user.
  12104. The prompt will suggest to enter an ISO date, but you can also enter anything
  12105. which will at least partially be understood by `parse-time-string'.
  12106. Unrecognized parts of the date will default to the current day, month, year,
  12107. hour and minute. If this command is called to replace a timestamp at point,
  12108. or to enter the second timestamp of a range, the default time is taken
  12109. from the existing stamp. Furthermore, the command prefers the future,
  12110. so if you are giving a date where the year is not given, and the day-month
  12111. combination is already past in the current year, it will assume you
  12112. mean next year. For details, see the manual. A few examples:
  12113. 3-2-5 --> 2003-02-05
  12114. feb 15 --> currentyear-02-15
  12115. 2/15 --> currentyear-02-15
  12116. sep 12 9 --> 2009-09-12
  12117. 12:45 --> today 12:45
  12118. 22 sept 0:34 --> currentyear-09-22 0:34
  12119. 12 --> currentyear-currentmonth-12
  12120. Fri --> nearest Friday after today
  12121. -Tue --> last Tuesday
  12122. etc.
  12123. Furthermore you can specify a relative date by giving, as the *first* thing
  12124. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12125. change in days weeks, months, years.
  12126. With a single plus or minus, the date is relative to today. With a double
  12127. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12128. +4d --> four days from today
  12129. +4 --> same as above
  12130. +2w --> two weeks from today
  12131. ++5 --> five days from default date
  12132. The function understands only English month and weekday abbreviations.
  12133. While prompting, a calendar is popped up - you can also select the
  12134. date with the mouse (button 1). The calendar shows a period of three
  12135. months. To scroll it to other months, use the keys `>' and `<'.
  12136. If you don't like the calendar, turn it off with
  12137. (setq org-read-date-popup-calendar nil)
  12138. With optional argument TO-TIME, the date will immediately be converted
  12139. to an internal time.
  12140. With an optional argument WITH-TIME, the prompt will suggest to
  12141. also insert a time. Note that when WITH-TIME is not set, you can
  12142. still enter a time, and this function will inform the calling routine
  12143. about this change. The calling routine may then choose to change the
  12144. format used to insert the time stamp into the buffer to include the time.
  12145. With optional argument FROM-STRING, read from this string instead from
  12146. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12147. the time/date that is used for everything that is not specified by the
  12148. user."
  12149. (require 'parse-time)
  12150. (let* ((org-with-time with-time)
  12151. (org-time-stamp-rounding-minutes
  12152. (if (equal org-with-time '(16))
  12153. '(0 0)
  12154. org-time-stamp-rounding-minutes))
  12155. (ct (org-current-time))
  12156. (org-def (or org-overriding-default-time default-time ct))
  12157. (org-defdecode (decode-time org-def))
  12158. (cur-frame (selected-frame))
  12159. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12160. (calendar-setup
  12161. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12162. (calendar-move-hook nil)
  12163. (calendar-view-diary-initially-flag nil)
  12164. (calendar-view-holidays-initially-flag nil)
  12165. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12166. ;; Rationalize `org-def' and `org-defdecode', if required.
  12167. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12168. (setf (nth 2 org-defdecode) -1)
  12169. (setf (nth 1 org-defdecode) 59)
  12170. (setq org-def (apply #'encode-time org-defdecode))
  12171. (setq org-defdecode (decode-time org-def)))
  12172. (let* ((timestr (format-time-string
  12173. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12174. org-def))
  12175. (prompt (concat (if prompt (concat prompt " ") "")
  12176. (format "Date+time [%s]: " timestr))))
  12177. (cond
  12178. (from-string (setq ans from-string))
  12179. (org-read-date-popup-calendar
  12180. (save-excursion
  12181. (save-window-excursion
  12182. (calendar)
  12183. (when (eq calendar-setup 'calendar-only)
  12184. (setq cal-frame
  12185. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12186. (select-frame cal-frame))
  12187. (org-eval-in-calendar '(setq cursor-type nil) t)
  12188. (unwind-protect
  12189. (progn
  12190. (calendar-forward-day (- (time-to-days org-def)
  12191. (calendar-absolute-from-gregorian
  12192. (calendar-current-date))))
  12193. (org-eval-in-calendar nil t)
  12194. (let* ((old-map (current-local-map))
  12195. (map (copy-keymap calendar-mode-map))
  12196. (minibuffer-local-map
  12197. (copy-keymap org-read-date-minibuffer-local-map)))
  12198. (org-defkey map (kbd "RET") 'org-calendar-select)
  12199. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12200. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12201. (unwind-protect
  12202. (progn
  12203. (use-local-map map)
  12204. (setq org-read-date-inactive inactive)
  12205. (add-hook 'post-command-hook 'org-read-date-display)
  12206. (setq org-ans0
  12207. (read-string prompt
  12208. default-input
  12209. 'org-read-date-history
  12210. nil))
  12211. ;; org-ans0: from prompt
  12212. ;; org-ans1: from mouse click
  12213. ;; org-ans2: from calendar motion
  12214. (setq ans
  12215. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12216. (remove-hook 'post-command-hook 'org-read-date-display)
  12217. (use-local-map old-map)
  12218. (when org-read-date-overlay
  12219. (delete-overlay org-read-date-overlay)
  12220. (setq org-read-date-overlay nil)))))
  12221. (bury-buffer "*Calendar*")
  12222. (when cal-frame
  12223. (delete-frame cal-frame)
  12224. (select-frame-set-input-focus cur-frame))))))
  12225. (t ; Naked prompt only
  12226. (unwind-protect
  12227. (setq ans (read-string prompt default-input
  12228. 'org-read-date-history timestr))
  12229. (when org-read-date-overlay
  12230. (delete-overlay org-read-date-overlay)
  12231. (setq org-read-date-overlay nil))))))
  12232. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12233. (when org-read-date-analyze-forced-year
  12234. (message "Year was forced into %s"
  12235. (if org-read-date-force-compatible-dates
  12236. "compatible range (1970-2037)"
  12237. "range representable on this machine"))
  12238. (ding))
  12239. (setq final (apply #'encode-time final))
  12240. (setq org-read-date-final-answer ans)
  12241. (if to-time
  12242. final
  12243. ;; This round-trip gets rid of 34th of August and stuff like that....
  12244. (setq final (decode-time final))
  12245. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12246. (format "%04d-%02d-%02d %02d:%02d"
  12247. (nth 5 final) (nth 4 final) (nth 3 final)
  12248. (nth 2 final) (nth 1 final))
  12249. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12250. (defun org-read-date-display ()
  12251. "Display the current date prompt interpretation in the minibuffer."
  12252. (when org-read-date-display-live
  12253. (when org-read-date-overlay
  12254. (delete-overlay org-read-date-overlay))
  12255. (when (minibufferp (current-buffer))
  12256. (save-excursion
  12257. (end-of-line 1)
  12258. (while (not (equal (buffer-substring
  12259. (max (point-min) (- (point) 4)) (point))
  12260. " "))
  12261. (insert " ")))
  12262. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12263. " " (or org-ans1 org-ans2)))
  12264. (org-end-time-was-given nil)
  12265. (f (org-read-date-analyze ans org-def org-defdecode))
  12266. (fmts (if org-display-custom-times
  12267. org-time-stamp-custom-formats
  12268. org-time-stamp-formats))
  12269. (fmt (if (or org-with-time
  12270. (and (boundp 'org-time-was-given) org-time-was-given))
  12271. (cdr fmts)
  12272. (car fmts)))
  12273. (txt (format-time-string fmt (apply #'encode-time f)))
  12274. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12275. (txt (concat "=> " txt)))
  12276. (when (and org-end-time-was-given
  12277. (string-match org-plain-time-of-day-regexp txt))
  12278. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12279. org-end-time-was-given
  12280. (substring txt (match-end 0)))))
  12281. (when org-read-date-analyze-futurep
  12282. (setq txt (concat txt " (=>F)")))
  12283. (setq org-read-date-overlay
  12284. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12285. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12286. (defun org-read-date-analyze (ans def defdecode)
  12287. "Analyze the combined answer of the date prompt."
  12288. ;; FIXME: cleanup and comment
  12289. (let ((org-def def)
  12290. (org-defdecode defdecode)
  12291. (nowdecode (decode-time))
  12292. delta deltan deltaw deltadef year month day
  12293. hour minute second wday pm h2 m2 tl wday1
  12294. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12295. (setq org-read-date-analyze-futurep nil
  12296. org-read-date-analyze-forced-year nil)
  12297. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12298. (setq ans "+0"))
  12299. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12300. (setq ans (replace-match "" t t ans)
  12301. deltan (car delta)
  12302. deltaw (nth 1 delta)
  12303. deltadef (nth 2 delta)))
  12304. ;; Check if there is an iso week date in there. If yes, store the
  12305. ;; info and postpone interpreting it until the rest of the parsing
  12306. ;; is done.
  12307. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12308. (setq iso-year (when (match-end 1)
  12309. (org-small-year-to-year
  12310. (string-to-number (match-string 1 ans))))
  12311. iso-weekday (when (match-end 3)
  12312. (string-to-number (match-string 3 ans)))
  12313. iso-week (string-to-number (match-string 2 ans)))
  12314. (setq ans (replace-match "" t t ans)))
  12315. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12316. (when (string-match
  12317. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12318. (setq year (if (match-end 2)
  12319. (string-to-number (match-string 2 ans))
  12320. (progn (setq kill-year t)
  12321. (string-to-number (format-time-string "%Y"))))
  12322. month (string-to-number (match-string 3 ans))
  12323. day (string-to-number (match-string 4 ans)))
  12324. (setq year (org-small-year-to-year year))
  12325. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12326. t nil ans)))
  12327. ;; Help matching dotted european dates
  12328. (when (string-match
  12329. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12330. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12331. (setq kill-year t)
  12332. (string-to-number (format-time-string "%Y")))
  12333. day (string-to-number (match-string 1 ans))
  12334. month (string-to-number (match-string 2 ans))
  12335. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12336. t nil ans)))
  12337. ;; Help matching american dates, like 5/30 or 5/30/7
  12338. (when (string-match
  12339. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12340. (setq year (if (match-end 4)
  12341. (string-to-number (match-string 4 ans))
  12342. (progn (setq kill-year t)
  12343. (string-to-number (format-time-string "%Y"))))
  12344. month (string-to-number (match-string 1 ans))
  12345. day (string-to-number (match-string 2 ans)))
  12346. (setq year (org-small-year-to-year year))
  12347. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12348. t nil ans)))
  12349. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12350. ;; If there is a time with am/pm, and *no* time without it, we convert
  12351. ;; so that matching will be successful.
  12352. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12353. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12354. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12355. (setq hour (string-to-number (match-string 1 ans))
  12356. minute (if (match-end 3)
  12357. (string-to-number (match-string 3 ans))
  12358. 0)
  12359. pm (equal ?p
  12360. (string-to-char (downcase (match-string 4 ans)))))
  12361. (if (and (= hour 12) (not pm))
  12362. (setq hour 0)
  12363. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12364. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12365. t t ans))))
  12366. ;; Help matching HHhMM times, similarly as for am/pm times.
  12367. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12368. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12369. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12370. (setq hour (if (match-end 1)
  12371. (string-to-number (match-string 1 ans))
  12372. 0)
  12373. minute (if (match-end 2)
  12374. (string-to-number (match-string 2 ans))
  12375. 0))
  12376. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12377. t t ans))))
  12378. ;; Check if a time range is given as a duration
  12379. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12380. (setq hour (string-to-number (match-string 1 ans))
  12381. h2 (+ hour (string-to-number (match-string 3 ans)))
  12382. minute (string-to-number (match-string 2 ans))
  12383. m2 (+ minute (if (match-end 5) (string-to-number
  12384. (match-string 5 ans))0)))
  12385. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12386. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12387. t t ans)))
  12388. ;; Check if there is a time range
  12389. (when (boundp 'org-end-time-was-given)
  12390. (setq org-time-was-given nil)
  12391. (when (and (string-match org-plain-time-of-day-regexp ans)
  12392. (match-end 8))
  12393. (setq org-end-time-was-given (match-string 8 ans))
  12394. (setq ans (concat (substring ans 0 (match-beginning 7))
  12395. (substring ans (match-end 7))))))
  12396. (setq tl (parse-time-string ans)
  12397. day (or (nth 3 tl) (nth 3 org-defdecode))
  12398. month
  12399. (cond ((nth 4 tl))
  12400. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12401. ;; Day was specified. Make sure DAY+MONTH
  12402. ;; combination happens in the future.
  12403. ((nth 3 tl)
  12404. (setq futurep t)
  12405. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12406. (nth 4 nowdecode)))
  12407. (t (nth 4 org-defdecode)))
  12408. year
  12409. (cond ((and (not kill-year) (nth 5 tl)))
  12410. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12411. ;; Month was guessed in the future and is at least
  12412. ;; equal to NOWDECODE's. Fix year accordingly.
  12413. (futurep
  12414. (if (or (> month (nth 4 nowdecode))
  12415. (>= day (nth 3 nowdecode)))
  12416. (nth 5 nowdecode)
  12417. (1+ (nth 5 nowdecode))))
  12418. ;; Month was specified. Make sure MONTH+YEAR
  12419. ;; combination happens in the future.
  12420. ((nth 4 tl)
  12421. (setq futurep t)
  12422. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12423. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12424. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12425. (t (nth 5 nowdecode))))
  12426. (t (nth 5 org-defdecode)))
  12427. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12428. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12429. second (or (nth 0 tl) 0)
  12430. wday (nth 6 tl))
  12431. (when (and (eq org-read-date-prefer-future 'time)
  12432. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12433. (equal day (nth 3 nowdecode))
  12434. (equal month (nth 4 nowdecode))
  12435. (equal year (nth 5 nowdecode))
  12436. (nth 2 tl)
  12437. (or (< (nth 2 tl) (nth 2 nowdecode))
  12438. (and (= (nth 2 tl) (nth 2 nowdecode))
  12439. (nth 1 tl)
  12440. (< (nth 1 tl) (nth 1 nowdecode)))))
  12441. (setq day (1+ day)
  12442. futurep t))
  12443. ;; Special date definitions below
  12444. (cond
  12445. (iso-week
  12446. ;; There was an iso week
  12447. (require 'cal-iso)
  12448. (setq futurep nil)
  12449. (setq year (or iso-year year)
  12450. day (or iso-weekday wday 1)
  12451. wday nil ; to make sure that the trigger below does not match
  12452. iso-date (calendar-gregorian-from-absolute
  12453. (calendar-iso-to-absolute
  12454. (list iso-week day year))))
  12455. ; FIXME: Should we also push ISO weeks into the future?
  12456. ; (when (and org-read-date-prefer-future
  12457. ; (not iso-year)
  12458. ; (< (calendar-absolute-from-gregorian iso-date)
  12459. ; (time-to-days nil)))
  12460. ; (setq year (1+ year)
  12461. ; iso-date (calendar-gregorian-from-absolute
  12462. ; (calendar-iso-to-absolute
  12463. ; (list iso-week day year)))))
  12464. (setq month (car iso-date)
  12465. year (nth 2 iso-date)
  12466. day (nth 1 iso-date)))
  12467. (deltan
  12468. (setq futurep nil)
  12469. (unless deltadef
  12470. (let ((now (decode-time)))
  12471. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  12472. (cond ((member deltaw '("h" ""))
  12473. (when (boundp 'org-time-was-given)
  12474. (setq org-time-was-given t))
  12475. (setq hour (+ hour deltan)))
  12476. ((member deltaw '("d" "")) (setq day (+ day deltan)))
  12477. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  12478. ((equal deltaw "m") (setq month (+ month deltan)))
  12479. ((equal deltaw "y") (setq year (+ year deltan)))))
  12480. ((and wday (not (nth 3 tl)))
  12481. ;; Weekday was given, but no day, so pick that day in the week
  12482. ;; on or after the derived date.
  12483. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  12484. (unless (equal wday wday1)
  12485. (setq day (+ day (% (- wday wday1 -7) 7))))))
  12486. (when (and (boundp 'org-time-was-given)
  12487. (nth 2 tl))
  12488. (setq org-time-was-given t))
  12489. (when (< year 100) (setq year (+ 2000 year)))
  12490. ;; Check of the date is representable
  12491. (if org-read-date-force-compatible-dates
  12492. (progn
  12493. (when (< year 1970)
  12494. (setq year 1970 org-read-date-analyze-forced-year t))
  12495. (when (> year 2037)
  12496. (setq year 2037 org-read-date-analyze-forced-year t)))
  12497. (condition-case nil
  12498. (ignore (encode-time second minute hour day month year))
  12499. (error
  12500. (setq year (nth 5 org-defdecode))
  12501. (setq org-read-date-analyze-forced-year t))))
  12502. (setq org-read-date-analyze-futurep futurep)
  12503. (list second minute hour day month year)))
  12504. (defvar parse-time-weekdays)
  12505. (defun org-read-date-get-relative (s today default)
  12506. "Check string S for special relative date string.
  12507. TODAY and DEFAULT are internal times, for today and for a default.
  12508. Return shift list (N what def-flag)
  12509. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  12510. N is the number of WHATs to shift.
  12511. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  12512. the DEFAULT date rather than TODAY."
  12513. (require 'parse-time)
  12514. (when (and
  12515. (string-match
  12516. (concat
  12517. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  12518. "\\([0-9]+\\)?"
  12519. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  12520. "\\([ \t]\\|$\\)") s)
  12521. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  12522. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  12523. (string-to-char (substring (match-string 1 s) -1))
  12524. ?+))
  12525. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  12526. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  12527. (what (if (match-end 3) (match-string 3 s) "d"))
  12528. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  12529. (date (if rel default today))
  12530. (wday (nth 6 (decode-time date)))
  12531. delta)
  12532. (if wday1
  12533. (progn
  12534. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  12535. (when (= delta 0) (setq delta 7))
  12536. (when (= dir ?-)
  12537. (setq delta (- delta 7))
  12538. (when (= delta 0) (setq delta -7)))
  12539. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  12540. (list delta "d" rel))
  12541. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  12542. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  12543. "Turn a user-specified date into the internal representation.
  12544. The internal representation needed by the calendar is (month day year).
  12545. This is a wrapper to handle the brain-dead convention in calendar that
  12546. user function argument order change dependent on argument order."
  12547. (pcase calendar-date-style
  12548. (`american (list arg1 arg2 arg3))
  12549. (`european (list arg2 arg1 arg3))
  12550. (`iso (list arg2 arg3 arg1))))
  12551. (defun org-eval-in-calendar (form &optional keepdate)
  12552. "Eval FORM in the calendar window and return to current window.
  12553. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  12554. (let ((sf (selected-frame))
  12555. (sw (selected-window)))
  12556. (select-window (get-buffer-window "*Calendar*" t))
  12557. (eval form t)
  12558. (when (and (not keepdate) (calendar-cursor-to-date))
  12559. (let* ((date (calendar-cursor-to-date))
  12560. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12561. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  12562. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  12563. (select-window sw)
  12564. (select-frame-set-input-focus sf)))
  12565. (defun org-calendar-select ()
  12566. "Return to `org-read-date' with the date currently selected.
  12567. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12568. (interactive)
  12569. (when (calendar-cursor-to-date)
  12570. (let* ((date (calendar-cursor-to-date))
  12571. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12572. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12573. (when (active-minibuffer-window) (exit-minibuffer))))
  12574. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  12575. "Insert a date stamp for the date given by the internal TIME.
  12576. See `format-time-string' for the format of TIME.
  12577. WITH-HM means use the stamp format that includes the time of the day.
  12578. INACTIVE means use square brackets instead of angular ones, so that the
  12579. stamp will not contribute to the agenda.
  12580. PRE and POST are optional strings to be inserted before and after the
  12581. stamp.
  12582. The command returns the inserted time stamp."
  12583. (org-fold-core-ignore-modifications
  12584. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  12585. stamp)
  12586. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  12587. (insert-before-markers-and-inherit (or pre ""))
  12588. (when (listp extra)
  12589. (setq extra (car extra))
  12590. (if (and (stringp extra)
  12591. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  12592. (setq extra (format "-%02d:%02d"
  12593. (string-to-number (match-string 1 extra))
  12594. (string-to-number (match-string 2 extra))))
  12595. (setq extra nil)))
  12596. (when extra
  12597. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  12598. (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  12599. (insert-before-markers-and-inherit (or post ""))
  12600. (setq org-last-inserted-timestamp stamp))))
  12601. (defun org-toggle-time-stamp-overlays ()
  12602. "Toggle the use of custom time stamp formats."
  12603. (interactive)
  12604. (setq org-display-custom-times (not org-display-custom-times))
  12605. (unless org-display-custom-times
  12606. (let ((p (point-min)) (bmp (buffer-modified-p)))
  12607. (while (setq p (next-single-property-change p 'display))
  12608. (when (and (get-text-property p 'display)
  12609. (eq (get-text-property p 'face) 'org-date))
  12610. (remove-text-properties
  12611. p (setq p (next-single-property-change p 'display))
  12612. '(display t))))
  12613. (set-buffer-modified-p bmp)))
  12614. (org-restart-font-lock)
  12615. (setq org-table-may-need-update t)
  12616. (if org-display-custom-times
  12617. (message "Time stamps are overlaid with custom format")
  12618. (message "Time stamp overlays removed")))
  12619. (defun org-display-custom-time (beg end)
  12620. "Overlay modified time stamp format over timestamp between BEG and END."
  12621. (let* ((ts (buffer-substring beg end))
  12622. t1 with-hm tf time str (off 0))
  12623. (save-match-data
  12624. (setq t1 (org-parse-time-string ts t))
  12625. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  12626. (setq off (- (match-end 0) (match-beginning 0)))))
  12627. (setq end (- end off))
  12628. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  12629. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  12630. time (org-fix-decoded-time t1)
  12631. str (org-add-props
  12632. (format-time-string
  12633. (substring tf 1 -1) (apply 'encode-time time))
  12634. nil 'mouse-face 'highlight))
  12635. (put-text-property beg end 'display str)))
  12636. (defun org-fix-decoded-time (time)
  12637. "Set 0 instead of nil for the first 6 elements of time.
  12638. Don't touch the rest."
  12639. (let ((n 0))
  12640. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  12641. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  12642. "Difference between TIMESTAMP-STRING and now in days.
  12643. If SECONDS is non-nil, return the difference in seconds."
  12644. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  12645. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  12646. (funcall fdiff nil))))
  12647. (defun org-deadline-close-p (timestamp-string &optional ndays)
  12648. "Is the time in TIMESTAMP-STRING close to the current date?"
  12649. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  12650. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  12651. (not (org-entry-is-done-p))))
  12652. (defun org-get-wdays (ts &optional delay zero-delay)
  12653. "Get the deadline lead time appropriate for timestring TS.
  12654. When DELAY is non-nil, get the delay time for scheduled items
  12655. instead of the deadline lead time. When ZERO-DELAY is non-nil
  12656. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  12657. don't try to find the delay cookie in the scheduled timestamp."
  12658. (let ((tv (if delay org-scheduled-delay-days
  12659. org-deadline-warning-days)))
  12660. (cond
  12661. ((or (and delay (< tv 0))
  12662. (and delay zero-delay (<= tv 0))
  12663. (and (not delay) (<= tv 0)))
  12664. ;; Enforce this value no matter what
  12665. (- tv))
  12666. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  12667. ;; lead time is specified.
  12668. (floor (* (string-to-number (match-string 1 ts))
  12669. (cdr (assoc (match-string 2 ts)
  12670. '(("d" . 1) ("w" . 7)
  12671. ("m" . 30.4) ("y" . 365.25)
  12672. ("h" . 0.041667)))))))
  12673. ;; go for the default.
  12674. (t tv))))
  12675. (defun org-calendar-select-mouse (ev)
  12676. "Return to `org-read-date' with the date currently selected.
  12677. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  12678. (interactive "e")
  12679. (mouse-set-point ev)
  12680. (when (calendar-cursor-to-date)
  12681. (let* ((date (calendar-cursor-to-date))
  12682. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  12683. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  12684. (when (active-minibuffer-window) (exit-minibuffer))))
  12685. (defun org-check-deadlines (ndays)
  12686. "Check if there are any deadlines due or past due.
  12687. A deadline is considered due if it happens within `org-deadline-warning-days'
  12688. days from today's date. If the deadline appears in an entry marked DONE,
  12689. it is not shown. A numeric prefix argument NDAYS can be used to test that
  12690. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  12691. are shown."
  12692. (interactive "P")
  12693. (let* ((org-warn-days
  12694. (cond
  12695. ((equal ndays '(4)) 100000)
  12696. (ndays (prefix-numeric-value ndays))
  12697. (t (abs org-deadline-warning-days))))
  12698. (case-fold-search nil)
  12699. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  12700. (callback
  12701. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  12702. (message "%d deadlines past-due or due within %d days"
  12703. (org-occur regexp nil callback)
  12704. org-warn-days)))
  12705. (defsubst org-re-timestamp (type)
  12706. "Return a regexp for timestamp TYPE.
  12707. Allowed values for TYPE are:
  12708. all: all timestamps
  12709. active: only active timestamps (<...>)
  12710. inactive: only inactive timestamps ([...])
  12711. scheduled: only scheduled timestamps
  12712. deadline: only deadline timestamps
  12713. closed: only closed time-stamps
  12714. When TYPE is nil, fall back on returning a regexp that matches
  12715. both scheduled and deadline timestamps."
  12716. (cl-case type
  12717. (all org-ts-regexp-both)
  12718. (active org-ts-regexp)
  12719. (inactive org-ts-regexp-inactive)
  12720. (scheduled org-scheduled-time-regexp)
  12721. (deadline org-deadline-time-regexp)
  12722. (closed org-closed-time-regexp)
  12723. (otherwise
  12724. (concat "\\<"
  12725. (regexp-opt (list org-deadline-string org-scheduled-string))
  12726. " *<\\([^>]+\\)>"))))
  12727. (defun org-check-before-date (d)
  12728. "Check if there are deadlines or scheduled entries before date D."
  12729. (interactive (list (org-read-date)))
  12730. (let* ((case-fold-search nil)
  12731. (regexp (org-re-timestamp org-ts-type))
  12732. (ts-type org-ts-type)
  12733. (callback
  12734. (lambda ()
  12735. (let ((match (match-string 1)))
  12736. (and (if (memq ts-type '(active inactive all))
  12737. (eq (org-element-type (save-excursion
  12738. (backward-char)
  12739. (org-element-context)))
  12740. 'timestamp)
  12741. (org-at-planning-p))
  12742. (time-less-p
  12743. (org-time-string-to-time match)
  12744. (org-time-string-to-time d)))))))
  12745. (message "%d entries before %s"
  12746. (org-occur regexp nil callback)
  12747. d)))
  12748. (defun org-check-after-date (d)
  12749. "Check if there are deadlines or scheduled entries after date D."
  12750. (interactive (list (org-read-date)))
  12751. (let* ((case-fold-search nil)
  12752. (regexp (org-re-timestamp org-ts-type))
  12753. (ts-type org-ts-type)
  12754. (callback
  12755. (lambda ()
  12756. (let ((match (match-string 1)))
  12757. (and (if (memq ts-type '(active inactive all))
  12758. (eq (org-element-type (save-excursion
  12759. (backward-char)
  12760. (org-element-context)))
  12761. 'timestamp)
  12762. (org-at-planning-p))
  12763. (not (time-less-p
  12764. (org-time-string-to-time match)
  12765. (org-time-string-to-time d))))))))
  12766. (message "%d entries after %s"
  12767. (org-occur regexp nil callback)
  12768. d)))
  12769. (defun org-check-dates-range (start-date end-date)
  12770. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  12771. (interactive (list (org-read-date nil nil nil "Range starts")
  12772. (org-read-date nil nil nil "Range end")))
  12773. (let ((case-fold-search nil)
  12774. (regexp (org-re-timestamp org-ts-type))
  12775. (callback
  12776. (let ((type org-ts-type))
  12777. (lambda ()
  12778. (let ((match (match-string 1)))
  12779. (and
  12780. (if (memq type '(active inactive all))
  12781. (eq (org-element-type (save-excursion
  12782. (backward-char)
  12783. (org-element-context)))
  12784. 'timestamp)
  12785. (org-at-planning-p))
  12786. (not (time-less-p
  12787. (org-time-string-to-time match)
  12788. (org-time-string-to-time start-date)))
  12789. (time-less-p
  12790. (org-time-string-to-time match)
  12791. (org-time-string-to-time end-date))))))))
  12792. (message "%d entries between %s and %s"
  12793. (org-occur regexp nil callback) start-date end-date)))
  12794. (defun org-evaluate-time-range (&optional to-buffer)
  12795. "Evaluate a time range by computing the difference between start and end.
  12796. Normally the result is just printed in the echo area, but with prefix arg
  12797. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  12798. If the time range is actually in a table, the result is inserted into the
  12799. next column.
  12800. For time difference computation, a year is assumed to be exactly 365
  12801. days in order to avoid rounding problems."
  12802. (interactive "P")
  12803. (or
  12804. (org-clock-update-time-maybe)
  12805. (save-excursion
  12806. (unless (org-at-date-range-p t)
  12807. (goto-char (point-at-bol))
  12808. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  12809. (unless (org-at-date-range-p t)
  12810. (user-error "Not at a time-stamp range, and none found in current line")))
  12811. (let* ((ts1 (match-string 1))
  12812. (ts2 (match-string 2))
  12813. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  12814. (match-end (match-end 0))
  12815. (time1 (org-time-string-to-time ts1))
  12816. (time2 (org-time-string-to-time ts2))
  12817. (diff (abs (float-time (time-subtract time2 time1))))
  12818. (negative (time-less-p time2 time1))
  12819. ;; (ys (floor (* 365 24 60 60)))
  12820. (ds (* 24 60 60))
  12821. (hs (* 60 60))
  12822. (fy "%dy %dd %02d:%02d")
  12823. (fy1 "%dy %dd")
  12824. (fd "%dd %02d:%02d")
  12825. (fd1 "%dd")
  12826. (fh "%02d:%02d")
  12827. y d h m align)
  12828. (if havetime
  12829. (setq ; y (floor diff ys) diff (mod diff ys)
  12830. y 0
  12831. d (floor diff ds) diff (mod diff ds)
  12832. h (floor diff hs) diff (mod diff hs)
  12833. m (floor diff 60))
  12834. (setq ; y (floor diff ys) diff (mod diff ys)
  12835. y 0
  12836. d (round diff ds)
  12837. h 0 m 0))
  12838. (if (not to-buffer)
  12839. (message "%s" (org-make-tdiff-string y d h m))
  12840. (if (org-at-table-p)
  12841. (progn
  12842. (goto-char match-end)
  12843. (setq align t)
  12844. (and (looking-at " *|") (goto-char (match-end 0))))
  12845. (goto-char match-end))
  12846. (when (looking-at
  12847. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  12848. (replace-match ""))
  12849. (when negative (insert " -"))
  12850. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  12851. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  12852. (insert " " (format fh h m))))
  12853. (when align (org-table-align))
  12854. (message "Time difference inserted")))))
  12855. (defun org-make-tdiff-string (y d h m)
  12856. (let ((fmt "")
  12857. (l nil))
  12858. (when (> y 0)
  12859. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  12860. (push y l))
  12861. (when (> d 0)
  12862. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  12863. (push d l))
  12864. (when (> h 0)
  12865. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  12866. (push h l))
  12867. (when (> m 0)
  12868. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  12869. (push m l))
  12870. (apply 'format fmt (nreverse l))))
  12871. (defun org-time-string-to-time (s)
  12872. "Convert timestamp string S into internal time."
  12873. (apply #'encode-time (org-parse-time-string s)))
  12874. (defun org-time-string-to-seconds (s)
  12875. "Convert a timestamp string S into a number of seconds."
  12876. (float-time (org-time-string-to-time s)))
  12877. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  12878. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  12879. "Convert time stamp S to an absolute day number.
  12880. If DAYNR in non-nil, and there is a specifier for a cyclic time
  12881. stamp, get the closest date to DAYNR. If PREFER is
  12882. `past' (respectively `future') return a date past (respectively
  12883. after) or equal to DAYNR.
  12884. POS is the location of time stamp S, as a buffer position in
  12885. BUFFER.
  12886. Diary sexp timestamps are matched against DAYNR, when non-nil.
  12887. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  12888. signaled."
  12889. (cond
  12890. ((string-match "\\`%%\\((.*)\\)" s)
  12891. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  12892. ;; only able to match individual dates. If it fails, raise an
  12893. ;; error.
  12894. (if (and daynr
  12895. (org-diary-sexp-entry
  12896. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  12897. daynr
  12898. (signal 'org-diary-sexp-no-match (list s))))
  12899. (daynr (org-closest-date s daynr prefer))
  12900. (t (time-to-days
  12901. (condition-case errdata
  12902. (org-time-string-to-time s)
  12903. (error (error "Bad timestamp `%s'%s\nError was: %s"
  12904. s
  12905. (if (not (and buffer pos)) ""
  12906. (format-message " at %d in buffer `%s'" pos buffer))
  12907. (cdr errdata))))))))
  12908. (defun org-days-to-iso-week (days)
  12909. "Return the ISO week number."
  12910. (require 'cal-iso)
  12911. (car (calendar-iso-from-absolute days)))
  12912. (defun org-small-year-to-year (year)
  12913. "Convert 2-digit years into 4-digit years.
  12914. YEAR is expanded into one of the 30 next years, if possible, or
  12915. into a past one. Any year larger than 99 is returned unchanged."
  12916. (if (>= year 100) year
  12917. (let* ((current (string-to-number (format-time-string "%Y")))
  12918. (century (/ current 100))
  12919. (offset (- year (% current 100))))
  12920. (cond ((> offset 30) (+ (* (1- century) 100) year))
  12921. ((> offset -70) (+ (* century 100) year))
  12922. (t (+ (* (1+ century) 100) year))))))
  12923. (defun org-time-from-absolute (d)
  12924. "Return the time corresponding to date D.
  12925. D may be an absolute day number, or a calendar-type list (month day year)."
  12926. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  12927. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  12928. (defvar org-agenda-current-date)
  12929. (defun org-calendar-holiday ()
  12930. "List of holidays, for Diary display in Org mode."
  12931. (require 'holidays)
  12932. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  12933. (and hl (mapconcat #'identity hl "; "))))
  12934. (defun org-diary-sexp-entry (sexp entry d)
  12935. "Process a SEXP diary ENTRY for date D."
  12936. (require 'diary-lib)
  12937. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  12938. ;; dynamically.
  12939. (let* ((sexp `(let ((entry ,entry)
  12940. (date ',d))
  12941. ,(car (read-from-string sexp))))
  12942. ;; FIXME: Do not use (eval ... t) in the following sexp as
  12943. ;; diary vars are still using dynamic scope.
  12944. (result (if calendar-debug-sexp (eval sexp)
  12945. (condition-case nil
  12946. (eval sexp)
  12947. (error
  12948. (beep)
  12949. (message "Bad sexp at line %d in %s: %s"
  12950. (org-current-line)
  12951. (buffer-file-name) sexp)
  12952. (sleep-for 2))))))
  12953. (cond ((stringp result) (split-string result "; "))
  12954. ((and (consp result)
  12955. (not (consp (cdr result)))
  12956. (stringp (cdr result))) (cdr result))
  12957. ((and (consp result)
  12958. (stringp (car result))) result)
  12959. (result entry))))
  12960. (defun org-diary-to-ical-string (frombuf)
  12961. "Get iCalendar entries from diary entries in buffer FROMBUF.
  12962. This uses the icalendar.el library."
  12963. (let* ((tmpdir temporary-file-directory)
  12964. (tmpfile (make-temp-name
  12965. (expand-file-name "orgics" tmpdir)))
  12966. buf rtn b e)
  12967. (with-current-buffer frombuf
  12968. (icalendar-export-region (point-min) (point-max) tmpfile)
  12969. (setq buf (find-buffer-visiting tmpfile))
  12970. (set-buffer buf)
  12971. (goto-char (point-min))
  12972. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  12973. (setq b (match-beginning 0)))
  12974. (goto-char (point-max))
  12975. (when (re-search-backward "^END:VEVENT" nil t)
  12976. (setq e (match-end 0)))
  12977. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  12978. (kill-buffer buf)
  12979. (delete-file tmpfile)
  12980. rtn))
  12981. (defun org-closest-date (start current prefer)
  12982. "Return closest date to CURRENT starting from START.
  12983. CURRENT and START are both time stamps.
  12984. When PREFER is `past', return a date that is either CURRENT or
  12985. past. When PREFER is `future', return a date that is either
  12986. CURRENT or future.
  12987. Only time stamps with a repeater are modified. Any other time
  12988. stamp stay unchanged. In any case, return value is an absolute
  12989. day number."
  12990. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  12991. ;; No repeater. Do not shift time stamp.
  12992. (time-to-days (org-time-string-to-time start))
  12993. (let ((value (string-to-number (match-string 1 start)))
  12994. (type (match-string 2 start)))
  12995. (if (= 0 value)
  12996. ;; Repeater with a 0-value is considered as void.
  12997. (time-to-days (org-time-string-to-time start))
  12998. (let* ((base (org-date-to-gregorian start))
  12999. (target (org-date-to-gregorian current))
  13000. (sday (calendar-absolute-from-gregorian base))
  13001. (cday (calendar-absolute-from-gregorian target))
  13002. n1 n2)
  13003. ;; If START is already past CURRENT, just return START.
  13004. (if (<= cday sday) sday
  13005. ;; Compute closest date before (N1) and closest date past
  13006. ;; (N2) CURRENT.
  13007. (pcase type
  13008. ("h"
  13009. (let ((missing-hours
  13010. (mod (+ (- (* 24 (- cday sday))
  13011. (nth 2 (org-parse-time-string start)))
  13012. org-extend-today-until)
  13013. value)))
  13014. (setf n1 (if (= missing-hours 0) cday
  13015. (- cday (1+ (/ missing-hours 24)))))
  13016. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13017. ((or "d" "w")
  13018. (let ((value (if (equal type "w") (* 7 value) value)))
  13019. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13020. (setf n2 (+ n1 value))))
  13021. ("m"
  13022. (let* ((add-months
  13023. (lambda (d n)
  13024. ;; Add N months to gregorian date D, i.e.,
  13025. ;; a list (MONTH DAY YEAR). Return a valid
  13026. ;; gregorian date.
  13027. (let ((m (+ (nth 0 d) n)))
  13028. (list (mod m 12)
  13029. (nth 1 d)
  13030. (+ (/ m 12) (nth 2 d))))))
  13031. (months ; Complete months to TARGET.
  13032. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13033. (- (nth 0 target) (nth 0 base))
  13034. ;; If START's day is greater than
  13035. ;; TARGET's, remove incomplete month.
  13036. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13037. value)
  13038. value))
  13039. (before (funcall add-months base months)))
  13040. (setf n1 (calendar-absolute-from-gregorian before))
  13041. (setf n2
  13042. (calendar-absolute-from-gregorian
  13043. (funcall add-months before value)))))
  13044. (_
  13045. (let* ((d (nth 1 base))
  13046. (m (nth 0 base))
  13047. (y (nth 2 base))
  13048. (years ; Complete years to TARGET.
  13049. (* (/ (- (nth 2 target)
  13050. y
  13051. ;; If START's month and day are
  13052. ;; greater than TARGET's, remove
  13053. ;; incomplete year.
  13054. (if (or (> (nth 0 target) m)
  13055. (and (= (nth 0 target) m)
  13056. (> (nth 1 target) d)))
  13057. 0
  13058. 1))
  13059. value)
  13060. value))
  13061. (before (list m d (+ y years))))
  13062. (setf n1 (calendar-absolute-from-gregorian before))
  13063. (setf n2 (calendar-absolute-from-gregorian
  13064. (list m d (+ (nth 2 before) value)))))))
  13065. ;; Handle PREFER parameter, if any.
  13066. (cond
  13067. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13068. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13069. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13070. (defun org-date-to-gregorian (d)
  13071. "Turn any specification of date D into a Gregorian date for the calendar."
  13072. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13073. ((and (listp d) (= (length d) 3)) d)
  13074. ((stringp d)
  13075. (let ((d (org-parse-time-string d)))
  13076. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13077. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13078. (defun org-timestamp-up (&optional arg)
  13079. "Increase the date item at the cursor by one.
  13080. If the cursor is on the year, change the year. If it is on the month,
  13081. the day or the time, change that. If the cursor is on the enclosing
  13082. bracket, change the timestamp type.
  13083. With prefix ARG, change by that many units."
  13084. (interactive "p")
  13085. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13086. (defun org-timestamp-down (&optional arg)
  13087. "Decrease the date item at the cursor by one.
  13088. If the cursor is on the year, change the year. If it is on the month,
  13089. the day or the time, change that. If the cursor is on the enclosing
  13090. bracket, change the timestamp type.
  13091. With prefix ARG, change by that many units."
  13092. (interactive "p")
  13093. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13094. (defun org-timestamp-up-day (&optional arg)
  13095. "Increase the date in the time stamp by one day.
  13096. With prefix ARG, change that many days."
  13097. (interactive "p")
  13098. (if (and (not (org-at-timestamp-p 'lax))
  13099. (org-at-heading-p))
  13100. (org-todo 'up)
  13101. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13102. (defun org-timestamp-down-day (&optional arg)
  13103. "Decrease the date in the time stamp by one day.
  13104. With prefix ARG, change that many days."
  13105. (interactive "p")
  13106. (if (and (not (org-at-timestamp-p 'lax))
  13107. (org-at-heading-p))
  13108. (org-todo 'down)
  13109. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13110. (defun org-at-timestamp-p (&optional extended)
  13111. "Non-nil if point is inside a timestamp.
  13112. By default, the function only consider syntactically valid active
  13113. timestamps. However, the caller may have a broader definition
  13114. for timestamps. As a consequence, optional argument EXTENDED can
  13115. be set to the following values
  13116. `inactive'
  13117. Include also syntactically valid inactive timestamps.
  13118. `agenda'
  13119. Include timestamps allowed in Agenda, i.e., those in
  13120. properties drawers, planning lines and clock lines.
  13121. `lax'
  13122. Ignore context. The function matches any part of the
  13123. document looking like a timestamp. This includes comments,
  13124. example blocks...
  13125. For backward-compatibility with Org 9.0, every other non-nil
  13126. value is equivalent to `inactive'.
  13127. When at a timestamp, return the position of the point as a symbol
  13128. among `bracket', `after', `year', `month', `hour', `minute',
  13129. `day' or a number of character from the last know part of the
  13130. time stamp. If diary sexp timestamps, any point inside the timestamp
  13131. is considered `day' (i.e. only `bracket', `day', and `after' return
  13132. values are possible).
  13133. When matching, the match groups are the following:
  13134. group 1: year, if any
  13135. group 2: month, if any
  13136. group 3: day number, if any
  13137. group 4: day name, if any
  13138. group 5: hours, if any
  13139. group 6: minutes, if any"
  13140. (let* ((regexp
  13141. (if extended
  13142. (if (eq extended 'agenda)
  13143. (rx-to-string
  13144. `(or (regexp ,org-ts-regexp3)
  13145. (regexp ,org-element--timestamp-regexp)))
  13146. org-ts-regexp3)
  13147. org-ts-regexp2))
  13148. (pos (point))
  13149. (match?
  13150. (let ((boundaries (org-in-regexp regexp)))
  13151. (save-match-data
  13152. (cond ((null boundaries) nil)
  13153. ((eq extended 'lax) t)
  13154. (t
  13155. (or (and (eq extended 'agenda)
  13156. (or (org-at-planning-p)
  13157. (org-at-property-p)
  13158. (and (bound-and-true-p
  13159. org-agenda-include-inactive-timestamps)
  13160. (org-at-clock-log-p))))
  13161. (eq 'timestamp
  13162. (save-excursion
  13163. (when (= pos (cdr boundaries)) (forward-char -1))
  13164. (org-element-type (org-element-context)))))))))))
  13165. (cond
  13166. ((not match?) nil)
  13167. ((= pos (match-beginning 0)) 'bracket)
  13168. ;; Distinguish location right before the closing bracket from
  13169. ;; right after it.
  13170. ((= pos (1- (match-end 0))) 'bracket)
  13171. ((= pos (match-end 0)) 'after)
  13172. ((org-pos-in-match-range pos 2) 'year)
  13173. ((org-pos-in-match-range pos 3) 'month)
  13174. ((org-pos-in-match-range pos 7) 'hour)
  13175. ((org-pos-in-match-range pos 8) 'minute)
  13176. ((or (org-pos-in-match-range pos 4)
  13177. (org-pos-in-match-range pos 5)) 'day)
  13178. ((and (or (match-end 8) (match-end 5))
  13179. (> pos (or (match-end 8) (match-end 5)))
  13180. (< pos (match-end 0)))
  13181. (- pos (or (match-end 8) (match-end 5))))
  13182. (t 'day))))
  13183. (defun org-toggle-timestamp-type ()
  13184. "Toggle the type (<active> or [inactive]) of a time stamp."
  13185. (interactive)
  13186. (when (org-at-timestamp-p 'lax)
  13187. (let ((beg (match-beginning 0)) (end (match-end 0))
  13188. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13189. (save-excursion
  13190. (goto-char beg)
  13191. (while (re-search-forward "[][<>]" end t)
  13192. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13193. t t)))
  13194. (message "Timestamp is now %sactive"
  13195. (if (equal (char-after beg) ?<) "" "in")))))
  13196. (defun org-at-clock-log-p ()
  13197. "Non-nil if point is on a clock log line."
  13198. (and (org-match-line org-clock-line-re)
  13199. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13200. (defvar org-clock-history) ; defined in org-clock.el
  13201. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13202. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13203. "Change the date in the time stamp at point.
  13204. The date is changed by N times WHAT. WHAT can be `day', `month',
  13205. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13206. position in the timestamp determines what is changed.
  13207. When optional argument UPDOWN is non-nil, minutes are rounded
  13208. according to `org-time-stamp-rounding-minutes'.
  13209. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13210. \"--2d\"."
  13211. (let ((origin (point))
  13212. (timestamp? (org-at-timestamp-p 'lax))
  13213. origin-cat
  13214. with-hm inactive
  13215. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13216. extra rem
  13217. ts time time0 fixnext clrgx)
  13218. (unless timestamp? (user-error "Not at a timestamp"))
  13219. (if (and (not what) (eq timestamp? 'bracket))
  13220. (org-toggle-timestamp-type)
  13221. ;; Point isn't on brackets. Remember the part of the time-stamp
  13222. ;; the point was in. Indeed, size of time-stamps may change,
  13223. ;; but point must be kept in the same category nonetheless.
  13224. (setq origin-cat timestamp?)
  13225. (when (and (not what) (not (eq timestamp? 'day))
  13226. org-display-custom-times
  13227. (get-text-property (point) 'display)
  13228. (not (get-text-property (1- (point)) 'display)))
  13229. (setq timestamp? 'day))
  13230. (setq timestamp? (or what timestamp?)
  13231. inactive (= (char-after (match-beginning 0)) ?\[)
  13232. ts (match-string 0))
  13233. (replace-match "")
  13234. (when (string-match
  13235. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13236. ts)
  13237. (setq extra (match-string 1 ts))
  13238. (when suppress-tmp-delay
  13239. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13240. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13241. (setq with-hm t))
  13242. (setq time0 (org-parse-time-string ts))
  13243. (when (and updown
  13244. (eq timestamp? 'minute)
  13245. (not current-prefix-arg))
  13246. ;; This looks like s-up and s-down. Change by one rounding step.
  13247. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13248. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13249. (setcar (cdr time0) (+ (nth 1 time0)
  13250. (if (> n 0) (- rem) (- dm rem))))))
  13251. (setq time
  13252. (apply #'encode-time
  13253. (or (car time0) 0)
  13254. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13255. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13256. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13257. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13258. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13259. (nthcdr 6 time0)))
  13260. (when (and (memq timestamp? '(hour minute))
  13261. extra
  13262. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13263. (setq extra (org-modify-ts-extra
  13264. extra
  13265. (if (eq timestamp? 'hour) 2 5)
  13266. n dm)))
  13267. (when (integerp timestamp?)
  13268. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13269. (when (eq what 'calendar)
  13270. (let ((cal-date (org-get-date-from-calendar)))
  13271. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13272. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13273. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13274. (setcar time0 (or (car time0) 0))
  13275. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13276. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13277. (setq time (apply 'encode-time time0))))
  13278. ;; Insert the new time-stamp, and ensure point stays in the same
  13279. ;; category as before (i.e. not after the last position in that
  13280. ;; category).
  13281. (let ((pos (point)))
  13282. ;; Stay before inserted string. `save-excursion' is of no use.
  13283. (setq org-last-changed-timestamp
  13284. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13285. (goto-char pos))
  13286. (save-match-data
  13287. (looking-at org-ts-regexp3)
  13288. (goto-char
  13289. (pcase origin-cat
  13290. ;; `day' category ends before `hour' if any, or at the end
  13291. ;; of the day name.
  13292. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13293. (`hour (min (match-end 7) origin))
  13294. (`minute (min (1- (match-end 8)) origin))
  13295. ((pred integerp) (min (1- (match-end 0)) origin))
  13296. ;; Point was right after the time-stamp. However, the
  13297. ;; time-stamp length might have changed, so refer to
  13298. ;; (match-end 0) instead.
  13299. (`after (match-end 0))
  13300. ;; `year' and `month' have both fixed size: point couldn't
  13301. ;; have moved into another part.
  13302. (_ origin))))
  13303. ;; Update clock if on a CLOCK line.
  13304. (org-clock-update-time-maybe)
  13305. ;; Maybe adjust the closest clock in `org-clock-history'
  13306. (when org-clock-adjust-closest
  13307. (if (not (and (org-at-clock-log-p)
  13308. (< 1 (length (delq nil (mapcar 'marker-position
  13309. org-clock-history))))))
  13310. (message "No clock to adjust")
  13311. (cond ((save-excursion ; fix previous clock?
  13312. (re-search-backward org-ts-regexp0 nil t)
  13313. (looking-back (concat org-clock-string " \\[")
  13314. (line-beginning-position)))
  13315. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13316. ((save-excursion ; fix next clock?
  13317. (re-search-backward org-ts-regexp0 nil t)
  13318. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13319. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13320. (save-window-excursion
  13321. ;; Find closest clock to point, adjust the previous/next one in history
  13322. (let* ((p (save-excursion (org-back-to-heading t)))
  13323. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13324. (clfixnth
  13325. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13326. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13327. (if (not clfixpos)
  13328. (message "No clock to adjust")
  13329. (save-excursion
  13330. (org-goto-marker-or-bmk clfixpos)
  13331. (org-fold-show-subtree)
  13332. (when (re-search-forward clrgx nil t)
  13333. (goto-char (match-beginning 1))
  13334. (let (org-clock-adjust-closest)
  13335. (org-timestamp-change n timestamp? updown))
  13336. (message "Clock adjusted in %s for heading: %s"
  13337. (file-name-nondirectory (buffer-file-name))
  13338. (org-get-heading t t)))))))))
  13339. ;; Try to recenter the calendar window, if any.
  13340. (when (and org-calendar-follow-timestamp-change
  13341. (get-buffer-window "*Calendar*" t)
  13342. (memq timestamp? '(day month year)))
  13343. (org-recenter-calendar (time-to-days time))))))
  13344. (defun org-modify-ts-extra (s pos n dm)
  13345. "Change the different parts of the lead-time and repeat fields in timestamp."
  13346. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13347. ng h m new rem)
  13348. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13349. (cond
  13350. ((or (org-pos-in-match-range pos 2)
  13351. (org-pos-in-match-range pos 3))
  13352. (setq m (string-to-number (match-string 3 s))
  13353. h (string-to-number (match-string 2 s)))
  13354. (if (org-pos-in-match-range pos 2)
  13355. (setq h (+ h n))
  13356. (setq n (* dm (with-no-warnings (cl-signum n))))
  13357. (unless (= 0 (setq rem (% m dm)))
  13358. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13359. (setq m (+ m n)))
  13360. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13361. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13362. (setq h (mod h 24))
  13363. (setq ng 1 new (format "-%02d:%02d" h m)))
  13364. ((org-pos-in-match-range pos 6)
  13365. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13366. ((org-pos-in-match-range pos 5)
  13367. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13368. ((org-pos-in-match-range pos 9)
  13369. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13370. ((org-pos-in-match-range pos 8)
  13371. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13372. (when ng
  13373. (setq s (concat
  13374. (substring s 0 (match-beginning ng))
  13375. new
  13376. (substring s (match-end ng))))))
  13377. s))
  13378. (defun org-recenter-calendar (d)
  13379. "If the calendar is visible, recenter it to date D."
  13380. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13381. (when cwin
  13382. (let ((calendar-move-hook nil))
  13383. (with-selected-window cwin
  13384. (calendar-goto-date
  13385. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13386. (defun org-goto-calendar (&optional arg)
  13387. "Go to the Emacs calendar at the current date.
  13388. If there is a time stamp in the current line, go to that date.
  13389. A prefix ARG can be used to force the current date."
  13390. (interactive "P")
  13391. (let ((calendar-move-hook nil)
  13392. (calendar-view-holidays-initially-flag nil)
  13393. (calendar-view-diary-initially-flag nil)
  13394. diff)
  13395. (when (or (org-at-timestamp-p 'lax)
  13396. (org-match-line (concat ".*" org-ts-regexp)))
  13397. (let ((d1 (time-to-days nil))
  13398. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13399. (setq diff (- d2 d1))))
  13400. (calendar)
  13401. (calendar-goto-today)
  13402. (when (and diff (not arg)) (calendar-forward-day diff))))
  13403. (defun org-get-date-from-calendar ()
  13404. "Return a list (month day year) of date at point in calendar."
  13405. (with-current-buffer "*Calendar*"
  13406. (save-match-data
  13407. (calendar-cursor-to-date))))
  13408. (defun org-date-from-calendar ()
  13409. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13410. If there is already a time stamp at the cursor position, update it."
  13411. (interactive)
  13412. (if (org-at-timestamp-p 'lax)
  13413. (org-timestamp-change 0 'calendar)
  13414. (let ((cal-date (org-get-date-from-calendar)))
  13415. (org-insert-time-stamp
  13416. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13417. (defcustom org-image-actual-width t
  13418. "When non-nil, use the actual width of images when inlining them.
  13419. When set to a number, use imagemagick (when available) to set the
  13420. image's width to this value.
  13421. When set to a number in a list, try to get the width from any
  13422. #+ATTR.* keyword if it matches a width specification like
  13423. #+ATTR_HTML: :width 300px
  13424. and fall back on that number if none is found.
  13425. When set to nil, try to get the width from an #+ATTR.* keyword
  13426. and fall back on the original width if none is found.
  13427. When set to any other non-nil value, always use the image width.
  13428. This requires Emacs >= 24.1, built with imagemagick support."
  13429. :group 'org-appearance
  13430. :version "24.4"
  13431. :package-version '(Org . "8.0")
  13432. :type '(choice
  13433. (const :tag "Use the image width" t)
  13434. (integer :tag "Use a number of pixels")
  13435. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13436. (const :tag "Use #+ATTR* or don't resize" nil)))
  13437. (defcustom org-agenda-inhibit-startup nil
  13438. "Inhibit startup when preparing agenda buffers.
  13439. When this variable is t, the initialization of the Org agenda
  13440. buffers is inhibited: e.g. the visibility state is not set, the
  13441. tables are not re-aligned, etc."
  13442. :type 'boolean
  13443. :version "24.3"
  13444. :group 'org-agenda)
  13445. (defcustom org-agenda-ignore-properties nil
  13446. "Avoid updating text properties when building the agenda.
  13447. Properties are used to prepare buffers for effort estimates,
  13448. appointments, statistics and subtree-local categories.
  13449. If you don't use these in the agenda, you can add them to this
  13450. list and agenda building will be a bit faster.
  13451. The value is a list, with zero or more of the symbols `effort', `appt',
  13452. `stats' or `category'."
  13453. :type '(set :greedy t
  13454. (const effort)
  13455. (const appt)
  13456. (const stats)
  13457. (const category))
  13458. :version "26.1"
  13459. :package-version '(Org . "8.3")
  13460. :group 'org-agenda)
  13461. ;;;; Files
  13462. (defun org-save-all-org-buffers ()
  13463. "Save all Org buffers without user confirmation."
  13464. (interactive)
  13465. (message "Saving all Org buffers...")
  13466. (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  13467. (when (featurep 'org-id) (org-id-locations-save))
  13468. (message "Saving all Org buffers... done"))
  13469. (defun org-revert-all-org-buffers ()
  13470. "Revert all Org buffers.
  13471. Prompt for confirmation when there are unsaved changes.
  13472. Be sure you know what you are doing before letting this function
  13473. overwrite your changes.
  13474. This function is useful in a setup where one tracks Org files
  13475. with a version control system, to revert on one machine after pulling
  13476. changes from another. I believe the procedure must be like this:
  13477. 1. \\[org-save-all-org-buffers]
  13478. 2. Pull changes from the other machine, resolve conflicts
  13479. 3. \\[org-revert-all-org-buffers]"
  13480. (interactive)
  13481. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  13482. (user-error "Abort"))
  13483. (save-excursion
  13484. (save-window-excursion
  13485. (dolist (b (buffer-list))
  13486. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  13487. (with-current-buffer b buffer-file-name))
  13488. (pop-to-buffer-same-window b)
  13489. (revert-buffer t 'no-confirm)))
  13490. (when (and (featurep 'org-id) org-id-track-globally)
  13491. (org-id-locations-load)))))
  13492. ;;;; Agenda files
  13493. ;;;###autoload
  13494. (defun org-switchb (&optional arg)
  13495. "Switch between Org buffers.
  13496. With `\\[universal-argument]' prefix, restrict available buffers to files.
  13497. With `\\[universal-argument] \\[universal-argument]' \
  13498. prefix, restrict available buffers to agenda files."
  13499. (interactive "P")
  13500. (let ((blist (org-buffer-list
  13501. (cond ((equal arg '(4)) 'files)
  13502. ((equal arg '(16)) 'agenda)))))
  13503. (pop-to-buffer-same-window
  13504. (completing-read "Org buffer: "
  13505. (mapcar #'list (mapcar #'buffer-name blist))
  13506. nil t))))
  13507. (defun org-agenda-files (&optional unrestricted archives)
  13508. "Get the list of agenda files.
  13509. Optional UNRESTRICTED means return the full list even if a restriction
  13510. is currently in place.
  13511. When ARCHIVES is t, include all archive files that are really being
  13512. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  13513. `org-agenda-archives-mode' is t."
  13514. (let ((files
  13515. (cond
  13516. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  13517. ((stringp org-agenda-files) (org-read-agenda-file-list))
  13518. ((listp org-agenda-files) org-agenda-files)
  13519. (t (error "Invalid value of `org-agenda-files'")))))
  13520. (setq files (apply 'append
  13521. (mapcar (lambda (f)
  13522. (if (file-directory-p f)
  13523. (directory-files
  13524. f t org-agenda-file-regexp)
  13525. (list (expand-file-name f org-directory))))
  13526. files)))
  13527. (when org-agenda-skip-unavailable-files
  13528. (setq files (delq nil
  13529. (mapcar (lambda (file)
  13530. (and (file-readable-p file) file))
  13531. files))))
  13532. (when (or (eq archives t)
  13533. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  13534. (setq files (org-add-archive-files files)))
  13535. files))
  13536. (defun org-agenda-file-p (&optional file)
  13537. "Return non-nil, if FILE is an agenda file.
  13538. If FILE is omitted, use the file associated with the current
  13539. buffer."
  13540. (let ((fname (or file (buffer-file-name))))
  13541. (and fname
  13542. (member (file-truename fname)
  13543. (mapcar #'file-truename (org-agenda-files t))))))
  13544. (defun org-edit-agenda-file-list ()
  13545. "Edit the list of agenda files.
  13546. Depending on setup, this either uses customize to edit the variable
  13547. `org-agenda-files', or it visits the file that is holding the list. In the
  13548. latter case, the buffer is set up in a way that saving it automatically kills
  13549. the buffer and restores the previous window configuration."
  13550. (interactive)
  13551. (if (stringp org-agenda-files)
  13552. (let ((cw (current-window-configuration)))
  13553. (find-file org-agenda-files)
  13554. (setq-local org-window-configuration cw)
  13555. (add-hook 'after-save-hook
  13556. (lambda ()
  13557. (set-window-configuration
  13558. (prog1 org-window-configuration
  13559. (kill-buffer (current-buffer))))
  13560. (org-install-agenda-files-menu)
  13561. (message "New agenda file list installed"))
  13562. nil 'local)
  13563. (message "%s" (substitute-command-keys
  13564. "Edit list and finish with \\[save-buffer]")))
  13565. (customize-variable 'org-agenda-files)))
  13566. (defun org-store-new-agenda-file-list (list)
  13567. "Set new value for the agenda file list and save it correctly."
  13568. (if (stringp org-agenda-files)
  13569. (let ((fe (org-read-agenda-file-list t)) b u)
  13570. (while (setq b (find-buffer-visiting org-agenda-files))
  13571. (kill-buffer b))
  13572. (with-temp-file org-agenda-files
  13573. (insert
  13574. (mapconcat
  13575. (lambda (f) ;; Keep un-expanded entries.
  13576. (if (setq u (assoc f fe))
  13577. (cdr u)
  13578. f))
  13579. list "\n")
  13580. "\n")))
  13581. (let ((org-mode-hook nil) (org-inhibit-startup t)
  13582. (org-insert-mode-line-in-empty-file nil))
  13583. (setq org-agenda-files list)
  13584. (customize-save-variable 'org-agenda-files org-agenda-files))))
  13585. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  13586. "Read the list of agenda files from a file.
  13587. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  13588. filenames, used by `org-store-new-agenda-file-list' to write back
  13589. un-expanded file names."
  13590. (when (file-directory-p org-agenda-files)
  13591. (error "`org-agenda-files' cannot be a single directory"))
  13592. (when (stringp org-agenda-files)
  13593. (with-temp-buffer
  13594. (insert-file-contents org-agenda-files)
  13595. (mapcar
  13596. (lambda (f)
  13597. (let ((e (expand-file-name (substitute-in-file-name f)
  13598. org-directory)))
  13599. (if pair-with-expansion
  13600. (cons e f)
  13601. e)))
  13602. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  13603. ;;;###autoload
  13604. (defun org-cycle-agenda-files ()
  13605. "Cycle through the files in `org-agenda-files'.
  13606. If the current buffer visits an agenda file, find the next one in the list.
  13607. If the current buffer does not, find the first agenda file."
  13608. (interactive)
  13609. (let* ((fs (or (org-agenda-files t)
  13610. (user-error "No agenda files")))
  13611. (files (copy-sequence fs))
  13612. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  13613. file)
  13614. (when tcf
  13615. (while (and (setq file (pop files))
  13616. (not (equal (file-truename file) tcf)))))
  13617. (find-file (car (or files fs)))
  13618. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  13619. (defun org-agenda-file-to-front (&optional to-end)
  13620. "Move/add the current file to the top of the agenda file list.
  13621. If the file is not present in the list, it is added to the front. If it is
  13622. present, it is moved there. With optional argument TO-END, add/move to the
  13623. end of the list."
  13624. (interactive "P")
  13625. (let ((org-agenda-skip-unavailable-files nil)
  13626. (file-alist (mapcar (lambda (x)
  13627. (cons (file-truename x) x))
  13628. (org-agenda-files t)))
  13629. (ctf (file-truename
  13630. (or buffer-file-name
  13631. (user-error "Please save the current buffer to a file"))))
  13632. x had)
  13633. (setq x (assoc ctf file-alist) had x)
  13634. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  13635. (if to-end
  13636. (setq file-alist (append (delq x file-alist) (list x)))
  13637. (setq file-alist (cons x (delq x file-alist))))
  13638. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  13639. (org-install-agenda-files-menu)
  13640. (message "File %s to %s of agenda file list"
  13641. (if had "moved" "added") (if to-end "end" "front"))))
  13642. (defun org-remove-file (&optional file)
  13643. "Remove current file from the list of files in variable `org-agenda-files'.
  13644. These are the files which are being checked for agenda entries.
  13645. Optional argument FILE means use this file instead of the current."
  13646. (interactive)
  13647. (let* ((org-agenda-skip-unavailable-files nil)
  13648. (file (or file buffer-file-name
  13649. (user-error "Current buffer does not visit a file")))
  13650. (true-file (file-truename file))
  13651. (afile (abbreviate-file-name file))
  13652. (files (delq nil (mapcar
  13653. (lambda (x)
  13654. (unless (equal true-file
  13655. (file-truename x))
  13656. x))
  13657. (org-agenda-files t)))))
  13658. (if (not (= (length files) (length (org-agenda-files t))))
  13659. (progn
  13660. (org-store-new-agenda-file-list files)
  13661. (org-install-agenda-files-menu)
  13662. (message "Removed from Org Agenda list: %s" afile))
  13663. (message "File was not in list: %s (not removed)" afile))))
  13664. (defun org-file-menu-entry (file)
  13665. (vector file (list 'find-file file) t))
  13666. (defun org-check-agenda-file (file)
  13667. "Make sure FILE exists. If not, ask user what to do."
  13668. (unless (file-exists-p file)
  13669. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  13670. (abbreviate-file-name file))
  13671. (let ((r (downcase (read-char-exclusive))))
  13672. (cond
  13673. ((equal r ?r)
  13674. (org-remove-file file)
  13675. (throw 'nextfile t))
  13676. (t (user-error "Abort"))))))
  13677. (defun org-get-agenda-file-buffer (file)
  13678. "Get an agenda buffer visiting FILE.
  13679. If the buffer needs to be created, add it to the list of buffers
  13680. which might be released later."
  13681. (let ((buf (org-find-base-buffer-visiting file)))
  13682. (if buf
  13683. buf ; just return it
  13684. ;; Make a new buffer and remember it
  13685. (setq buf (find-file-noselect file))
  13686. (when buf (push buf org-agenda-new-buffers))
  13687. buf)))
  13688. (defun org-release-buffers (blist)
  13689. "Release all buffers in list, asking the user for confirmation when needed.
  13690. When a buffer is unmodified, it is just killed. When modified, it is saved
  13691. \(if the user agrees) and then killed."
  13692. (let (file)
  13693. (dolist (buf blist)
  13694. (setq file (buffer-file-name buf))
  13695. (when (and (buffer-modified-p buf)
  13696. file
  13697. (y-or-n-p (format "Save file %s? " file)))
  13698. (with-current-buffer buf (save-buffer)))
  13699. (kill-buffer buf))))
  13700. (defun org-agenda-prepare-buffers (files)
  13701. "Create buffers for all agenda files, protect archived trees and comments."
  13702. (interactive)
  13703. (let ((inhibit-read-only t)
  13704. (org-inhibit-startup org-agenda-inhibit-startup)
  13705. pos)
  13706. (setq org-tag-alist-for-agenda nil
  13707. org-tag-groups-alist-for-agenda nil)
  13708. (save-excursion
  13709. (save-restriction
  13710. (dolist (file files)
  13711. (catch 'nextfile
  13712. (if (bufferp file)
  13713. (set-buffer file)
  13714. (org-check-agenda-file file)
  13715. (set-buffer (org-get-agenda-file-buffer file)))
  13716. (widen)
  13717. (org-set-regexps-and-options 'tags-only)
  13718. (setq pos (point))
  13719. (or (memq 'category org-agenda-ignore-properties)
  13720. (org-refresh-category-properties))
  13721. (or (memq 'stats org-agenda-ignore-properties)
  13722. (org-refresh-stats-properties))
  13723. (or (memq 'effort org-agenda-ignore-properties)
  13724. (unless org-element-use-cache
  13725. (org-refresh-effort-properties)))
  13726. (or (memq 'appt org-agenda-ignore-properties)
  13727. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  13728. (setq org-todo-keywords-for-agenda
  13729. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  13730. (setq org-done-keywords-for-agenda
  13731. (append org-done-keywords-for-agenda org-done-keywords))
  13732. (setq org-todo-keyword-alist-for-agenda
  13733. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  13734. (setq org-tag-alist-for-agenda
  13735. (org--tag-add-to-alist
  13736. org-tag-alist-for-agenda
  13737. org-current-tag-alist))
  13738. ;; Merge current file's tag groups into global
  13739. ;; `org-tag-groups-alist-for-agenda'.
  13740. (when org-group-tags
  13741. (dolist (alist org-tag-groups-alist)
  13742. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  13743. (if old
  13744. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  13745. (push alist org-tag-groups-alist-for-agenda)))))
  13746. (goto-char pos)))))
  13747. (setq org-todo-keywords-for-agenda
  13748. (org-uniquify org-todo-keywords-for-agenda))
  13749. (setq org-todo-keyword-alist-for-agenda
  13750. (org-uniquify org-todo-keyword-alist-for-agenda))))
  13751. ;;;; CDLaTeX minor mode
  13752. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  13753. "Keymap for the minor `org-cdlatex-mode'.")
  13754. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  13755. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  13756. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  13757. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  13758. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  13759. (defvar org-cdlatex-texmathp-advice-is-done nil
  13760. "Flag remembering if we have applied the advice to texmathp already.")
  13761. (define-minor-mode org-cdlatex-mode
  13762. "Toggle the minor `org-cdlatex-mode'.
  13763. This mode supports entering LaTeX environment and math in LaTeX fragments
  13764. in Org mode.
  13765. \\{org-cdlatex-mode-map}"
  13766. :lighter " OCDL"
  13767. (when org-cdlatex-mode
  13768. (require 'cdlatex)
  13769. (run-hooks 'cdlatex-mode-hook)
  13770. (cdlatex-compute-tables))
  13771. (unless org-cdlatex-texmathp-advice-is-done
  13772. (setq org-cdlatex-texmathp-advice-is-done t)
  13773. (advice-add 'texmathp :around #'org--math-always-on)))
  13774. (defun org--math-always-on (orig-fun &rest args)
  13775. "Always return t in Org buffers.
  13776. This is because we want to insert math symbols without dollars even outside
  13777. the LaTeX math segments. If Org mode thinks that point is actually inside
  13778. an embedded LaTeX fragment, let `texmathp' do its job.
  13779. `\\[org-cdlatex-mode-map]'"
  13780. (interactive)
  13781. (cond
  13782. ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  13783. ((eq this-command 'cdlatex-math-symbol)
  13784. (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  13785. t)
  13786. (t
  13787. (let ((p (org-inside-LaTeX-fragment-p)))
  13788. (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  13789. (if (member (car p)
  13790. (plist-get org-format-latex-options :matchers))
  13791. (progn
  13792. (setq texmathp-why '("Org mode embedded math" . 0))
  13793. t)
  13794. (apply orig-fun args)))))))
  13795. (defun turn-on-org-cdlatex ()
  13796. "Unconditionally turn on `org-cdlatex-mode'."
  13797. (org-cdlatex-mode 1))
  13798. (defun org-try-cdlatex-tab ()
  13799. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  13800. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  13801. - inside a LaTeX fragment, or
  13802. - after the first word in a line, where an abbreviation expansion could
  13803. insert a LaTeX environment."
  13804. (when org-cdlatex-mode
  13805. (cond
  13806. ;; Before any word on the line: No expansion possible.
  13807. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  13808. ;; Just after first word on the line: Expand it. Make sure it
  13809. ;; cannot happen on headlines, though.
  13810. ((save-excursion
  13811. (skip-chars-backward "a-zA-Z0-9*")
  13812. (skip-chars-backward " \t")
  13813. (and (bolp) (not (org-at-heading-p))))
  13814. (cdlatex-tab) t)
  13815. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  13816. (defun org-cdlatex-underscore-caret (&optional _arg)
  13817. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  13818. Revert to the normal definition outside of these fragments."
  13819. (interactive "P")
  13820. (if (org-inside-LaTeX-fragment-p)
  13821. (call-interactively 'cdlatex-sub-superscript)
  13822. (let (org-cdlatex-mode)
  13823. (call-interactively (key-binding (vector last-input-event))))))
  13824. (defun org-cdlatex-math-modify (&optional _arg)
  13825. "Execute `cdlatex-math-modify' in LaTeX fragments.
  13826. Revert to the normal definition outside of these fragments."
  13827. (interactive "P")
  13828. (if (org-inside-LaTeX-fragment-p)
  13829. (call-interactively 'cdlatex-math-modify)
  13830. (let (org-cdlatex-mode)
  13831. (call-interactively (key-binding (vector last-input-event))))))
  13832. (defun org-cdlatex-environment-indent (&optional environment item)
  13833. "Execute `cdlatex-environment' and indent the inserted environment.
  13834. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  13835. The inserted environment is indented to current indentation
  13836. unless point is at the beginning of the line, in which the
  13837. environment remains unintended."
  13838. (interactive)
  13839. ;; cdlatex-environment always return nil. Therefore, capture output
  13840. ;; first and determine if an environment was selected.
  13841. (let* ((beg (point-marker))
  13842. (end (copy-marker (point) t))
  13843. (inserted (progn
  13844. (ignore-errors (cdlatex-environment environment item))
  13845. (< beg end)))
  13846. ;; Figure out how many lines to move forward after the
  13847. ;; environment has been inserted.
  13848. (lines (when inserted
  13849. (save-excursion
  13850. (- (cl-loop while (< beg (point))
  13851. with x = 0
  13852. do (forward-line -1)
  13853. (cl-incf x)
  13854. finally return x)
  13855. (if (progn (goto-char beg)
  13856. (and (progn (skip-chars-forward " \t") (eolp))
  13857. (progn (skip-chars-backward " \t") (bolp))))
  13858. 1 0)))))
  13859. (env (org-trim (delete-and-extract-region beg end))))
  13860. (when inserted
  13861. ;; Get indentation of next line unless at column 0.
  13862. (let ((ind (if (bolp) 0
  13863. (save-excursion
  13864. (org-return t)
  13865. (prog1 (current-indentation)
  13866. (when (progn (skip-chars-forward " \t") (eolp))
  13867. (delete-region beg (point)))))))
  13868. (bol (progn (skip-chars-backward " \t") (bolp))))
  13869. ;; Insert a newline before environment unless at column zero
  13870. ;; to "escape" the current line. Insert a newline if
  13871. ;; something is one the same line as \end{ENVIRONMENT}.
  13872. (insert
  13873. (concat (unless bol "\n") env
  13874. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  13875. (unless (zerop ind)
  13876. (save-excursion
  13877. (goto-char beg)
  13878. (while (< (point) end)
  13879. (unless (eolp) (indent-line-to ind))
  13880. (forward-line))))
  13881. (goto-char beg)
  13882. (forward-line lines)
  13883. (indent-line-to ind)))
  13884. (set-marker beg nil)
  13885. (set-marker end nil)))
  13886. ;;;; LaTeX fragments
  13887. (defun org-inside-LaTeX-fragment-p ()
  13888. "Test if point is inside a LaTeX fragment.
  13889. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  13890. sequence appearing also before point.
  13891. Even though the matchers for math are configurable, this function assumes
  13892. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  13893. delimiters are skipped when they have been removed by customization.
  13894. The return value is nil, or a cons cell with the delimiter and the
  13895. position of this delimiter.
  13896. This function does a reasonably good job, but can locally be fooled by
  13897. for example currency specifications. For example it will assume being in
  13898. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  13899. fragments that are properly closed, but during editing, we have to live
  13900. with the uncertainty caused by missing closing delimiters. This function
  13901. looks only before point, not after."
  13902. (catch 'exit
  13903. (let ((pos (point))
  13904. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  13905. (lim (progn
  13906. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  13907. 'move)
  13908. (point)))
  13909. dd-on str (start 0) m re)
  13910. (goto-char pos)
  13911. (when dodollar
  13912. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  13913. re (nth 1 (assoc "$" org-latex-regexps)))
  13914. (while (string-match re str start)
  13915. (cond
  13916. ((= (match-end 0) (length str))
  13917. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  13918. ((= (match-end 0) (- (length str) 5))
  13919. (throw 'exit nil))
  13920. (t (setq start (match-end 0))))))
  13921. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  13922. (goto-char pos)
  13923. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  13924. (and (match-beginning 2) (throw 'exit nil))
  13925. ;; count $$
  13926. (while (re-search-backward "\\$\\$" lim t)
  13927. (setq dd-on (not dd-on)))
  13928. (goto-char pos)
  13929. (when dd-on (cons "$$" m))))))
  13930. (defun org-inside-latex-macro-p ()
  13931. "Is point inside a LaTeX macro or its arguments?"
  13932. (save-match-data
  13933. (org-in-regexp
  13934. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  13935. (defun org--make-preview-overlay (beg end image &optional imagetype)
  13936. "Build an overlay between BEG and END using IMAGE file.
  13937. Argument IMAGETYPE is the extension of the displayed image,
  13938. as a string. It defaults to \"png\"."
  13939. (let ((ov (make-overlay beg end))
  13940. (imagetype (or (intern imagetype) 'png)))
  13941. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  13942. (overlay-put ov 'evaporate t)
  13943. (overlay-put ov
  13944. 'modification-hooks
  13945. (list (lambda (o _flag _beg _end &optional _l)
  13946. (delete-overlay o))))
  13947. (overlay-put ov
  13948. 'display
  13949. (list 'image :type imagetype :file image :ascent 'center))))
  13950. (defun org-clear-latex-preview (&optional beg end)
  13951. "Remove all overlays with LaTeX fragment images in current buffer.
  13952. When optional arguments BEG and END are non-nil, remove all
  13953. overlays between them instead. Return a non-nil value when some
  13954. overlays were removed, nil otherwise."
  13955. (let ((overlays
  13956. (cl-remove-if-not
  13957. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  13958. (overlays-in (or beg (point-min)) (or end (point-max))))))
  13959. (mapc #'delete-overlay overlays)
  13960. overlays))
  13961. (defun org--latex-preview-region (beg end)
  13962. "Preview LaTeX fragments between BEG and END.
  13963. BEG and END are buffer positions."
  13964. (let ((file (buffer-file-name (buffer-base-buffer))))
  13965. (save-excursion
  13966. (org-format-latex
  13967. (concat org-preview-latex-image-directory "org-ltximg")
  13968. beg end
  13969. ;; Emacs cannot overlay images from remote hosts. Create it in
  13970. ;; `temporary-file-directory' instead.
  13971. (if (or (not file) (file-remote-p file))
  13972. temporary-file-directory
  13973. default-directory)
  13974. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  13975. (defun org-latex-preview (&optional arg)
  13976. "Toggle preview of the LaTeX fragment at point.
  13977. If the cursor is on a LaTeX fragment, create the image and
  13978. overlay it over the source code, if there is none. Remove it
  13979. otherwise. If there is no fragment at point, display images for
  13980. all fragments in the current section. With an active region,
  13981. display images for all fragments in the region.
  13982. With a `\\[universal-argument]' prefix argument ARG, clear images \
  13983. for all fragments
  13984. in the current section.
  13985. With a `\\[universal-argument] \\[universal-argument]' prefix \
  13986. argument ARG, display image for all
  13987. fragments in the buffer.
  13988. With a `\\[universal-argument] \\[universal-argument] \
  13989. \\[universal-argument]' prefix argument ARG, clear image for all
  13990. fragments in the buffer."
  13991. (interactive "P")
  13992. (cond
  13993. ((not (display-graphic-p)) nil)
  13994. ;; Clear whole buffer.
  13995. ((equal arg '(64))
  13996. (org-clear-latex-preview (point-min) (point-max))
  13997. (message "LaTeX previews removed from buffer"))
  13998. ;; Preview whole buffer.
  13999. ((equal arg '(16))
  14000. (message "Creating LaTeX previews in buffer...")
  14001. (org--latex-preview-region (point-min) (point-max))
  14002. (message "Creating LaTeX previews in buffer... done."))
  14003. ;; Clear current section.
  14004. ((equal arg '(4))
  14005. (org-clear-latex-preview
  14006. (if (use-region-p)
  14007. (region-beginning)
  14008. (if (org-before-first-heading-p) (point-min)
  14009. (save-excursion
  14010. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14011. (if (use-region-p)
  14012. (region-end)
  14013. (org-with-limited-levels (org-entry-end-position)))))
  14014. ((use-region-p)
  14015. (message "Creating LaTeX previews in region...")
  14016. (org--latex-preview-region (region-beginning) (region-end))
  14017. (message "Creating LaTeX previews in region... done."))
  14018. ;; Toggle preview on LaTeX code at point.
  14019. ((let ((datum (org-element-context)))
  14020. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14021. (let ((beg (org-element-property :begin datum))
  14022. (end (org-element-property :end datum)))
  14023. (if (org-clear-latex-preview beg end)
  14024. (message "LaTeX preview removed")
  14025. (message "Creating LaTeX preview...")
  14026. (org--latex-preview-region beg end)
  14027. (message "Creating LaTeX preview... done."))
  14028. t))))
  14029. ;; Preview current section.
  14030. (t
  14031. (let ((beg (if (org-before-first-heading-p) (point-min)
  14032. (save-excursion
  14033. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14034. (end (org-with-limited-levels (org-entry-end-position))))
  14035. (message "Creating LaTeX previews in section...")
  14036. (org--latex-preview-region beg end)
  14037. (message "Creating LaTeX previews in section... done.")))))
  14038. (defun org-format-latex
  14039. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14040. "Replace LaTeX fragments with links to an image.
  14041. The function takes care of creating the replacement image.
  14042. Only consider fragments between BEG and END when those are
  14043. provided.
  14044. When optional argument OVERLAYS is non-nil, display the image on
  14045. top of the fragment instead of replacing it.
  14046. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14047. Some of the options can be changed using the variable
  14048. `org-format-latex-options', which see."
  14049. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14050. (unless (eq processing-type 'verbatim)
  14051. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14052. (cnt 0)
  14053. checkdir-flag)
  14054. (goto-char (or beg (point-min)))
  14055. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14056. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14057. (overlay-recenter (or end (point-max))))
  14058. (while (re-search-forward math-regexp end t)
  14059. (unless (and overlays
  14060. (eq (get-char-property (point) 'org-overlay-type)
  14061. 'org-latex-overlay))
  14062. (let* ((context (org-element-context))
  14063. (type (org-element-type context)))
  14064. (when (memq type '(latex-environment latex-fragment))
  14065. (let ((block-type (eq type 'latex-environment))
  14066. (value (org-element-property :value context))
  14067. (beg (org-element-property :begin context))
  14068. (end (save-excursion
  14069. (goto-char (org-element-property :end context))
  14070. (skip-chars-backward " \r\t\n")
  14071. (point))))
  14072. (cond
  14073. ((eq processing-type 'mathjax)
  14074. ;; Prepare for MathJax processing.
  14075. (if (not (string-match "\\`\\$\\$?" value))
  14076. (goto-char end)
  14077. (delete-region beg end)
  14078. (if (string= (match-string 0 value) "$$")
  14079. (insert "\\[" (substring value 2 -2) "\\]")
  14080. (insert "\\(" (substring value 1 -1) "\\)"))))
  14081. ((eq processing-type 'html)
  14082. (goto-char beg)
  14083. (delete-region beg end)
  14084. (insert (org-format-latex-as-html value)))
  14085. ((assq processing-type org-preview-latex-process-alist)
  14086. ;; Process to an image.
  14087. (cl-incf cnt)
  14088. (goto-char beg)
  14089. (let* ((processing-info
  14090. (cdr (assq processing-type org-preview-latex-process-alist)))
  14091. (face (face-at-point))
  14092. ;; Get the colors from the face at point.
  14093. (fg
  14094. (let ((color (plist-get org-format-latex-options
  14095. :foreground)))
  14096. (if forbuffer
  14097. (cond
  14098. ((eq color 'auto)
  14099. (face-attribute face :foreground nil 'default))
  14100. ((eq color 'default)
  14101. (face-attribute 'default :foreground nil))
  14102. (t color))
  14103. color)))
  14104. (bg
  14105. (let ((color (plist-get org-format-latex-options
  14106. :background)))
  14107. (if forbuffer
  14108. (cond
  14109. ((eq color 'auto)
  14110. (face-attribute face :background nil 'default))
  14111. ((eq color 'default)
  14112. (face-attribute 'default :background nil))
  14113. (t color))
  14114. color)))
  14115. (hash (sha1 (prin1-to-string
  14116. (list org-format-latex-header
  14117. org-latex-default-packages-alist
  14118. org-latex-packages-alist
  14119. org-format-latex-options
  14120. forbuffer value fg bg))))
  14121. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14122. (absprefix (expand-file-name prefix dir))
  14123. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14124. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14125. (sep (and block-type "\n\n"))
  14126. (link (concat sep "[[file:" linkfile "]]" sep))
  14127. (options
  14128. (org-combine-plists
  14129. org-format-latex-options
  14130. `(:foreground ,fg :background ,bg))))
  14131. (when msg (message msg cnt))
  14132. (unless checkdir-flag ; Ensure the directory exists.
  14133. (setq checkdir-flag t)
  14134. (let ((todir (file-name-directory absprefix)))
  14135. (unless (file-directory-p todir)
  14136. (make-directory todir t))))
  14137. (unless (file-exists-p movefile)
  14138. (org-create-formula-image
  14139. value movefile options forbuffer processing-type))
  14140. (if overlays
  14141. (progn
  14142. (dolist (o (overlays-in beg end))
  14143. (when (eq (overlay-get o 'org-overlay-type)
  14144. 'org-latex-overlay)
  14145. (delete-overlay o)))
  14146. (org--make-preview-overlay beg end movefile imagetype)
  14147. (goto-char end))
  14148. (delete-region beg end)
  14149. (insert
  14150. (org-add-props link
  14151. (list 'org-latex-src
  14152. (replace-regexp-in-string "\"" "" value)
  14153. 'org-latex-src-embed-type
  14154. (if block-type 'paragraph 'character)))))))
  14155. ((eq processing-type 'mathml)
  14156. ;; Process to MathML.
  14157. (unless (org-format-latex-mathml-available-p)
  14158. (user-error "LaTeX to MathML converter not configured"))
  14159. (cl-incf cnt)
  14160. (when msg (message msg cnt))
  14161. (goto-char beg)
  14162. (delete-region beg end)
  14163. (insert (org-format-latex-as-mathml
  14164. value block-type prefix dir)))
  14165. (t
  14166. (error "Unknown conversion process %s for LaTeX fragments"
  14167. processing-type)))))))))))
  14168. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14169. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14170. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14171. successful, return the portion between \"<math...> </math>\"
  14172. elements otherwise return nil. When MATHML-FILE is specified,
  14173. write the results in to that file. When invoked as an
  14174. interactive command, prompt for LATEX-FRAG, with initial value
  14175. set to the current active region and echo the results for user
  14176. inspection."
  14177. (interactive (list (let ((frag (when (org-region-active-p)
  14178. (buffer-substring-no-properties
  14179. (region-beginning) (region-end)))))
  14180. (read-string "LaTeX Fragment: " frag nil frag))))
  14181. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14182. (let* ((tmp-in-file
  14183. (let ((file (file-relative-name
  14184. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14185. (write-region latex-frag nil file)
  14186. file))
  14187. (tmp-out-file (file-relative-name
  14188. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14189. (cmd (format-spec
  14190. org-latex-to-mathml-convert-command
  14191. `((?j . ,(and org-latex-to-mathml-jar-file
  14192. (shell-quote-argument
  14193. (expand-file-name
  14194. org-latex-to-mathml-jar-file))))
  14195. (?I . ,(shell-quote-argument tmp-in-file))
  14196. (?i . ,latex-frag)
  14197. (?o . ,(shell-quote-argument tmp-out-file)))))
  14198. mathml shell-command-output)
  14199. (when (called-interactively-p 'any)
  14200. (unless (org-format-latex-mathml-available-p)
  14201. (user-error "LaTeX to MathML converter not configured")))
  14202. (message "Running %s" cmd)
  14203. (setq shell-command-output (shell-command-to-string cmd))
  14204. (setq mathml
  14205. (when (file-readable-p tmp-out-file)
  14206. (with-current-buffer (find-file-noselect tmp-out-file t)
  14207. (goto-char (point-min))
  14208. (when (re-search-forward
  14209. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14210. (regexp-quote
  14211. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14212. nil t)
  14213. (prog1 (match-string 0) (kill-buffer))))))
  14214. (cond
  14215. (mathml
  14216. (setq mathml
  14217. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14218. (when mathml-file
  14219. (write-region mathml nil mathml-file))
  14220. (when (called-interactively-p 'any)
  14221. (message mathml)))
  14222. ((warn "LaTeX to MathML conversion failed")
  14223. (message shell-command-output)))
  14224. (delete-file tmp-in-file)
  14225. (when (file-exists-p tmp-out-file)
  14226. (delete-file tmp-out-file))
  14227. mathml))
  14228. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14229. prefix &optional dir)
  14230. "Use `org-create-math-formula' but check local cache first."
  14231. (let* ((absprefix (expand-file-name prefix dir))
  14232. (print-length nil) (print-level nil)
  14233. (formula-id (concat
  14234. "formula-"
  14235. (sha1
  14236. (prin1-to-string
  14237. (list latex-frag
  14238. org-latex-to-mathml-convert-command)))))
  14239. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14240. (formula-cache-dir (file-name-directory formula-cache)))
  14241. (unless (file-directory-p formula-cache-dir)
  14242. (make-directory formula-cache-dir t))
  14243. (unless (file-exists-p formula-cache)
  14244. (org-create-math-formula latex-frag formula-cache))
  14245. (if (file-exists-p formula-cache)
  14246. ;; Successful conversion. Return the link to MathML file.
  14247. (org-add-props
  14248. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14249. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14250. 'org-latex-src-embed-type (if latex-frag-type
  14251. 'paragraph 'character)))
  14252. ;; Failed conversion. Return the LaTeX fragment verbatim
  14253. latex-frag)))
  14254. (defun org-format-latex-as-html (latex-fragment)
  14255. "Convert LATEX-FRAGMENT to HTML.
  14256. This uses `org-latex-to-html-convert-command', which see."
  14257. (let ((cmd (format-spec org-latex-to-html-convert-command
  14258. `((?i . ,latex-fragment)))))
  14259. (message "Running %s" cmd)
  14260. (shell-command-to-string cmd)))
  14261. (defun org--get-display-dpi ()
  14262. "Get the DPI of the display.
  14263. The function assumes that the display has the same pixel width in
  14264. the horizontal and vertical directions."
  14265. (if (display-graphic-p)
  14266. (round (/ (display-pixel-height)
  14267. (/ (display-mm-height) 25.4)))
  14268. (error "Attempt to calculate the dpi of a non-graphic display")))
  14269. (defun org-create-formula-image
  14270. (string tofile options buffer &optional processing-type)
  14271. "Create an image from LaTeX source using external processes.
  14272. The LaTeX STRING is saved to a temporary LaTeX file, then
  14273. converted to an image file by process PROCESSING-TYPE defined in
  14274. `org-preview-latex-process-alist'. A nil value defaults to
  14275. `org-preview-latex-default-process'.
  14276. The generated image file is eventually moved to TOFILE.
  14277. The OPTIONS argument controls the size, foreground color and
  14278. background color of the generated image.
  14279. When BUFFER non-nil, this function is used for LaTeX previewing.
  14280. Otherwise, it is used to deal with LaTeX snippets showed in
  14281. a HTML file."
  14282. (let* ((processing-type (or processing-type
  14283. org-preview-latex-default-process))
  14284. (processing-info
  14285. (cdr (assq processing-type org-preview-latex-process-alist)))
  14286. (programs (plist-get processing-info :programs))
  14287. (error-message (or (plist-get processing-info :message) ""))
  14288. (image-input-type (plist-get processing-info :image-input-type))
  14289. (image-output-type (plist-get processing-info :image-output-type))
  14290. (post-clean (or (plist-get processing-info :post-clean)
  14291. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14292. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14293. (latex-header
  14294. (or (plist-get processing-info :latex-header)
  14295. (org-latex-make-preamble
  14296. (org-export-get-environment (org-export-get-backend 'latex))
  14297. org-format-latex-header
  14298. 'snippet)))
  14299. (latex-compiler (plist-get processing-info :latex-compiler))
  14300. (tmpdir temporary-file-directory)
  14301. (texfilebase (make-temp-name
  14302. (expand-file-name "orgtex" tmpdir)))
  14303. (texfile (concat texfilebase ".tex"))
  14304. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14305. '(1.0 . 1.0)))
  14306. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14307. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14308. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14309. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14310. "Black"))
  14311. (bg (or (plist-get options (if buffer :background :html-background))
  14312. "Transparent"))
  14313. (image-converter
  14314. (or (and (string= bg "Transparent")
  14315. (plist-get processing-info :transparent-image-converter))
  14316. (plist-get processing-info :image-converter)))
  14317. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14318. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14319. (dolist (program programs)
  14320. (org-check-external-command program error-message))
  14321. (if (eq fg 'default)
  14322. (setq fg (org-latex-color :foreground))
  14323. (setq fg (org-latex-color-format fg)))
  14324. (setq bg (cond
  14325. ((eq bg 'default) (org-latex-color :background))
  14326. ((string= bg "Transparent") nil)
  14327. (t (org-latex-color-format bg))))
  14328. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14329. (if (string-suffix-p string "\n")
  14330. (aset string (1- (length string)) ?%)
  14331. (setq string (concat string "%")))
  14332. (with-temp-file texfile
  14333. (insert latex-header)
  14334. (insert "\n\\begin{document}\n"
  14335. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14336. (if bg
  14337. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14338. "\n\\pagecolor{bg}%\n")
  14339. "")
  14340. "\n{\\color{fg}\n"
  14341. string
  14342. "\n}\n"
  14343. "\n\\end{document}\n"))
  14344. (let* ((err-msg (format "Please adjust `%s' part of \
  14345. `org-preview-latex-process-alist'."
  14346. processing-type))
  14347. (image-input-file
  14348. (org-compile-file
  14349. texfile latex-compiler image-input-type err-msg log-buf))
  14350. (image-output-file
  14351. (org-compile-file
  14352. image-input-file image-converter image-output-type err-msg log-buf
  14353. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14354. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14355. (copy-file image-output-file tofile 'replace)
  14356. (dolist (e post-clean)
  14357. (when (file-exists-p (concat texfilebase e))
  14358. (delete-file (concat texfilebase e))))
  14359. image-output-file)))
  14360. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14361. "Fill a LaTeX header template TPL.
  14362. In the template, the following place holders will be recognized:
  14363. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14364. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14365. [PACKAGES] \\usepackage statements for PKG
  14366. [NO-PACKAGES] do not include PKG
  14367. [EXTRA] the string EXTRA
  14368. [NO-EXTRA] do not include EXTRA
  14369. For backward compatibility, if both the positive and the negative place
  14370. holder is missing, the positive one (without the \"NO-\") will be
  14371. assumed to be present at the end of the template.
  14372. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14373. EXTRA is a string.
  14374. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14375. (let (rpl (end ""))
  14376. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14377. (setq rpl (if (or (match-end 1) (not def-pkg))
  14378. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14379. tpl (replace-match rpl t t tpl))
  14380. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14381. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14382. (setq rpl (if (or (match-end 1) (not pkg))
  14383. "" (org-latex-packages-to-string pkg snippets-p t))
  14384. tpl (replace-match rpl t t tpl))
  14385. (when pkg (setq end
  14386. (concat end "\n"
  14387. (org-latex-packages-to-string pkg snippets-p)))))
  14388. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14389. (setq rpl (if (or (match-end 1) (not extra))
  14390. "" (concat extra "\n"))
  14391. tpl (replace-match rpl t t tpl))
  14392. (when (and extra (string-match "\\S-" extra))
  14393. (setq end (concat end "\n" extra))))
  14394. (if (string-match "\\S-" end)
  14395. (concat tpl "\n" end)
  14396. tpl)))
  14397. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14398. "Turn an alist of packages into a string with the \\usepackage macros."
  14399. (setq pkg (mapconcat (lambda(p)
  14400. (cond
  14401. ((stringp p) p)
  14402. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14403. (format "%% Package %s omitted" (cadr p)))
  14404. ((equal "" (car p))
  14405. (format "\\usepackage{%s}" (cadr p)))
  14406. (t
  14407. (format "\\usepackage[%s]{%s}"
  14408. (car p) (cadr p)))))
  14409. pkg
  14410. "\n"))
  14411. (if newline (concat pkg "\n") pkg))
  14412. (defun org-dvipng-color (attr)
  14413. "Return a RGB color specification for dvipng."
  14414. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14415. (defun org-dvipng-color-format (color-name)
  14416. "Convert COLOR-NAME to a RGB color value for dvipng."
  14417. (apply #'format "rgb %s %s %s"
  14418. (mapcar 'org-normalize-color
  14419. (color-values color-name))))
  14420. (defun org-latex-color (attr)
  14421. "Return a RGB color for the LaTeX color package."
  14422. (org-latex-color-format (face-attribute 'default attr nil)))
  14423. (defun org-latex-color-format (color-name)
  14424. "Convert COLOR-NAME to a RGB color value."
  14425. (apply #'format "%s,%s,%s"
  14426. (mapcar 'org-normalize-color
  14427. (color-values color-name))))
  14428. (defun org-normalize-color (value)
  14429. "Return string to be used as color value for an RGB component."
  14430. (format "%g" (/ value 65535.0)))
  14431. ;; Image display
  14432. (defvar-local org-inline-image-overlays nil)
  14433. (defun org-toggle-inline-images (&optional include-linked)
  14434. "Toggle the display of inline images.
  14435. INCLUDE-LINKED is passed to `org-display-inline-images'."
  14436. (interactive "P")
  14437. (if org-inline-image-overlays
  14438. (progn
  14439. (org-remove-inline-images)
  14440. (when (called-interactively-p 'interactive)
  14441. (message "Inline image display turned off")))
  14442. (org-display-inline-images include-linked)
  14443. (when (called-interactively-p 'interactive)
  14444. (message (if org-inline-image-overlays
  14445. (format "%d images displayed inline"
  14446. (length org-inline-image-overlays))
  14447. "No images to display inline")))))
  14448. (defun org-redisplay-inline-images ()
  14449. "Assure display of inline images and refresh them."
  14450. (interactive)
  14451. (org-toggle-inline-images)
  14452. (unless org-inline-image-overlays
  14453. (org-toggle-inline-images)))
  14454. ;; For without-x builds.
  14455. (declare-function image-refresh "image" (spec &optional frame))
  14456. (defcustom org-display-remote-inline-images 'skip
  14457. "How to display remote inline images.
  14458. Possible values of this option are:
  14459. skip Don't display remote images.
  14460. download Always download and display remote images.
  14461. cache Display remote images, and open them in separate buffers
  14462. for caching. Silently update the image buffer when a file
  14463. change is detected."
  14464. :group 'org-appearance
  14465. :package-version '(Org . "9.4")
  14466. :type '(choice
  14467. (const :tag "Ignore remote images" skip)
  14468. (const :tag "Always display remote images" download)
  14469. (const :tag "Display and silently update remote images" cache))
  14470. :safe #'symbolp)
  14471. (defun org--create-inline-image (file width)
  14472. "Create image located at FILE, or return nil.
  14473. WIDTH is the width of the image. The image may not be created
  14474. according to the value of `org-display-remote-inline-images'."
  14475. (let* ((remote? (file-remote-p file))
  14476. (file-or-data
  14477. (pcase org-display-remote-inline-images
  14478. ((guard (not remote?)) file)
  14479. (`download (with-temp-buffer
  14480. (set-buffer-multibyte nil)
  14481. (insert-file-contents-literally file)
  14482. (buffer-string)))
  14483. (`cache (let ((revert-without-query '(".")))
  14484. (with-current-buffer (find-file-noselect file)
  14485. (buffer-string))))
  14486. (`skip nil)
  14487. (other
  14488. (message "Invalid value of `org-display-remote-inline-images': %S"
  14489. other)
  14490. nil))))
  14491. (when file-or-data
  14492. (create-image file-or-data
  14493. (and (image-type-available-p 'imagemagick)
  14494. width
  14495. 'imagemagick)
  14496. remote?
  14497. :width width :scale 1))))
  14498. (defun org-display-inline-images (&optional include-linked refresh beg end)
  14499. "Display inline images.
  14500. An inline image is a link which follows either of these
  14501. conventions:
  14502. 1. Its path is a file with an extension matching return value
  14503. from `image-file-name-regexp' and it has no contents.
  14504. 2. Its description consists in a single link of the previous
  14505. type. In this case, that link must be a well-formed plain
  14506. or angle link, i.e., it must have an explicit \"file\" type.
  14507. Equip each image with the key-map `image-map'.
  14508. When optional argument INCLUDE-LINKED is non-nil, also links with
  14509. a text description part will be inlined. This can be nice for
  14510. a quick look at those images, but it does not reflect what
  14511. exported files will look like.
  14512. When optional argument REFRESH is non-nil, refresh existing
  14513. images between BEG and END. This will create new image displays
  14514. only if necessary.
  14515. BEG and END define the considered part. They default to the
  14516. buffer boundaries with possible narrowing."
  14517. (interactive "P")
  14518. (when (display-graphic-p)
  14519. (unless refresh
  14520. (org-remove-inline-images)
  14521. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  14522. (let ((end (or end (point-max))))
  14523. (org-with-point-at (or beg (point-min))
  14524. (let* ((case-fold-search t)
  14525. (file-extension-re (image-file-name-regexp))
  14526. (link-abbrevs (mapcar #'car
  14527. (append org-link-abbrev-alist-local
  14528. org-link-abbrev-alist)))
  14529. ;; Check absolute, relative file names and explicit
  14530. ;; "file:" links. Also check link abbreviations since
  14531. ;; some might expand to "file" links.
  14532. (file-types-re
  14533. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  14534. (if (not link-abbrevs) ""
  14535. (concat "\\|" (regexp-opt link-abbrevs))))))
  14536. (while (re-search-forward file-types-re end t)
  14537. (let* ((link (org-element-lineage
  14538. (save-match-data (org-element-context))
  14539. '(link) t))
  14540. (linktype (org-element-property :type link))
  14541. (inner-start (match-beginning 1))
  14542. (path
  14543. (cond
  14544. ;; No link at point; no inline image.
  14545. ((not link) nil)
  14546. ;; File link without a description. Also handle
  14547. ;; INCLUDE-LINKED here since it should have
  14548. ;; precedence over the next case. I.e., if link
  14549. ;; contains filenames in both the path and the
  14550. ;; description, prioritize the path only when
  14551. ;; INCLUDE-LINKED is non-nil.
  14552. ((or (not (org-element-property :contents-begin link))
  14553. include-linked)
  14554. (and (or (equal "file" linktype)
  14555. (equal "attachment" linktype))
  14556. (org-element-property :path link)))
  14557. ;; Link with a description. Check if description
  14558. ;; is a filename. Even if Org doesn't have syntax
  14559. ;; for those -- clickable image -- constructs, fake
  14560. ;; them, as in `org-export-insert-image-links'.
  14561. ((not inner-start) nil)
  14562. (t
  14563. (org-with-point-at inner-start
  14564. (and (looking-at
  14565. (if (char-equal ?< (char-after inner-start))
  14566. org-link-angle-re
  14567. org-link-plain-re))
  14568. ;; File name must fill the whole
  14569. ;; description.
  14570. (= (org-element-property :contents-end link)
  14571. (match-end 0))
  14572. (match-string 2)))))))
  14573. (when (and path (string-match-p file-extension-re path))
  14574. (let ((file (if (equal "attachment" linktype)
  14575. (progn
  14576. (require 'org-attach)
  14577. (ignore-errors (org-attach-expand path)))
  14578. (expand-file-name path))))
  14579. (when (and file (file-exists-p file))
  14580. (let ((width (org-display-inline-image--width link))
  14581. (old (get-char-property-and-overlay
  14582. (org-element-property :begin link)
  14583. 'org-image-overlay)))
  14584. (if (and (car-safe old) refresh)
  14585. (image-refresh (overlay-get (cdr old) 'display))
  14586. (let ((image (org--create-inline-image file width)))
  14587. (when image
  14588. (let ((ov (make-overlay
  14589. (org-element-property :begin link)
  14590. (progn
  14591. (goto-char
  14592. (org-element-property :end link))
  14593. (skip-chars-backward " \t")
  14594. (point)))))
  14595. (overlay-put ov 'display image)
  14596. (overlay-put ov 'face 'default)
  14597. (overlay-put ov 'org-image-overlay t)
  14598. (overlay-put
  14599. ov 'modification-hooks
  14600. (list 'org-display-inline-remove-overlay))
  14601. (when (boundp 'image-map)
  14602. (overlay-put ov 'keymap image-map))
  14603. (push ov org-inline-image-overlays))))))))))))))))
  14604. (defvar visual-fill-column-width) ; Silence compiler warning
  14605. (defun org-display-inline-image--width (link)
  14606. "Determine the display width of the image LINK, in pixels.
  14607. - When `org-image-actual-width' is t, the image's pixel width is used.
  14608. - When `org-image-actual-width' is a number, that value will is used.
  14609. - When `org-image-actual-width' is nil or a list, the first :width attribute
  14610. set (if it exists) is used to set the image width. A width of X% is
  14611. divided by 100.
  14612. If no :width attribute is given and `org-image-actual-width' is a list with
  14613. a number as the car, then that number is used as the default value.
  14614. If the value is a float between 0 and 2, it interpreted as that proportion
  14615. of the text width in the buffer."
  14616. ;; Apply `org-image-actual-width' specifications.
  14617. (cond
  14618. ((eq org-image-actual-width t) nil)
  14619. ((listp org-image-actual-width)
  14620. (let* ((case-fold-search t)
  14621. (par (org-element-lineage link '(paragraph)))
  14622. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  14623. (par-end (org-element-property :post-affiliated par))
  14624. ;; Try to find an attribute providing a :width.
  14625. (attr-width
  14626. (when (and par (org-with-point-at
  14627. (org-element-property :begin par)
  14628. (re-search-forward attr-re par-end t)))
  14629. (match-string 1)))
  14630. (width
  14631. (cond
  14632. ;; Treat :width t as if `org-image-actual-width' were t.
  14633. ((string= attr-width "t") nil)
  14634. ;; Fallback to `org-image-actual-width' if no interprable width is given.
  14635. ((or (null attr-width)
  14636. (string-match-p "\\`[^0-9]" attr-width))
  14637. (car org-image-actual-width))
  14638. ;; Convert numeric widths to numbers, converting percentages.
  14639. ((string-match-p "\\`[0-9.]+%" attr-width)
  14640. (/ (string-to-number attr-width) 100.0))
  14641. (t (string-to-number attr-width)))))
  14642. (if (and (floatp width) (<= 0.0 width 2.0))
  14643. ;; A float in [0,2] should be interpereted as this portion of
  14644. ;; the text width in the window. This works well with cases like
  14645. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  14646. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  14647. ;; bound as cases such as 1.2\linewidth are feasible.
  14648. (round (* width
  14649. (window-pixel-width)
  14650. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  14651. (or visual-fill-column-width auto-fill-function))
  14652. (when auto-fill-function fill-column)
  14653. (- (window-text-width) (line-number-display-width)))
  14654. (float (window-total-width)))))
  14655. width)))
  14656. ((numberp org-image-actual-width)
  14657. org-image-actual-width)
  14658. (t nil)))
  14659. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  14660. "Remove inline-display overlay if a corresponding region is modified."
  14661. (let ((inhibit-modification-hooks t))
  14662. (when (and ov after)
  14663. (delete ov org-inline-image-overlays)
  14664. (delete-overlay ov))))
  14665. (defun org-remove-inline-images ()
  14666. "Remove inline display of images."
  14667. (interactive)
  14668. (mapc #'delete-overlay org-inline-image-overlays)
  14669. (setq org-inline-image-overlays nil))
  14670. (defvar org-self-insert-command-undo-counter 0)
  14671. (defvar org-speed-command nil)
  14672. (defun org-fix-tags-on-the-fly ()
  14673. "Align tags in headline at point.
  14674. Unlike `org-align-tags', this function does nothing if point is
  14675. either not currently on a tagged headline or on a tag."
  14676. (when (and (org-match-line org-tag-line-re)
  14677. (< (point) (match-beginning 1)))
  14678. (org-align-tags)))
  14679. (defun org-self-insert-command (N)
  14680. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  14681. If the cursor is in a table looking at whitespace, the whitespace is
  14682. overwritten, and the table is not marked as requiring realignment."
  14683. (interactive "p")
  14684. (org-fold-check-before-invisible-edit 'insert)
  14685. (cond
  14686. ((and org-use-speed-commands
  14687. (let ((kv (this-command-keys-vector)))
  14688. (setq org-speed-command
  14689. (run-hook-with-args-until-success
  14690. 'org-speed-command-hook
  14691. (make-string 1 (aref kv (1- (length kv))))))))
  14692. (cond
  14693. ((commandp org-speed-command)
  14694. (setq this-command org-speed-command)
  14695. (call-interactively org-speed-command))
  14696. ((functionp org-speed-command)
  14697. (funcall org-speed-command))
  14698. ((consp org-speed-command)
  14699. (eval org-speed-command t))
  14700. (t (let (org-use-speed-commands)
  14701. (call-interactively 'org-self-insert-command)))))
  14702. ((and
  14703. (= N 1)
  14704. (not (org-region-active-p))
  14705. (org-at-table-p)
  14706. (progn
  14707. ;; Check if we blank the field, and if that triggers align.
  14708. (and (featurep 'org-table)
  14709. org-table-auto-blank-field
  14710. (memq last-command
  14711. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  14712. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  14713. ;; Got extra space, this field does not determine
  14714. ;; column width.
  14715. (let (org-table-may-need-update) (org-table-blank-field))
  14716. ;; No extra space, this field may determine column
  14717. ;; width.
  14718. (org-table-blank-field)))
  14719. t)
  14720. (looking-at "[^|\n]* |"))
  14721. ;; There is room for insertion without re-aligning the table.
  14722. (self-insert-command N)
  14723. (org-table-with-shrunk-field
  14724. (save-excursion
  14725. (skip-chars-forward "^|")
  14726. ;; Do not delete last space, which is
  14727. ;; `org-table-separator-space', but the regular space before
  14728. ;; it.
  14729. (delete-region (- (point) 2) (1- (point))))))
  14730. (t
  14731. (setq org-table-may-need-update t)
  14732. (self-insert-command N)
  14733. (org-fix-tags-on-the-fly)
  14734. (when org-self-insert-cluster-for-undo
  14735. (if (not (eq last-command 'org-self-insert-command))
  14736. (setq org-self-insert-command-undo-counter 1)
  14737. (if (>= org-self-insert-command-undo-counter 20)
  14738. (setq org-self-insert-command-undo-counter 1)
  14739. (and (> org-self-insert-command-undo-counter 0)
  14740. buffer-undo-list (listp buffer-undo-list)
  14741. (not (cadr buffer-undo-list)) ; remove nil entry
  14742. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  14743. (setq org-self-insert-command-undo-counter
  14744. (1+ org-self-insert-command-undo-counter))))))))
  14745. (defun org-delete-backward-char (N)
  14746. "Like `delete-backward-char', insert whitespace at field end in tables.
  14747. When deleting backwards, in tables this function will insert whitespace in
  14748. front of the next \"|\" separator, to keep the table aligned. The table will
  14749. still be marked for re-alignment if the field did fill the entire column,
  14750. because, in this case the deletion might narrow the column."
  14751. (interactive "p")
  14752. (org-fold-core-ignore-modifications
  14753. (save-match-data
  14754. (org-fold-check-before-invisible-edit 'delete-backward)
  14755. (if (and (= N 1)
  14756. (not overwrite-mode)
  14757. (not (org-region-active-p))
  14758. (not (eq (char-before) ?|))
  14759. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  14760. (looking-at-p ".*?|")
  14761. (org-at-table-p))
  14762. (progn (forward-char -1) (org-delete-char 1))
  14763. (backward-delete-char N)
  14764. (org-fix-tags-on-the-fly)))))
  14765. (defun org-delete-char (N)
  14766. "Like `delete-char', but insert whitespace at field end in tables.
  14767. When deleting characters, in tables this function will insert whitespace in
  14768. front of the next \"|\" separator, to keep the table aligned. The table will
  14769. still be marked for re-alignment if the field did fill the entire column,
  14770. because, in this case the deletion might narrow the column."
  14771. (interactive "p")
  14772. (org-fold-core-ignore-modifications
  14773. (save-match-data
  14774. (org-fold-check-before-invisible-edit 'delete)
  14775. (cond
  14776. ((or (/= N 1)
  14777. (eq (char-after) ?|)
  14778. (save-excursion (skip-chars-backward " \t") (bolp))
  14779. (not (org-at-table-p)))
  14780. (delete-char N)
  14781. (org-fix-tags-on-the-fly))
  14782. ((looking-at ".\\(.*?\\)|")
  14783. (let* ((update? org-table-may-need-update)
  14784. (noalign (looking-at-p ".*? |")))
  14785. (delete-char 1)
  14786. (org-table-with-shrunk-field
  14787. (save-excursion
  14788. ;; Last space is `org-table-separator-space', so insert
  14789. ;; a regular one before it instead.
  14790. (goto-char (- (match-end 0) 2))
  14791. (insert " ")))
  14792. ;; If there were two spaces at the end, this field does not
  14793. ;; determine the width of the column.
  14794. (when noalign (setq org-table-may-need-update update?))))
  14795. (t
  14796. (delete-char N))))))
  14797. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  14798. (put 'org-self-insert-command 'delete-selection
  14799. (lambda ()
  14800. (not (run-hook-with-args-until-success
  14801. 'self-insert-uses-region-functions))))
  14802. (put 'orgtbl-self-insert-command 'delete-selection
  14803. (lambda ()
  14804. (not (run-hook-with-args-until-success
  14805. 'self-insert-uses-region-functions))))
  14806. (put 'org-delete-char 'delete-selection 'supersede)
  14807. (put 'org-delete-backward-char 'delete-selection 'supersede)
  14808. (put 'org-yank 'delete-selection 'yank)
  14809. (put 'org-return 'delete-selection t)
  14810. ;; Make `flyspell-mode' delay after some commands
  14811. (put 'org-self-insert-command 'flyspell-delayed t)
  14812. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  14813. (put 'org-delete-char 'flyspell-delayed t)
  14814. (put 'org-delete-backward-char 'flyspell-delayed t)
  14815. ;; Make pabbrev-mode expand after Org mode commands
  14816. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  14817. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  14818. (defun org-transpose-words ()
  14819. "Transpose words for Org.
  14820. This uses the `org-mode-transpose-word-syntax-table' syntax
  14821. table, which interprets characters in `org-emphasis-alist' as
  14822. word constituents."
  14823. (interactive)
  14824. (with-syntax-table org-mode-transpose-word-syntax-table
  14825. (call-interactively 'transpose-words)))
  14826. (defvar org-ctrl-c-ctrl-c-hook nil
  14827. "Hook for functions attaching themselves to `C-c C-c'.
  14828. This can be used to add additional functionality to the `C-c C-c'
  14829. key which executes context-dependent commands. This hook is run
  14830. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  14831. run after the last test.
  14832. Each function will be called with no arguments. The function
  14833. must check if the context is appropriate for it to act. If yes,
  14834. it should do its thing and then return a non-nil value. If the
  14835. context is wrong, just do nothing and return nil.")
  14836. (defvar org-ctrl-c-ctrl-c-final-hook nil
  14837. "Hook for functions attaching themselves to `C-c C-c'.
  14838. This can be used to add additional functionality to the `C-c C-c'
  14839. key which executes context-dependent commands. This hook is run
  14840. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  14841. before the first test.
  14842. Each function will be called with no arguments. The function
  14843. must check if the context is appropriate for it to act. If yes,
  14844. it should do its thing and then return a non-nil value. If the
  14845. context is wrong, just do nothing and return nil.")
  14846. (defvar org-tab-after-check-for-table-hook nil
  14847. "Hook for functions to attach themselves to TAB.
  14848. See `org-ctrl-c-ctrl-c-hook' for more information.
  14849. This hook runs after it has been established that the cursor is not in a
  14850. table, but before checking if the cursor is in a headline or if global cycling
  14851. should be done.
  14852. If any function in this hook returns t, not other actions like visibility
  14853. cycling will be done.")
  14854. (defvar org-tab-after-check-for-cycling-hook nil
  14855. "Hook for functions to attach themselves to TAB.
  14856. See `org-ctrl-c-ctrl-c-hook' for more information.
  14857. This hook runs after it has been established that not table field motion and
  14858. not visibility should be done because of current context. This is probably
  14859. the place where a package like yasnippets can hook in.")
  14860. (defvar org-tab-before-tab-emulation-hook nil
  14861. "Hook for functions to attach themselves to TAB.
  14862. See `org-ctrl-c-ctrl-c-hook' for more information.
  14863. This hook runs after every other options for TAB have been exhausted, but
  14864. before indentation and \t insertion takes place.")
  14865. (defvar org-metaleft-hook nil
  14866. "Hook for functions attaching themselves to `M-left'.
  14867. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14868. (defvar org-metaright-hook nil
  14869. "Hook for functions attaching themselves to `M-right'.
  14870. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14871. (defvar org-metaup-hook nil
  14872. "Hook for functions attaching themselves to `M-up'.
  14873. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14874. (defvar org-metadown-hook nil
  14875. "Hook for functions attaching themselves to `M-down'.
  14876. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14877. (defvar org-shiftmetaleft-hook nil
  14878. "Hook for functions attaching themselves to `M-S-left'.
  14879. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14880. (defvar org-shiftmetaright-hook nil
  14881. "Hook for functions attaching themselves to `M-S-right'.
  14882. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14883. (defvar org-shiftmetaup-hook nil
  14884. "Hook for functions attaching themselves to `M-S-up'.
  14885. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14886. (defvar org-shiftmetadown-hook nil
  14887. "Hook for functions attaching themselves to `M-S-down'.
  14888. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14889. (defvar org-metareturn-hook nil
  14890. "Hook for functions attaching themselves to `M-RET'.
  14891. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14892. (defvar org-shiftup-hook nil
  14893. "Hook for functions attaching themselves to `S-up'.
  14894. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14895. (defvar org-shiftup-final-hook nil
  14896. "Hook for functions attaching themselves to `S-up'.
  14897. This one runs after all other options except shift-select have been excluded.
  14898. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14899. (defvar org-shiftdown-hook nil
  14900. "Hook for functions attaching themselves to `S-down'.
  14901. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14902. (defvar org-shiftdown-final-hook nil
  14903. "Hook for functions attaching themselves to `S-down'.
  14904. This one runs after all other options except shift-select have been excluded.
  14905. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14906. (defvar org-shiftleft-hook nil
  14907. "Hook for functions attaching themselves to `S-left'.
  14908. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14909. (defvar org-shiftleft-final-hook nil
  14910. "Hook for functions attaching themselves to `S-left'.
  14911. This one runs after all other options except shift-select have been excluded.
  14912. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14913. (defvar org-shiftright-hook nil
  14914. "Hook for functions attaching themselves to `S-right'.
  14915. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14916. (defvar org-shiftright-final-hook nil
  14917. "Hook for functions attaching themselves to `S-right'.
  14918. This one runs after all other options except shift-select have been excluded.
  14919. See `org-ctrl-c-ctrl-c-hook' for more information.")
  14920. (defun org-modifier-cursor-error ()
  14921. "Throw an error, a modified cursor command was applied in wrong context."
  14922. (user-error "This command is active in special context like tables, headlines or items"))
  14923. (defun org-shiftselect-error ()
  14924. "Throw an error because Shift-Cursor command was applied in wrong context."
  14925. (if (and (boundp 'shift-select-mode) shift-select-mode)
  14926. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  14927. (user-error "This command works only in special context like headlines or timestamps")))
  14928. (defun org-call-for-shift-select (cmd)
  14929. (let ((this-command-keys-shift-translated t))
  14930. (call-interactively cmd)))
  14931. (defun org-shifttab (&optional arg)
  14932. "Global visibility cycling or move to previous table field.
  14933. Call `org-table-previous-field' within a table.
  14934. When ARG is nil, cycle globally through visibility states.
  14935. When ARG is a numeric prefix, show contents of this level."
  14936. (interactive "P")
  14937. (cond
  14938. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  14939. ((integerp arg)
  14940. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  14941. (message "Content view to level: %d" arg)
  14942. (org-cycle-content (prefix-numeric-value arg2))
  14943. (org-cycle-show-empty-lines t)
  14944. (setq org-cycle-global-status 'overview)
  14945. (run-hook-with-args 'org-cycle-hook 'overview)))
  14946. (t (call-interactively 'org-cycle-global))))
  14947. (defun org-shiftmetaleft ()
  14948. "Promote subtree or delete table column.
  14949. Calls `org-promote-subtree', `org-outdent-item-tree', or
  14950. `org-table-delete-column', depending on context. See the
  14951. individual commands for more information."
  14952. (interactive)
  14953. (cond
  14954. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  14955. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  14956. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  14957. ((if (not (org-region-active-p)) (org-at-item-p)
  14958. (save-excursion (goto-char (region-beginning))
  14959. (org-at-item-p)))
  14960. (call-interactively 'org-outdent-item-tree))
  14961. (t (org-modifier-cursor-error))))
  14962. (defun org-shiftmetaright ()
  14963. "Demote subtree or insert table column.
  14964. Calls `org-demote-subtree', `org-indent-item-tree', or
  14965. `org-table-insert-column', depending on context. See the
  14966. individual commands for more information."
  14967. (interactive)
  14968. (cond
  14969. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  14970. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  14971. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  14972. ((if (not (org-region-active-p)) (org-at-item-p)
  14973. (save-excursion (goto-char (region-beginning))
  14974. (org-at-item-p)))
  14975. (call-interactively 'org-indent-item-tree))
  14976. (t (org-modifier-cursor-error))))
  14977. (defun org-shiftmetaup (&optional _arg)
  14978. "Drag the line at point up.
  14979. In a table, kill the current row.
  14980. On a clock timestamp, update the value of the timestamp like `S-<up>'
  14981. but also adjust the previous clocked item in the clock history.
  14982. Everywhere else, drag the line at point up."
  14983. (interactive "P")
  14984. (cond
  14985. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  14986. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  14987. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  14988. (call-interactively 'org-timestamp-up)))
  14989. (t (call-interactively 'org-drag-line-backward))))
  14990. (defun org-shiftmetadown (&optional _arg)
  14991. "Drag the line at point down.
  14992. In a table, insert an empty row at the current line.
  14993. On a clock timestamp, update the value of the timestamp like `S-<down>'
  14994. but also adjust the previous clocked item in the clock history.
  14995. Everywhere else, drag the line at point down."
  14996. (interactive "P")
  14997. (cond
  14998. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  14999. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15000. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15001. (call-interactively 'org-timestamp-down)))
  15002. (t (call-interactively 'org-drag-line-forward))))
  15003. (defsubst org-hidden-tree-error ()
  15004. (user-error
  15005. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15006. (defun org-metaleft (&optional _arg)
  15007. "Promote heading, list item at point or move table column left.
  15008. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15009. depending on context. With no specific context, calls the Emacs
  15010. default `backward-word'. See the individual commands for more
  15011. information.
  15012. This function runs the hook `org-metaleft-hook' as a first step,
  15013. and returns at first non-nil value."
  15014. (interactive "P")
  15015. (cond
  15016. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15017. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15018. ((org-with-limited-levels
  15019. (or (org-at-heading-p)
  15020. (and (org-region-active-p)
  15021. (save-excursion
  15022. (goto-char (region-beginning))
  15023. (org-at-heading-p)))))
  15024. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15025. (call-interactively 'org-do-promote))
  15026. ;; At an inline task.
  15027. ((org-at-heading-p)
  15028. (call-interactively 'org-inlinetask-promote))
  15029. ((or (org-at-item-p)
  15030. (and (org-region-active-p)
  15031. (save-excursion
  15032. (goto-char (region-beginning))
  15033. (org-at-item-p))))
  15034. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15035. (call-interactively 'org-outdent-item))
  15036. (t (call-interactively 'backward-word))))
  15037. (defun org-metaright (&optional _arg)
  15038. "Demote heading, list item at point or move table column right.
  15039. In front of a drawer or a block keyword, indent it correctly.
  15040. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15041. `org-indent-drawer' or `org-indent-block' depending on context.
  15042. With no specific context, calls the Emacs default `forward-word'.
  15043. See the individual commands for more information.
  15044. This function runs the hook `org-metaright-hook' as a first step,
  15045. and returns at first non-nil value."
  15046. (interactive "P")
  15047. (cond
  15048. ((run-hook-with-args-until-success 'org-metaright-hook))
  15049. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15050. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15051. ((org-at-block-p) (call-interactively 'org-indent-block))
  15052. ((org-with-limited-levels
  15053. (or (org-at-heading-p)
  15054. (and (org-region-active-p)
  15055. (save-excursion
  15056. (goto-char (region-beginning))
  15057. (org-at-heading-p)))))
  15058. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15059. (call-interactively 'org-do-demote))
  15060. ;; At an inline task.
  15061. ((org-at-heading-p)
  15062. (call-interactively 'org-inlinetask-demote))
  15063. ((or (org-at-item-p)
  15064. (and (org-region-active-p)
  15065. (save-excursion
  15066. (goto-char (region-beginning))
  15067. (org-at-item-p))))
  15068. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15069. (call-interactively 'org-indent-item))
  15070. (t (call-interactively 'forward-word))))
  15071. (defun org-check-for-hidden (what)
  15072. "Check if there are hidden headlines/items in the current visual line.
  15073. WHAT can be either `headlines' or `items'. If the current line is
  15074. an outline or item heading and it has a folded subtree below it,
  15075. this function returns t, nil otherwise."
  15076. (let ((re (cond
  15077. ((eq what 'headlines) org-outline-regexp-bol)
  15078. ((eq what 'items) (org-item-beginning-re))
  15079. (t (error "This should not happen"))))
  15080. beg end)
  15081. (save-excursion
  15082. (catch 'exit
  15083. (unless (org-region-active-p)
  15084. (setq beg (point-at-bol))
  15085. (beginning-of-line 2)
  15086. (while (and (not (eobp)) ;; this is like `next-line'
  15087. (org-invisible-p (1- (point))))
  15088. (beginning-of-line 2))
  15089. (setq end (point))
  15090. (goto-char beg)
  15091. (goto-char (point-at-eol))
  15092. (setq end (max end (point)))
  15093. (while (re-search-forward re end t)
  15094. (when (org-invisible-p (match-beginning 0))
  15095. (throw 'exit t))))
  15096. nil))))
  15097. (defun org-metaup (&optional _arg)
  15098. "Move subtree up or move table row up.
  15099. Calls `org-move-subtree-up' or `org-table-move-row' or
  15100. `org-move-item-up', depending on context. See the individual commands
  15101. for more information."
  15102. (interactive "P")
  15103. (cond
  15104. ((run-hook-with-args-until-success 'org-metaup-hook))
  15105. ((org-region-active-p)
  15106. (let* ((a (save-excursion
  15107. (goto-char (region-beginning))
  15108. (line-beginning-position)))
  15109. (b (save-excursion
  15110. (goto-char (region-end))
  15111. (if (bolp) (1- (point)) (line-end-position))))
  15112. (c (save-excursion
  15113. (goto-char a)
  15114. (move-beginning-of-line 0)
  15115. (point)))
  15116. (d (save-excursion
  15117. (goto-char a)
  15118. (move-end-of-line 0)
  15119. (point))))
  15120. (transpose-regions a b c d)
  15121. (goto-char c)))
  15122. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15123. ((and (featurep 'org-inlinetask)
  15124. (org-inlinetask-in-task-p))
  15125. (org-drag-element-backward))
  15126. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15127. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15128. (t (org-drag-element-backward))))
  15129. (defun org-metadown (&optional _arg)
  15130. "Move subtree down or move table row down.
  15131. Calls `org-move-subtree-down' or `org-table-move-row' or
  15132. `org-move-item-down', depending on context. See the individual
  15133. commands for more information."
  15134. (interactive "P")
  15135. (cond
  15136. ((run-hook-with-args-until-success 'org-metadown-hook))
  15137. ((org-region-active-p)
  15138. (let* ((a (save-excursion
  15139. (goto-char (region-beginning))
  15140. (line-beginning-position)))
  15141. (b (save-excursion
  15142. (goto-char (region-end))
  15143. (if (bolp) (1- (point)) (line-end-position))))
  15144. (c (save-excursion
  15145. (goto-char b)
  15146. (move-beginning-of-line (if (bolp) 1 2))
  15147. (point)))
  15148. (d (save-excursion
  15149. (goto-char b)
  15150. (move-end-of-line (if (bolp) 1 2))
  15151. (point))))
  15152. (transpose-regions a b c d)
  15153. (goto-char d)))
  15154. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15155. ((and (featurep 'org-inlinetask)
  15156. (org-inlinetask-in-task-p))
  15157. (org-drag-element-forward))
  15158. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15159. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15160. (t (org-drag-element-forward))))
  15161. (defun org-shiftup (&optional arg)
  15162. "Act on current element according to context.
  15163. Call `org-timestamp-up' or `org-priority-up', or
  15164. `org-previous-item', or `org-table-move-cell-up'. See the
  15165. individual commands for more information."
  15166. (interactive "P")
  15167. (cond
  15168. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15169. ((and org-support-shift-select (org-region-active-p))
  15170. (org-call-for-shift-select 'previous-line))
  15171. ((org-at-timestamp-p 'lax)
  15172. (call-interactively (if org-edit-timestamp-down-means-later
  15173. 'org-timestamp-down 'org-timestamp-up)))
  15174. ((and (not (eq org-support-shift-select 'always))
  15175. org-priority-enable-commands
  15176. (org-at-heading-p))
  15177. (call-interactively 'org-priority-up))
  15178. ((and (not org-support-shift-select) (org-at-item-p))
  15179. (call-interactively 'org-previous-item))
  15180. ((org-clocktable-try-shift 'up arg))
  15181. ((and (not (eq org-support-shift-select 'always))
  15182. (org-at-table-p))
  15183. (org-table-move-cell-up))
  15184. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15185. (org-support-shift-select
  15186. (org-call-for-shift-select 'previous-line))
  15187. (t (org-shiftselect-error))))
  15188. (defun org-shiftdown (&optional arg)
  15189. "Act on current element according to context.
  15190. Call `org-timestamp-down' or `org-priority-down', or
  15191. `org-next-item', or `org-table-move-cell-down'. See the
  15192. individual commands for more information."
  15193. (interactive "P")
  15194. (cond
  15195. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15196. ((and org-support-shift-select (org-region-active-p))
  15197. (org-call-for-shift-select 'next-line))
  15198. ((org-at-timestamp-p 'lax)
  15199. (call-interactively (if org-edit-timestamp-down-means-later
  15200. 'org-timestamp-up 'org-timestamp-down)))
  15201. ((and (not (eq org-support-shift-select 'always))
  15202. org-priority-enable-commands
  15203. (org-at-heading-p))
  15204. (call-interactively 'org-priority-down))
  15205. ((and (not org-support-shift-select) (org-at-item-p))
  15206. (call-interactively 'org-next-item))
  15207. ((org-clocktable-try-shift 'down arg))
  15208. ((and (not (eq org-support-shift-select 'always))
  15209. (org-at-table-p))
  15210. (org-table-move-cell-down))
  15211. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15212. (org-support-shift-select
  15213. (org-call-for-shift-select 'next-line))
  15214. (t (org-shiftselect-error))))
  15215. (defun org-shiftright (&optional arg)
  15216. "Act on the current element according to context.
  15217. This does one of the following:
  15218. - switch a timestamp at point one day into the future
  15219. - on a headline, switch to the next TODO keyword
  15220. - on an item, switch entire list to the next bullet type
  15221. - on a property line, switch to the next allowed value
  15222. - on a clocktable definition line, move time block into the future
  15223. - in a table, move a single cell right"
  15224. (interactive "P")
  15225. (cond
  15226. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15227. ((and org-support-shift-select (org-region-active-p))
  15228. (org-call-for-shift-select 'forward-char))
  15229. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15230. ((and (not (eq org-support-shift-select 'always))
  15231. (org-at-heading-p))
  15232. (let ((org-inhibit-logging
  15233. (not org-treat-S-cursor-todo-selection-as-state-change))
  15234. (org-inhibit-blocking
  15235. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15236. (org-call-with-arg 'org-todo 'right)))
  15237. ((or (and org-support-shift-select
  15238. (not (eq org-support-shift-select 'always))
  15239. (org-at-item-bullet-p))
  15240. (and (not org-support-shift-select) (org-at-item-p)))
  15241. (org-call-with-arg 'org-cycle-list-bullet nil))
  15242. ((and (not (eq org-support-shift-select 'always))
  15243. (org-at-property-p))
  15244. (call-interactively 'org-property-next-allowed-value))
  15245. ((org-clocktable-try-shift 'right arg))
  15246. ((and (not (eq org-support-shift-select 'always))
  15247. (org-at-table-p))
  15248. (org-table-move-cell-right))
  15249. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15250. (org-support-shift-select
  15251. (org-call-for-shift-select 'forward-char))
  15252. (t (org-shiftselect-error))))
  15253. (defun org-shiftleft (&optional arg)
  15254. "Act on current element according to context.
  15255. This does one of the following:
  15256. - switch a timestamp at point one day into the past
  15257. - on a headline, switch to the previous TODO keyword.
  15258. - on an item, switch entire list to the previous bullet type
  15259. - on a property line, switch to the previous allowed value
  15260. - on a clocktable definition line, move time block into the past
  15261. - in a table, move a single cell left"
  15262. (interactive "P")
  15263. (cond
  15264. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15265. ((and org-support-shift-select (org-region-active-p))
  15266. (org-call-for-shift-select 'backward-char))
  15267. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15268. ((and (not (eq org-support-shift-select 'always))
  15269. (org-at-heading-p))
  15270. (let ((org-inhibit-logging
  15271. (not org-treat-S-cursor-todo-selection-as-state-change))
  15272. (org-inhibit-blocking
  15273. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15274. (org-call-with-arg 'org-todo 'left)))
  15275. ((or (and org-support-shift-select
  15276. (not (eq org-support-shift-select 'always))
  15277. (org-at-item-bullet-p))
  15278. (and (not org-support-shift-select) (org-at-item-p)))
  15279. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15280. ((and (not (eq org-support-shift-select 'always))
  15281. (org-at-property-p))
  15282. (call-interactively 'org-property-previous-allowed-value))
  15283. ((org-clocktable-try-shift 'left arg))
  15284. ((and (not (eq org-support-shift-select 'always))
  15285. (org-at-table-p))
  15286. (org-table-move-cell-left))
  15287. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15288. (org-support-shift-select
  15289. (org-call-for-shift-select 'backward-char))
  15290. (t (org-shiftselect-error))))
  15291. (defun org-shiftcontrolright ()
  15292. "Switch to next TODO set."
  15293. (interactive)
  15294. (cond
  15295. ((and org-support-shift-select (org-region-active-p))
  15296. (org-call-for-shift-select 'forward-word))
  15297. ((and (not (eq org-support-shift-select 'always))
  15298. (org-at-heading-p))
  15299. (org-call-with-arg 'org-todo 'nextset))
  15300. (org-support-shift-select
  15301. (org-call-for-shift-select 'forward-word))
  15302. (t (org-shiftselect-error))))
  15303. (defun org-shiftcontrolleft ()
  15304. "Switch to previous TODO set."
  15305. (interactive)
  15306. (cond
  15307. ((and org-support-shift-select (org-region-active-p))
  15308. (org-call-for-shift-select 'backward-word))
  15309. ((and (not (eq org-support-shift-select 'always))
  15310. (org-at-heading-p))
  15311. (org-call-with-arg 'org-todo 'previousset))
  15312. (org-support-shift-select
  15313. (org-call-for-shift-select 'backward-word))
  15314. (t (org-shiftselect-error))))
  15315. (defun org-shiftcontrolup (&optional n)
  15316. "Change timestamps synchronously up in CLOCK log lines.
  15317. Optional argument N tells to change by that many units."
  15318. (interactive "P")
  15319. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15320. (let (org-support-shift-select)
  15321. (org-clock-timestamps-up n))
  15322. (user-error "Not at a clock log")))
  15323. (defun org-shiftcontroldown (&optional n)
  15324. "Change timestamps synchronously down in CLOCK log lines.
  15325. Optional argument N tells to change by that many units."
  15326. (interactive "P")
  15327. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15328. (let (org-support-shift-select)
  15329. (org-clock-timestamps-down n))
  15330. (user-error "Not at a clock log")))
  15331. (defun org-increase-number-at-point (&optional inc)
  15332. "Increment the number at point.
  15333. With an optional prefix numeric argument INC, increment using
  15334. this numeric value."
  15335. (interactive "p")
  15336. (if (not (number-at-point))
  15337. (user-error "Not on a number")
  15338. (unless inc (setq inc 1))
  15339. (let ((pos (point))
  15340. (beg (skip-chars-backward "-+^/*0-9eE."))
  15341. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15342. (setq nap (buffer-substring-no-properties
  15343. (+ pos beg) (+ pos beg end)))
  15344. (delete-region (+ pos beg) (+ pos beg end))
  15345. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15346. (when (org-at-table-p)
  15347. (org-table-align)
  15348. (org-table-end-of-field 1))))
  15349. (defun org-decrease-number-at-point (&optional inc)
  15350. "Decrement the number at point.
  15351. With an optional prefix numeric argument INC, decrement using
  15352. this numeric value."
  15353. (interactive "p")
  15354. (org-increase-number-at-point (- (or inc 1))))
  15355. (defun org-ctrl-c-ret ()
  15356. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15357. (interactive)
  15358. (cond
  15359. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15360. (t (call-interactively 'org-insert-heading))))
  15361. (defun org-copy-visible (beg end)
  15362. "Copy the visible parts of the region."
  15363. (interactive "r")
  15364. (let ((result ""))
  15365. (while (/= beg end)
  15366. (if (eq org-fold-core-style 'text-properties)
  15367. (progn
  15368. (while (org-invisible-p beg)
  15369. (setq beg (org-fold-next-visibility-change beg end)))
  15370. (let ((next (org-fold-next-visibility-change beg end)))
  15371. (setq result (concat result (buffer-substring beg next)))
  15372. (setq beg next)))
  15373. (when (invisible-p beg)
  15374. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  15375. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  15376. (setq result (concat result (buffer-substring beg next)))
  15377. (setq beg next))))
  15378. (setq deactivate-mark t)
  15379. (kill-new result)
  15380. (message "Visible strings have been copied to the kill ring.")))
  15381. (defun org-copy-special ()
  15382. "Copy region in table or copy current subtree.
  15383. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  15384. context. See the individual commands for more information."
  15385. (interactive)
  15386. (call-interactively
  15387. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  15388. (defun org-cut-special ()
  15389. "Cut region in table or cut current subtree.
  15390. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  15391. context. See the individual commands for more information."
  15392. (interactive)
  15393. (call-interactively
  15394. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  15395. (defun org-paste-special (arg)
  15396. "Paste rectangular region into table, or past subtree relative to level.
  15397. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  15398. See the individual commands for more information."
  15399. (interactive "P")
  15400. (if (org-at-table-p)
  15401. (org-table-paste-rectangle)
  15402. (org-paste-subtree arg)))
  15403. (defun org-edit-special (&optional arg)
  15404. "Call a special editor for the element at point.
  15405. When at a table, call the formula editor with `org-table-edit-formulas'.
  15406. When in a source code block, call `org-edit-src-code'.
  15407. When in a fixed-width region, call `org-edit-fixed-width-region'.
  15408. When in an export block, call `org-edit-export-block'.
  15409. When in a LaTeX environment, call `org-edit-latex-environment'.
  15410. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  15411. When at a footnote reference, call `org-edit-footnote-reference'.
  15412. When at a planning line call, `org-deadline' and/or `org-schedule'.
  15413. When at an active timestamp, call `org-time-stamp'.
  15414. When at an inactive timestamp, call `org-time-stamp-inactive'.
  15415. On a link, call `ffap' to visit the link at point.
  15416. Otherwise, return a user error."
  15417. (interactive "P")
  15418. (let ((element (org-element-at-point)))
  15419. (barf-if-buffer-read-only)
  15420. (pcase (org-element-type element)
  15421. (`src-block
  15422. (if (not arg) (org-edit-src-code)
  15423. (let* ((info (org-babel-get-src-block-info))
  15424. (lang (nth 0 info))
  15425. (params (nth 2 info))
  15426. (session (cdr (assq :session params))))
  15427. (if (not session) (org-edit-src-code)
  15428. ;; At a source block with a session and function called
  15429. ;; with an ARG: switch to the buffer related to the
  15430. ;; inferior process.
  15431. (switch-to-buffer
  15432. (funcall (intern (concat "org-babel-prep-session:" lang))
  15433. session params))))))
  15434. (`keyword
  15435. (unless (member (org-element-property :key element)
  15436. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  15437. (user-error "No special environment to edit here"))
  15438. (let ((value (org-element-property :value element)))
  15439. (unless (org-string-nw-p value) (user-error "No file to edit"))
  15440. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  15441. (or (match-string 1 value)
  15442. (match-string 0 value)))))
  15443. (when (org-url-p file)
  15444. (user-error "Files located with a URL cannot be edited"))
  15445. (org-link-open-from-string
  15446. (format "[[%s]]" (expand-file-name file))))))
  15447. (`table
  15448. (if (eq (org-element-property :type element) 'table.el)
  15449. (org-edit-table.el)
  15450. (call-interactively 'org-table-edit-formulas)))
  15451. ;; Only Org tables contain `table-row' type elements.
  15452. (`table-row (call-interactively 'org-table-edit-formulas))
  15453. (`example-block (org-edit-src-code))
  15454. (`export-block (org-edit-export-block))
  15455. (`fixed-width (org-edit-fixed-width-region))
  15456. (`latex-environment (org-edit-latex-environment))
  15457. (`planning
  15458. (let ((proplist (cadr element)))
  15459. (mapc #'call-interactively
  15460. (remq nil
  15461. (list
  15462. (when (plist-get proplist :deadline) #'org-deadline)
  15463. (when (plist-get proplist :scheduled) #'org-schedule))))))
  15464. (_
  15465. ;; No notable element at point. Though, we may be at a link or
  15466. ;; a footnote reference, which are objects. Thus, scan deeper.
  15467. (let ((context (org-element-context element)))
  15468. (pcase (org-element-type context)
  15469. (`footnote-reference (org-edit-footnote-reference))
  15470. (`inline-src-block (org-edit-inline-src-code))
  15471. (`latex-fragment (org-edit-latex-fragment))
  15472. (`timestamp (if (eq 'inactive (org-element-property :type context))
  15473. (call-interactively #'org-time-stamp-inactive)
  15474. (call-interactively #'org-time-stamp)))
  15475. (`link (call-interactively #'ffap))
  15476. (_ (user-error "No special environment to edit here"))))))))
  15477. (defun org-ctrl-c-ctrl-c (&optional arg)
  15478. "Set tags in headline, or update according to changed information at point.
  15479. This command does many different things, depending on context:
  15480. - If column view is active, in agenda or org buffers, quit it.
  15481. - If there are highlights, remove them.
  15482. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  15483. this is what we do.
  15484. - If the cursor is on a statistics cookie, update it.
  15485. - If the cursor is in a headline, in an agenda or an org buffer,
  15486. prompt for tags and insert them into the current line, aligned
  15487. to `org-tags-column'. When called with prefix arg, realign all
  15488. tags in the current buffer.
  15489. - If the cursor is in one of the special #+KEYWORD lines, this
  15490. triggers scanning the buffer for these lines and updating the
  15491. information.
  15492. - If the cursor is inside a table, realign the table. This command
  15493. works even if the automatic table editor has been turned off.
  15494. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  15495. the entire table.
  15496. - If the cursor is at a footnote reference or definition, jump to
  15497. the corresponding definition or references, respectively.
  15498. - If the cursor is a the beginning of a dynamic block, update it.
  15499. - If the current buffer is a capture buffer, close note and file it.
  15500. - If the cursor is on a <<<target>>>, update radio targets and
  15501. corresponding links in this buffer.
  15502. - If the cursor is on a numbered item in a plain list, renumber the
  15503. ordered list.
  15504. - If the cursor is on a checkbox, toggle it.
  15505. - If the cursor is on a code block, evaluate it. The variable
  15506. `org-confirm-babel-evaluate' can be used to control prompting
  15507. before code block evaluation, by default every code block
  15508. evaluation requires confirmation. Code block evaluation can be
  15509. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  15510. (interactive "P")
  15511. (cond
  15512. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  15513. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  15514. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  15515. (org-remove-occur-highlights)
  15516. (message "Temporary highlights/overlays removed from current buffer"))
  15517. ((and (local-variable-p 'org-finish-function)
  15518. (fboundp org-finish-function))
  15519. (funcall org-finish-function))
  15520. ((org-babel-hash-at-point))
  15521. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  15522. (t
  15523. (let* ((context
  15524. (org-element-lineage
  15525. (org-element-context)
  15526. ;; Limit to supported contexts.
  15527. '(babel-call clock dynamic-block footnote-definition
  15528. footnote-reference inline-babel-call inline-src-block
  15529. inlinetask item keyword node-property paragraph
  15530. plain-list planning property-drawer radio-target
  15531. src-block statistics-cookie table table-cell table-row
  15532. timestamp)
  15533. t))
  15534. (radio-list-p (org-at-radio-list-p))
  15535. (type (org-element-type context)))
  15536. ;; For convenience: at the first line of a paragraph on the same
  15537. ;; line as an item, apply function on that item instead.
  15538. (when (eq type 'paragraph)
  15539. (let ((parent (org-element-property :parent context)))
  15540. (when (and (eq (org-element-type parent) 'item)
  15541. (= (line-beginning-position)
  15542. (org-element-property :begin parent)))
  15543. (setq context parent)
  15544. (setq type 'item))))
  15545. ;; Act according to type of element or object at point.
  15546. ;;
  15547. ;; Do nothing on a blank line, except if it is contained in
  15548. ;; a source block. Hence, we first check if point is in such
  15549. ;; a block and then if it is at a blank line.
  15550. (pcase type
  15551. ((or `inline-src-block `src-block)
  15552. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  15553. (org-babel-eval-wipe-error-buffer)
  15554. (org-babel-execute-src-block
  15555. current-prefix-arg (org-babel-get-src-block-info nil context))))
  15556. ((guard (org-match-line "[ \t]*$"))
  15557. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  15558. (user-error
  15559. (substitute-command-keys
  15560. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  15561. ((or `babel-call `inline-babel-call)
  15562. (let ((info (org-babel-lob-get-info context)))
  15563. (when info (org-babel-execute-src-block nil info))))
  15564. (`clock (org-clock-update-time-maybe))
  15565. (`dynamic-block
  15566. (save-excursion
  15567. (goto-char (org-element-property :post-affiliated context))
  15568. (org-update-dblock)))
  15569. (`footnote-definition
  15570. (goto-char (org-element-property :post-affiliated context))
  15571. (call-interactively 'org-footnote-action))
  15572. (`footnote-reference (call-interactively #'org-footnote-action))
  15573. ((or `headline `inlinetask)
  15574. (save-excursion (goto-char (org-element-property :begin context))
  15575. (call-interactively #'org-set-tags-command)))
  15576. (`item
  15577. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  15578. ;; unconditionally, whereas `C-u' will toggle its presence.
  15579. ;; Without a universal argument, if the item has a checkbox,
  15580. ;; toggle it. Otherwise repair the list.
  15581. (if (or radio-list-p
  15582. (and (boundp org-list-checkbox-radio-mode)
  15583. org-list-checkbox-radio-mode))
  15584. (org-toggle-radio-button arg)
  15585. (let* ((box (org-element-property :checkbox context))
  15586. (struct (org-element-property :structure context))
  15587. (old-struct (copy-tree struct))
  15588. (parents (org-list-parents-alist struct))
  15589. (prevs (org-list-prevs-alist struct))
  15590. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  15591. (org-list-set-checkbox
  15592. (org-element-property :begin context) struct
  15593. (cond ((equal arg '(16)) "[-]")
  15594. ((and (not box) (equal arg '(4))) "[ ]")
  15595. ((or (not box) (equal arg '(4))) nil)
  15596. ((eq box 'on) "[ ]")
  15597. (t "[X]")))
  15598. ;; Mimic `org-list-write-struct' but with grabbing a return
  15599. ;; value from `org-list-struct-fix-box'.
  15600. (org-list-struct-fix-ind struct parents 2)
  15601. (org-list-struct-fix-item-end struct)
  15602. (org-list-struct-fix-bul struct prevs)
  15603. (org-list-struct-fix-ind struct parents)
  15604. (let ((block-item
  15605. (org-list-struct-fix-box struct parents prevs orderedp)))
  15606. (if (and box (equal struct old-struct))
  15607. (if (equal arg '(16))
  15608. (message "Checkboxes already reset")
  15609. (user-error "Cannot toggle this checkbox: %s"
  15610. (if (eq box 'on)
  15611. "all subitems checked"
  15612. "unchecked subitems")))
  15613. (org-list-struct-apply-struct struct old-struct)
  15614. (org-update-checkbox-count-maybe))
  15615. (when block-item
  15616. (message "Checkboxes were removed due to empty box at line %d"
  15617. (org-current-line block-item)))))))
  15618. (`plain-list
  15619. ;; At a plain list, with a double C-u argument, set
  15620. ;; checkboxes of each item to "[-]", whereas a single one
  15621. ;; will toggle their presence according to the state of the
  15622. ;; first item in the list. Without an argument, repair the
  15623. ;; list.
  15624. (if (or radio-list-p
  15625. (and (boundp org-list-checkbox-radio-mode)
  15626. org-list-checkbox-radio-mode))
  15627. (org-toggle-radio-button arg)
  15628. (let* ((begin (org-element-property :contents-begin context))
  15629. (struct (org-element-property :structure context))
  15630. (old-struct (copy-tree struct))
  15631. (first-box (save-excursion
  15632. (goto-char begin)
  15633. (looking-at org-list-full-item-re)
  15634. (match-string-no-properties 3)))
  15635. (new-box (cond ((equal arg '(16)) "[-]")
  15636. ((equal arg '(4)) (unless first-box "[ ]"))
  15637. ((equal first-box "[X]") "[ ]")
  15638. (t "[X]"))))
  15639. (cond
  15640. (arg
  15641. (dolist (pos
  15642. (org-list-get-all-items
  15643. begin struct (org-list-prevs-alist struct)))
  15644. (org-list-set-checkbox pos struct new-box)))
  15645. ((and first-box (eq (point) begin))
  15646. ;; For convenience, when point is at bol on the first
  15647. ;; item of the list and no argument is provided, simply
  15648. ;; toggle checkbox of that item, if any.
  15649. (org-list-set-checkbox begin struct new-box)))
  15650. (when (equal
  15651. (org-list-write-struct
  15652. struct (org-list-parents-alist struct) old-struct)
  15653. old-struct)
  15654. (message "Cannot update this checkbox"))
  15655. (org-update-checkbox-count-maybe))))
  15656. (`keyword
  15657. (let ((org-inhibit-startup-visibility-stuff t)
  15658. (org-startup-align-all-tables nil))
  15659. (when (boundp 'org-table-coordinate-overlays)
  15660. (mapc #'delete-overlay org-table-coordinate-overlays)
  15661. (setq org-table-coordinate-overlays nil))
  15662. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  15663. (message "Local setup has been refreshed"))
  15664. ((or `property-drawer `node-property)
  15665. (call-interactively #'org-property-action))
  15666. (`radio-target
  15667. (call-interactively #'org-update-radio-target-regexp))
  15668. (`statistics-cookie
  15669. (call-interactively #'org-update-statistics-cookies))
  15670. ((or `table `table-cell `table-row)
  15671. ;; At a table, generate a plot if on the #+plot line,
  15672. ;; recalculate every field and align it otherwise. Also
  15673. ;; send the table if necessary.
  15674. (cond
  15675. ((and (org-match-line "[ \t]*#\\+plot:")
  15676. (< (point) (org-element-property :post-affiliated context)))
  15677. (org-plot/gnuplot))
  15678. ;; If the table has a `table.el' type, just give up.
  15679. ((eq (org-element-property :type context) 'table.el)
  15680. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  15681. Use `\\[org-edit-special]' to edit table.el tables")))
  15682. ;; At a table row or cell, maybe recalculate line but always
  15683. ;; align table.
  15684. ((or (eq type 'table)
  15685. ;; Check if point is at a TBLFM line.
  15686. (and (eq type 'table-row)
  15687. (= (point) (org-element-property :end context))))
  15688. (save-excursion
  15689. (if (org-at-TBLFM-p)
  15690. (progn (require 'org-table)
  15691. (org-table-calc-current-TBLFM))
  15692. (goto-char (org-element-property :contents-begin context))
  15693. (org-call-with-arg 'org-table-recalculate (or arg t))
  15694. (orgtbl-send-table 'maybe))))
  15695. (t
  15696. (org-table-maybe-eval-formula)
  15697. (cond (arg (call-interactively #'org-table-recalculate))
  15698. ((org-table-maybe-recalculate-line))
  15699. (t (org-table-align))))))
  15700. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  15701. (org-timestamp-change 0 'day))
  15702. ((and `nil (guard (org-at-heading-p)))
  15703. ;; When point is on an unsupported object type, we can miss
  15704. ;; the fact that it also is at a heading. Handle it here.
  15705. (call-interactively #'org-set-tags-command))
  15706. ((guard
  15707. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  15708. (_
  15709. (user-error
  15710. (substitute-command-keys
  15711. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  15712. (defun org-mode-restart ()
  15713. "Restart `org-mode'."
  15714. (interactive)
  15715. (let ((indent-status (bound-and-true-p org-indent-mode)))
  15716. (funcall major-mode)
  15717. (hack-local-variables)
  15718. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  15719. (org-indent-mode -1))
  15720. (org-reset-file-cache))
  15721. (message "%s restarted" major-mode))
  15722. (defun org-kill-note-or-show-branches ()
  15723. "Abort storing current note, or show just branches."
  15724. (interactive)
  15725. (cond (org-finish-function
  15726. (let ((org-note-abort t)) (funcall org-finish-function)))
  15727. ((org-before-first-heading-p)
  15728. (org-fold-show-branches-buffer)
  15729. (org-fold-hide-archived-subtrees (point-min) (point-max)))
  15730. (t
  15731. (let ((beg (progn (org-back-to-heading) (point)))
  15732. (end (save-excursion (org-end-of-subtree t t) (point))))
  15733. (org-fold-hide-subtree)
  15734. (org-fold-show-branches)
  15735. (org-fold-hide-archived-subtrees beg end)))))
  15736. (defun org-delete-indentation (&optional arg)
  15737. "Join current line to previous and fix whitespace at join.
  15738. If previous line is a headline add to headline title. Otherwise
  15739. the function calls `delete-indentation'.
  15740. I.e. with a non-nil optional argument, join the line with the
  15741. following one. If there is a region then join the lines in that
  15742. region."
  15743. (interactive "*P")
  15744. (if (save-excursion
  15745. (beginning-of-line (if arg 1 0))
  15746. (let ((case-fold-search nil))
  15747. (looking-at org-complex-heading-regexp)))
  15748. ;; At headline.
  15749. (let ((tags-column (when (match-beginning 5)
  15750. (save-excursion (goto-char (match-beginning 5))
  15751. (current-column))))
  15752. (string (concat " " (progn (when arg (forward-line 1))
  15753. (org-trim (delete-and-extract-region
  15754. (line-beginning-position)
  15755. (line-end-position)))))))
  15756. (unless (bobp) (delete-region (point) (1- (point))))
  15757. (goto-char (or (match-end 4)
  15758. (match-beginning 5)
  15759. (match-end 0)))
  15760. (skip-chars-backward " \t")
  15761. (save-excursion (insert string))
  15762. ;; Adjust alignment of tags.
  15763. (cond
  15764. ((not tags-column)) ;no tags
  15765. (org-auto-align-tags (org-align-tags))
  15766. (t (org--align-tags-here tags-column)))) ;preserve tags column
  15767. (let ((current-prefix-arg arg))
  15768. (call-interactively #'delete-indentation))))
  15769. (defun org-open-line (n)
  15770. "Insert a new row in tables, call `open-line' elsewhere.
  15771. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  15772. As a special case, when a document starts with a table, allow to
  15773. call `open-line' on the very first character."
  15774. (interactive "*p")
  15775. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  15776. (org-table-insert-row)
  15777. (open-line n)))
  15778. (defun org--newline (indent arg interactive)
  15779. "Call `newline-and-indent' or just `newline'.
  15780. If INDENT is non-nil, call `newline-and-indent' with ARG to
  15781. indent unconditionally; otherwise, call `newline' with ARG and
  15782. INTERACTIVE, which can trigger indentation if
  15783. `electric-indent-mode' is enabled."
  15784. (if indent
  15785. (org-newline-and-indent arg)
  15786. (newline arg interactive)))
  15787. (defun org-return (&optional indent arg interactive)
  15788. "Goto next table row or insert a newline.
  15789. Calls `org-table-next-row' or `newline', depending on context.
  15790. When optional INDENT argument is non-nil, call
  15791. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  15792. and INTERACTIVE.
  15793. When `org-return-follows-link' is non-nil and point is on
  15794. a timestamp or a link, call `org-open-at-point'. However, it
  15795. will not happen if point is in a table or on a \"dead\"
  15796. object (e.g., within a comment). In these case, you need to use
  15797. `org-open-at-point' directly."
  15798. (interactive "i\nP\np")
  15799. (let* ((context (if org-return-follows-link (org-element-context)
  15800. (org-element-at-point)))
  15801. (element-type (org-element-type context)))
  15802. (cond
  15803. ;; In a table, call `org-table-next-row'. However, before first
  15804. ;; column or after last one, split the table.
  15805. ((or (and (eq 'table element-type)
  15806. (not (eq 'table.el (org-element-property :type context)))
  15807. (>= (point) (org-element-property :contents-begin context))
  15808. (< (point) (org-element-property :contents-end context)))
  15809. (org-element-lineage context '(table-row table-cell) t))
  15810. (if (or (looking-at-p "[ \t]*$")
  15811. (save-excursion (skip-chars-backward " \t") (bolp)))
  15812. (insert "\n")
  15813. (org-table-justify-field-maybe)
  15814. (call-interactively #'org-table-next-row)))
  15815. ;; On a link or a timestamp, call `org-open-at-point' if
  15816. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  15817. ;; locations, e.g., in a comment, as `org-open-at-point'.
  15818. ((and org-return-follows-link
  15819. (or (and (eq 'link element-type)
  15820. ;; Ensure point is not on the white spaces after
  15821. ;; the link.
  15822. (let ((origin (point)))
  15823. (org-with-point-at (org-element-property :end context)
  15824. (skip-chars-backward " \t")
  15825. (> (point) origin))))
  15826. (org-in-regexp org-ts-regexp-both nil t)
  15827. (org-in-regexp org-tsr-regexp-both nil t)
  15828. (org-in-regexp org-link-any-re nil t)))
  15829. (call-interactively #'org-open-at-point))
  15830. ;; Insert newline in heading, but preserve tags.
  15831. ((and (not (bolp))
  15832. (let ((case-fold-search nil))
  15833. (org-match-line org-complex-heading-regexp)))
  15834. ;; At headline. Split line. However, if point is on keyword,
  15835. ;; priority cookie or tags, do not break any of them: add
  15836. ;; a newline after the headline instead.
  15837. (let ((tags-column (and (match-beginning 5)
  15838. (save-excursion (goto-char (match-beginning 5))
  15839. (current-column))))
  15840. (string
  15841. (when (and (match-end 4) (org-point-in-group (point) 4))
  15842. (delete-and-extract-region (point) (match-end 4)))))
  15843. ;; Adjust tag alignment.
  15844. (cond
  15845. ((not (and tags-column string)))
  15846. (org-auto-align-tags (org-align-tags))
  15847. (t (org--align-tags-here tags-column))) ;preserve tags column
  15848. (end-of-line)
  15849. (org-fold-show-entry)
  15850. (org--newline indent arg interactive)
  15851. (when string (save-excursion (insert (org-trim string))))))
  15852. ;; In a list, make sure indenting keeps trailing text within.
  15853. ((and (not (eolp))
  15854. (org-element-lineage context '(item)))
  15855. (let ((trailing-data
  15856. (delete-and-extract-region (point) (line-end-position))))
  15857. (org--newline indent arg interactive)
  15858. (save-excursion (insert trailing-data))))
  15859. (t
  15860. ;; Do not auto-fill when point is in an Org property drawer.
  15861. (let ((auto-fill-function (and (not (org-at-property-p))
  15862. auto-fill-function)))
  15863. (org--newline indent arg interactive))))))
  15864. (defun org-return-and-maybe-indent ()
  15865. "Goto next table row, or insert a newline, maybe indented.
  15866. Call `org-table-next-row' or `org-return', depending on context.
  15867. See the individual commands for more information.
  15868. When inserting a newline, if `org-adapt-indentation' is t:
  15869. indent the line if `electric-indent-mode' is disabled, don't
  15870. indent it if it is enabled."
  15871. (interactive)
  15872. (org-return (not electric-indent-mode)))
  15873. (defun org-ctrl-c-tab (&optional arg)
  15874. "Toggle columns width in a table, or show children.
  15875. Call `org-table-toggle-column-width' if point is in a table.
  15876. Otherwise provide a compact view of the children. ARG is the
  15877. level to hide."
  15878. (interactive "p")
  15879. (cond
  15880. ((org-at-table-p)
  15881. (call-interactively #'org-table-toggle-column-width))
  15882. ((org-before-first-heading-p)
  15883. (save-excursion
  15884. (org-fold-flag-above-first-heading)
  15885. (org-fold-hide-sublevels (or arg 1))))
  15886. (t
  15887. (org-fold-hide-subtree)
  15888. (org-fold-show-children arg))))
  15889. (defun org-ctrl-c-star ()
  15890. "Compute table, or change heading status of lines.
  15891. Calls `org-table-recalculate' or `org-toggle-heading',
  15892. depending on context."
  15893. (interactive)
  15894. (cond
  15895. ((org-at-table-p)
  15896. (call-interactively 'org-table-recalculate))
  15897. (t
  15898. ;; Convert all lines in region to list items
  15899. (call-interactively 'org-toggle-heading))))
  15900. (defun org-ctrl-c-minus ()
  15901. "Insert separator line in table or modify bullet status of line.
  15902. Also turns a plain line or a region of lines into list items.
  15903. Calls `org-table-insert-hline', `org-toggle-item', or
  15904. `org-cycle-list-bullet', depending on context."
  15905. (interactive)
  15906. (cond
  15907. ((org-at-table-p)
  15908. (call-interactively 'org-table-insert-hline))
  15909. ((org-region-active-p)
  15910. (call-interactively 'org-toggle-item))
  15911. ((org-in-item-p)
  15912. (call-interactively 'org-cycle-list-bullet))
  15913. (t
  15914. (call-interactively 'org-toggle-item))))
  15915. (defun org-toggle-heading (&optional nstars)
  15916. "Convert headings to normal text, or items or text to headings.
  15917. If there is no active region, only convert the current line.
  15918. With a `\\[universal-argument]' prefix, convert the whole list at
  15919. point into heading.
  15920. In a region:
  15921. - If the first non blank line is a headline, remove the stars
  15922. from all headlines in the region.
  15923. - If it is a normal line, turn each and every normal line (i.e.,
  15924. not an heading or an item) in the region into headings. If you
  15925. want to convert only the first line of this region, use one
  15926. universal prefix argument.
  15927. - If it is a plain list item, turn all plain list items into headings.
  15928. When converting a line into a heading, the number of stars is chosen
  15929. such that the lines become children of the current entry. However,
  15930. when a numeric prefix argument is given, its value determines the
  15931. number of stars to add."
  15932. (interactive "P")
  15933. (let ((skip-blanks
  15934. ;; Return beginning of first non-blank line, starting from
  15935. ;; line at POS.
  15936. (lambda (pos)
  15937. (save-excursion
  15938. (goto-char pos)
  15939. (while (org-at-comment-p) (forward-line))
  15940. (skip-chars-forward " \r\t\n")
  15941. (point-at-bol))))
  15942. beg end toggled)
  15943. ;; Determine boundaries of changes. If a universal prefix has
  15944. ;; been given, put the list in a region. If region ends at a bol,
  15945. ;; do not consider the last line to be in the region.
  15946. (when (and current-prefix-arg (org-at-item-p))
  15947. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  15948. (org-mark-element))
  15949. (if (org-region-active-p)
  15950. (setq beg (funcall skip-blanks (region-beginning))
  15951. end (copy-marker (save-excursion
  15952. (goto-char (region-end))
  15953. (if (bolp) (point) (point-at-eol)))))
  15954. (setq beg (funcall skip-blanks (point-at-bol))
  15955. end (copy-marker (point-at-eol))))
  15956. ;; Ensure inline tasks don't count as headings.
  15957. (org-with-limited-levels
  15958. (save-excursion
  15959. (goto-char beg)
  15960. (cond
  15961. ;; Case 1. Started at an heading: de-star headings.
  15962. ((org-at-heading-p)
  15963. (while (< (point) end)
  15964. (when (org-at-heading-p)
  15965. (looking-at org-outline-regexp) (replace-match "")
  15966. (setq toggled t))
  15967. (forward-line)))
  15968. ;; Case 2. Started at an item: change items into headlines.
  15969. ;; One star will be added by `org-list-to-subtree'.
  15970. ((org-at-item-p)
  15971. (while (< (point) end)
  15972. (when (org-at-item-p)
  15973. ;; Pay attention to cases when region ends before list.
  15974. (let* ((struct (org-list-struct))
  15975. (list-end
  15976. (min (org-list-get-bottom-point struct) (1+ end))))
  15977. (save-restriction
  15978. (narrow-to-region (point) list-end)
  15979. (insert (org-list-to-subtree
  15980. (org-list-to-lisp t)
  15981. (pcase (org-current-level)
  15982. (`nil 1)
  15983. (l (1+ (org-reduced-level l)))))
  15984. "\n")))
  15985. (setq toggled t))
  15986. (forward-line)))
  15987. ;; Case 3. Started at normal text: make every line an heading,
  15988. ;; skipping headlines and items.
  15989. (t (let* ((stars
  15990. (make-string
  15991. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  15992. (add-stars
  15993. (cond (nstars "") ; stars from prefix only
  15994. ((equal stars "") "*") ; before first heading
  15995. (org-odd-levels-only "**") ; inside heading, odd
  15996. (t "*"))) ; inside heading, oddeven
  15997. (rpl (concat stars add-stars " "))
  15998. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  15999. (while (< (point) (if (equal nstars '(4)) lend end))
  16000. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16001. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16002. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16003. (forward-line)))))))
  16004. (unless toggled (message "Cannot toggle heading from here"))))
  16005. (defun org-meta-return (&optional arg)
  16006. "Insert a new heading or wrap a region in a table.
  16007. Calls `org-insert-heading', `org-insert-item' or
  16008. `org-table-wrap-region', depending on context. When called with
  16009. an argument, unconditionally call `org-insert-heading'."
  16010. (interactive "P")
  16011. (org-fold-check-before-invisible-edit 'insert)
  16012. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16013. (call-interactively (cond (arg #'org-insert-heading)
  16014. ((org-at-table-p) #'org-table-wrap-region)
  16015. ((org-in-item-p) #'org-insert-item)
  16016. (t #'org-insert-heading)))))
  16017. ;;; Menu entries
  16018. (defsubst org-in-subtree-not-table-p ()
  16019. "Are we in a subtree and not in a table?"
  16020. (and (not (org-before-first-heading-p))
  16021. (not (org-at-table-p))))
  16022. ;; Define the Org mode menus
  16023. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16024. `("Org"
  16025. ("Show/Hide"
  16026. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16027. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16028. ["Sparse Tree..." org-sparse-tree t]
  16029. ["Reveal Context" org-fold-reveal t]
  16030. ["Show All" org-fold-show-all t]
  16031. "--"
  16032. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16033. "--"
  16034. ["New Heading" org-insert-heading t]
  16035. ("Navigate Headings"
  16036. ["Up" outline-up-heading t]
  16037. ["Next" outline-next-visible-heading t]
  16038. ["Previous" outline-previous-visible-heading t]
  16039. ["Next Same Level" outline-forward-same-level t]
  16040. ["Previous Same Level" outline-backward-same-level t]
  16041. "--"
  16042. ["Jump" org-goto t])
  16043. ("Edit Structure"
  16044. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16045. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16046. "--"
  16047. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16048. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16049. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16050. "--"
  16051. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16052. "--"
  16053. ["Copy visible text" org-copy-visible t]
  16054. "--"
  16055. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16056. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16057. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16058. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16059. "--"
  16060. ["Sort Region/Children" org-sort t]
  16061. "--"
  16062. ["Convert to odd levels" org-convert-to-odd-levels t]
  16063. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16064. ("Editing"
  16065. ["Emphasis..." org-emphasize t]
  16066. ["Add block structure" org-insert-structure-template t]
  16067. ["Edit Source Example" org-edit-special t]
  16068. "--"
  16069. ["Footnote new/jump" org-footnote-action t]
  16070. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16071. ("Archive"
  16072. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16073. "--"
  16074. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16075. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16076. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16077. "--"
  16078. ("Hyperlinks"
  16079. ["Store Link (Global)" org-store-link t]
  16080. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16081. ["Insert Link" org-insert-link t]
  16082. ["Follow Link" org-open-at-point t]
  16083. "--"
  16084. ["Next link" org-next-link t]
  16085. ["Previous link" org-previous-link t]
  16086. "--"
  16087. ["Descriptive Links"
  16088. org-toggle-link-display
  16089. :style radio
  16090. :selected org-descriptive-links
  16091. ]
  16092. ["Literal Links"
  16093. org-toggle-link-display
  16094. :style radio
  16095. :selected (not org-descriptive-links)])
  16096. "--"
  16097. ("TODO Lists"
  16098. ["TODO/DONE/-" org-todo t]
  16099. ("Select keyword"
  16100. ["Next keyword" org-shiftright (org-at-heading-p)]
  16101. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16102. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16103. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16104. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16105. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16106. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16107. "--"
  16108. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16109. :selected org-enforce-todo-dependencies :style toggle :active t]
  16110. "Settings for tree at point"
  16111. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16112. :selected (org-entry-get nil "ORDERED")
  16113. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16114. ["Do Children parallel" org-toggle-ordered-property :style radio
  16115. :selected (not (org-entry-get nil "ORDERED"))
  16116. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16117. "--"
  16118. ["Set Priority" org-priority t]
  16119. ["Priority Up" org-shiftup t]
  16120. ["Priority Down" org-shiftdown t]
  16121. "--"
  16122. ["Get news from all feeds" org-feed-update-all t]
  16123. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16124. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16125. ("TAGS and Properties"
  16126. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16127. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16128. "--"
  16129. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16130. ["Column view of properties" org-columns t]
  16131. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16132. ("Dates and Scheduling"
  16133. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16134. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16135. ("Change Date"
  16136. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16137. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16138. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16139. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16140. ["Compute Time Range" org-evaluate-time-range t]
  16141. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16142. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16143. "--"
  16144. ["Custom time format" org-toggle-time-stamp-overlays
  16145. :style radio :selected org-display-custom-times]
  16146. "--"
  16147. ["Goto Calendar" org-goto-calendar t]
  16148. ["Date from Calendar" org-date-from-calendar t]
  16149. "--"
  16150. ["Start/Restart Timer" org-timer-start t]
  16151. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16152. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16153. ["Insert Timer String" org-timer t]
  16154. ["Insert Timer Item" org-timer-item t])
  16155. ("Logging work"
  16156. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16157. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16158. ["Clock out" org-clock-out t]
  16159. ["Clock cancel" org-clock-cancel t]
  16160. "--"
  16161. ["Mark as default task" org-clock-mark-default-task t]
  16162. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16163. ["Goto running clock" org-clock-goto t]
  16164. "--"
  16165. ["Display times" org-clock-display t]
  16166. ["Create clock table" org-clock-report t]
  16167. "--"
  16168. ["Record DONE time"
  16169. (progn (setq org-log-done (not org-log-done))
  16170. (message "Switching to %s will %s record a timestamp"
  16171. (car org-done-keywords)
  16172. (if org-log-done "automatically" "not")))
  16173. :style toggle :selected org-log-done])
  16174. "--"
  16175. ["Agenda Command..." org-agenda t]
  16176. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16177. ("File List for Agenda")
  16178. ("Special views current file"
  16179. ["TODO Tree" org-show-todo-tree t]
  16180. ["Check Deadlines" org-check-deadlines t]
  16181. ["Tags/Property tree" org-match-sparse-tree t])
  16182. "--"
  16183. ["Export/Publish..." org-export-dispatch t]
  16184. ("LaTeX"
  16185. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16186. :style toggle :selected org-cdlatex-mode]
  16187. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16188. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16189. ["Modify math symbol" org-cdlatex-math-modify
  16190. (org-inside-LaTeX-fragment-p)]
  16191. ["Insert citation" org-reftex-citation t])
  16192. "--"
  16193. ("Documentation"
  16194. ["Show Version" org-version t]
  16195. ["Info Documentation" org-info t]
  16196. ["Browse Org News" org-browse-news t])
  16197. ("Customize"
  16198. ["Browse Org Group" org-customize t]
  16199. "--"
  16200. ["Expand This Menu" org-create-customize-menu t])
  16201. ["Send bug report" org-submit-bug-report t]
  16202. "--"
  16203. ("Refresh/Reload"
  16204. ["Refresh setup current buffer" org-mode-restart t]
  16205. ["Reload Org (after update)" org-reload t]
  16206. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16207. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16208. '("Table"
  16209. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16210. ["Next Field" org-cycle (org-at-table-p)]
  16211. ["Previous Field" org-shifttab (org-at-table-p)]
  16212. ["Next Row" org-return (org-at-table-p)]
  16213. "--"
  16214. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16215. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16216. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16217. "--"
  16218. ("Column"
  16219. ["Move Column Left" org-metaleft (org-at-table-p)]
  16220. ["Move Column Right" org-metaright (org-at-table-p)]
  16221. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16222. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16223. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16224. ("Row"
  16225. ["Move Row Up" org-metaup (org-at-table-p)]
  16226. ["Move Row Down" org-metadown (org-at-table-p)]
  16227. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16228. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16229. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16230. "--"
  16231. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16232. ("Rectangle"
  16233. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16234. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16235. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16236. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16237. "--"
  16238. ("Calculate"
  16239. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16240. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16241. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16242. "--"
  16243. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16244. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16245. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16246. "--"
  16247. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16248. "--"
  16249. ["Sum Column/Rectangle" org-table-sum
  16250. (or (org-at-table-p) (org-region-active-p))]
  16251. ["Which Column?" org-table-current-column (org-at-table-p)])
  16252. ["Debug Formulas"
  16253. org-table-toggle-formula-debugger
  16254. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16255. ["Show Col/Row Numbers"
  16256. org-table-toggle-coordinate-overlays
  16257. :style toggle
  16258. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16259. "--"
  16260. ["Create" org-table-create (not (org-at-table-p))]
  16261. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16262. ["Import from File" org-table-import (not (org-at-table-p))]
  16263. ["Export to File" org-table-export (org-at-table-p)]
  16264. "--"
  16265. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16266. "--"
  16267. ("Plot"
  16268. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16269. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16270. (defun org-info (&optional node)
  16271. "Read documentation for Org in the info system.
  16272. With optional NODE, go directly to that node."
  16273. (interactive)
  16274. (info (format "(org)%s" (or node ""))))
  16275. (defun org-browse-news ()
  16276. "Browse the news for the latest major release."
  16277. (interactive)
  16278. (browse-url "https://orgmode.org/Changes.html"))
  16279. ;;;###autoload
  16280. (defun org-submit-bug-report ()
  16281. "Submit a bug report on Org via mail.
  16282. Don't hesitate to report any problems or inaccurate documentation.
  16283. If you don't have setup sending mail from (X)Emacs, please copy the
  16284. output buffer into your mail program, as it gives us important
  16285. information about your Org version and configuration."
  16286. (interactive)
  16287. (require 'reporter)
  16288. (defvar reporter-prompt-for-summary-p)
  16289. (org-load-modules-maybe)
  16290. (org-require-autoloaded-modules)
  16291. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16292. (reporter-submit-bug-report
  16293. "emacs-orgmode@gnu.org"
  16294. (org-version nil 'full)
  16295. (let (list)
  16296. (save-window-excursion
  16297. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16298. (delete-other-windows)
  16299. (erase-buffer)
  16300. (insert "You are about to submit a bug report to the Org mailing list.
  16301. If your report is about Org installation, please read this section:
  16302. https://orgmode.org/org.html#Installation
  16303. Please read https://orgmode.org/org.html#Feedback on how to make
  16304. a good report, it will help Org contributors fixing your problem.
  16305. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16306. if the issue you are about to raise has already been dealt with.
  16307. We also would like to add your full Org and Outline configuration
  16308. to the bug report. It will help us debugging the issue.
  16309. *HOWEVER*, some variables you have customized may contain private
  16310. information. The names of customers, colleagues, or friends, might
  16311. appear in the form of file names, tags, todo states or search strings.
  16312. If you answer \"yes\" to the prompt, you might want to check and remove
  16313. such private information before sending the email.")
  16314. (add-text-properties (point-min) (point-max) '(face org-warning))
  16315. (when (yes-or-no-p "Include your Org configuration ")
  16316. (mapatoms
  16317. (lambda (v)
  16318. (and (boundp v)
  16319. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16320. (or (and (symbol-value v)
  16321. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16322. (and
  16323. (get v 'custom-type) (get v 'standard-value)
  16324. (not (equal (symbol-value v)
  16325. (eval (car (get v 'standard-value)) t)))))
  16326. (push v list)))))
  16327. (kill-buffer (get-buffer "*Warn about privacy*"))
  16328. list))
  16329. nil nil
  16330. "Remember to cover the basics, that is, what you expected to happen and
  16331. what in fact did happen. You don't know how to make a good report? See
  16332. https://orgmode.org/manual/Feedback.html#Feedback
  16333. Your bug report will be posted to the Org mailing list.
  16334. ------------------------------------------------------------------------")
  16335. (save-excursion
  16336. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16337. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16338. (defun org-install-agenda-files-menu ()
  16339. "Install agenda file menu."
  16340. (let ((bl (buffer-list)))
  16341. (save-excursion
  16342. (while bl
  16343. (set-buffer (pop bl))
  16344. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16345. (when (derived-mode-p 'org-mode)
  16346. (easy-menu-change
  16347. '("Org") "File List for Agenda"
  16348. (append
  16349. (list
  16350. ["Edit File List" (org-edit-agenda-file-list) t]
  16351. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16352. ["Remove Current File from List" org-remove-file t]
  16353. ["Cycle through agenda files" org-cycle-agenda-files t]
  16354. ["Occur in all agenda files" org-occur-in-agenda-files t]
  16355. "--")
  16356. (mapcar 'org-file-menu-entry
  16357. ;; Prevent initialization from failing.
  16358. (ignore-errors (org-agenda-files t)))))))))
  16359. ;;;; Documentation
  16360. (defun org-require-autoloaded-modules ()
  16361. (interactive)
  16362. (mapc #'require
  16363. '(org-agenda org-archive org-attach org-clock org-colview org-id
  16364. org-table org-timer)))
  16365. ;;;###autoload
  16366. (defun org-reload (&optional uncompiled)
  16367. "Reload all Org Lisp files.
  16368. With prefix arg UNCOMPILED, load the uncompiled versions."
  16369. (interactive "P")
  16370. (require 'loadhist)
  16371. (let* ((org-dir (org-find-library-dir "org"))
  16372. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  16373. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  16374. (remove-re (format "\\`%s\\'"
  16375. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  16376. (feats (delete-dups
  16377. (mapcar 'file-name-sans-extension
  16378. (mapcar 'file-name-nondirectory
  16379. (delq nil
  16380. (mapcar 'feature-file
  16381. features))))))
  16382. (lfeat (append
  16383. (sort
  16384. (setq feats
  16385. (delq nil (mapcar
  16386. (lambda (f)
  16387. (if (and (string-match feature-re f)
  16388. (not (string-match remove-re f)))
  16389. f nil))
  16390. feats)))
  16391. 'string-lessp)
  16392. (list "org-version" "org")))
  16393. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  16394. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  16395. load-uncore load-misses)
  16396. (setq load-misses
  16397. (delq 't
  16398. (mapcar (lambda (f)
  16399. (or (org-load-noerror-mustsuffix (concat org-dir f))
  16400. (and (string= org-dir contrib-dir)
  16401. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  16402. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  16403. (push f load-uncore)
  16404. 't)
  16405. f))
  16406. lfeat)))
  16407. (when load-uncore
  16408. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  16409. (if (> (length load-uncore) 1) "s were" " was")
  16410. (reverse load-uncore)))
  16411. (if load-misses
  16412. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  16413. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  16414. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  16415. ;;;###autoload
  16416. (defun org-customize ()
  16417. "Call the customize function with org as argument."
  16418. (interactive)
  16419. (org-load-modules-maybe)
  16420. (org-require-autoloaded-modules)
  16421. (customize-browse 'org))
  16422. (defun org-create-customize-menu ()
  16423. "Create a full customization menu for Org mode, insert it into the menu."
  16424. (interactive)
  16425. (org-load-modules-maybe)
  16426. (org-require-autoloaded-modules)
  16427. (easy-menu-change
  16428. '("Org") "Customize"
  16429. `(["Browse Org group" org-customize t]
  16430. "--"
  16431. ,(customize-menu-create 'org)
  16432. ["Set" Custom-set t]
  16433. ["Save" Custom-save t]
  16434. ["Reset to Current" Custom-reset-current t]
  16435. ["Reset to Saved" Custom-reset-saved t]
  16436. ["Reset to Standard Settings" Custom-reset-standard t]))
  16437. (message "\"Org\"-menu now contains full customization menu"))
  16438. ;;;; Miscellaneous stuff
  16439. ;;; Generally useful functions
  16440. (defun org-in-clocktable-p ()
  16441. "Check if the cursor is in a clocktable."
  16442. (let ((pos (point)) start)
  16443. (save-excursion
  16444. (end-of-line 1)
  16445. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  16446. (setq start (match-beginning 0))
  16447. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  16448. (>= (match-end 0) pos)
  16449. start))))
  16450. (defun org-in-verbatim-emphasis ()
  16451. (save-match-data
  16452. (and (org-in-regexp org-verbatim-re 2)
  16453. (>= (point) (match-beginning 3))
  16454. (<= (point) (match-end 4)))))
  16455. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  16456. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  16457. (if (and marker (marker-buffer marker)
  16458. (buffer-live-p (marker-buffer marker)))
  16459. (progn
  16460. (pop-to-buffer-same-window (marker-buffer marker))
  16461. (when (or (> marker (point-max)) (< marker (point-min)))
  16462. (widen))
  16463. (goto-char marker)
  16464. (org-fold-show-context 'org-goto))
  16465. (if bookmark
  16466. (bookmark-jump bookmark)
  16467. (error "Cannot find location"))))
  16468. (defun org-quote-csv-field (s)
  16469. "Quote field for inclusion in CSV material."
  16470. (if (string-match "[\",]" s)
  16471. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  16472. s))
  16473. (defun org-force-self-insert (N)
  16474. "Needed to enforce self-insert under remapping."
  16475. (interactive "p")
  16476. (self-insert-command N))
  16477. (defun org-quote-vert (s)
  16478. "Replace \"|\" with \"\\vert\"."
  16479. (while (string-match "|" s)
  16480. (setq s (replace-match "\\vert" t t s)))
  16481. s)
  16482. (defun org-uuidgen-p (s)
  16483. "Is S an ID created by UUIDGEN?"
  16484. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  16485. (defun org-in-src-block-p (&optional inside element)
  16486. "Whether point is in a code source block.
  16487. When INSIDE is non-nil, don't consider we are within a source
  16488. block when point is at #+BEGIN_SRC or #+END_SRC.
  16489. When ELEMENT is provided, it is considered to be element at point."
  16490. (save-match-data (setq element (or element (org-element-at-point))))
  16491. (when (eq 'src-block (org-element-type element))
  16492. (or (not inside)
  16493. (not (or (= (line-beginning-position)
  16494. (org-element-property :post-affiliated element))
  16495. (= (1+ (line-end-position))
  16496. (- (org-element-property :end element)
  16497. (org-element-property :post-blank element))))))))
  16498. (defun org-context ()
  16499. "Return a list of contexts of the current cursor position.
  16500. If several contexts apply, all are returned.
  16501. Each context entry is a list with a symbol naming the context, and
  16502. two positions indicating start and end of the context. Possible
  16503. contexts are:
  16504. :headline anywhere in a headline
  16505. :headline-stars on the leading stars in a headline
  16506. :todo-keyword on a TODO keyword (including DONE) in a headline
  16507. :tags on the TAGS in a headline
  16508. :priority on the priority cookie in a headline
  16509. :item on the first line of a plain list item
  16510. :item-bullet on the bullet/number of a plain list item
  16511. :checkbox on the checkbox in a plain list item
  16512. :table in an Org table
  16513. :table-special on a special filed in a table
  16514. :table-table in a table.el table
  16515. :clocktable in a clocktable
  16516. :src-block in a source block
  16517. :link on a hyperlink
  16518. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  16519. :latex-fragment on a LaTeX fragment
  16520. :latex-preview on a LaTeX fragment with overlaid preview image
  16521. This function expects the position to be visible because it uses font-lock
  16522. faces as a help to recognize the following contexts: :table-special, :link,
  16523. and :keyword."
  16524. (let* ((f (get-text-property (point) 'face))
  16525. (faces (if (listp f) f (list f)))
  16526. (case-fold-search t)
  16527. (p (point)) clist o)
  16528. ;; First the large context
  16529. (cond
  16530. ((org-at-heading-p)
  16531. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  16532. (when (progn
  16533. (beginning-of-line 1)
  16534. (looking-at org-todo-line-tags-regexp))
  16535. (push (org-point-in-group p 1 :headline-stars) clist)
  16536. (push (org-point-in-group p 2 :todo-keyword) clist)
  16537. (push (org-point-in-group p 4 :tags) clist))
  16538. (goto-char p)
  16539. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  16540. (when (looking-at "\\[#[A-Z0-9]\\]")
  16541. (push (org-point-in-group p 0 :priority) clist)))
  16542. ((org-at-item-p)
  16543. (push (org-point-in-group p 2 :item-bullet) clist)
  16544. (push (list :item (point-at-bol)
  16545. (save-excursion (org-end-of-item) (point)))
  16546. clist)
  16547. (and (org-at-item-checkbox-p)
  16548. (push (org-point-in-group p 0 :checkbox) clist)))
  16549. ((org-at-table-p)
  16550. (push (list :table (org-table-begin) (org-table-end)) clist)
  16551. (when (memq 'org-formula faces)
  16552. (push (list :table-special
  16553. (previous-single-property-change p 'face)
  16554. (next-single-property-change p 'face))
  16555. clist)))
  16556. ((org-at-table-p 'any)
  16557. (push (list :table-table) clist)))
  16558. (goto-char p)
  16559. (let ((case-fold-search t))
  16560. ;; New the "medium" contexts: clocktables, source blocks
  16561. (cond ((org-in-clocktable-p)
  16562. (push (list :clocktable
  16563. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  16564. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  16565. (match-beginning 1))
  16566. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  16567. (match-end 0)))
  16568. clist))
  16569. ((org-in-src-block-p)
  16570. (push (list :src-block
  16571. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  16572. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  16573. (match-beginning 1))
  16574. (and (search-forward "#+END_SRC" nil t)
  16575. (match-beginning 0)))
  16576. clist))))
  16577. (goto-char p)
  16578. ;; Now the small context
  16579. (cond
  16580. ((org-at-timestamp-p)
  16581. (push (org-point-in-group p 0 :timestamp) clist))
  16582. ((memq 'org-link faces)
  16583. (push (list :link
  16584. (previous-single-property-change p 'face)
  16585. (next-single-property-change p 'face))
  16586. clist))
  16587. ((memq 'org-special-keyword faces)
  16588. (push (list :keyword
  16589. (previous-single-property-change p 'face)
  16590. (next-single-property-change p 'face))
  16591. clist))
  16592. ((setq o (cl-some
  16593. (lambda (o)
  16594. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  16595. o))
  16596. (overlays-at (point))))
  16597. (push (list :latex-fragment
  16598. (overlay-start o) (overlay-end o))
  16599. clist)
  16600. (push (list :latex-preview
  16601. (overlay-start o) (overlay-end o))
  16602. clist))
  16603. ((org-inside-LaTeX-fragment-p)
  16604. ;; FIXME: positions wrong.
  16605. (push (list :latex-fragment (point) (point)) clist)))
  16606. (setq clist (nreverse (delq nil clist)))
  16607. clist))
  16608. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  16609. "Non-nil when point is between matches of START-RE and END-RE.
  16610. Also return a non-nil value when point is on one of the matches.
  16611. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  16612. buffer positions. Default values are the positions of headlines
  16613. surrounding the point.
  16614. The functions returns a cons cell whose car (resp. cdr) is the
  16615. position before START-RE (resp. after END-RE)."
  16616. (save-match-data
  16617. (let ((pos (point))
  16618. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  16619. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  16620. beg end)
  16621. (save-excursion
  16622. ;; Point is on a block when on START-RE or if START-RE can be
  16623. ;; found before it...
  16624. (and (or (org-in-regexp start-re)
  16625. (re-search-backward start-re limit-up t))
  16626. (setq beg (match-beginning 0))
  16627. ;; ... and END-RE after it...
  16628. (goto-char (match-end 0))
  16629. (re-search-forward end-re limit-down t)
  16630. (> (setq end (match-end 0)) pos)
  16631. ;; ... without another START-RE in-between.
  16632. (goto-char (match-beginning 0))
  16633. (not (re-search-backward start-re (1+ beg) t))
  16634. ;; Return value.
  16635. (cons beg end))))))
  16636. (defun org-in-block-p (names)
  16637. "Non-nil when point belongs to a block whose name belongs to NAMES.
  16638. NAMES is a list of strings containing names of blocks.
  16639. Return first block name matched, or nil. Beware that in case of
  16640. nested blocks, the returned name may not belong to the closest
  16641. block from point."
  16642. (save-match-data
  16643. (catch 'exit
  16644. (let ((case-fold-search t)
  16645. (lim-up (save-excursion (outline-previous-heading)))
  16646. (lim-down (save-excursion (outline-next-heading))))
  16647. (dolist (name names)
  16648. (let ((n (regexp-quote name)))
  16649. (when (org-between-regexps-p
  16650. (concat "^[ \t]*#\\+begin_" n)
  16651. (concat "^[ \t]*#\\+end_" n)
  16652. lim-up lim-down)
  16653. (throw 'exit n)))))
  16654. nil)))
  16655. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  16656. "Call `multi-occur' with buffers for all agenda files."
  16657. (interactive "sOrg-files matching: ")
  16658. (let* ((files (org-agenda-files))
  16659. (tnames (mapcar #'file-truename files))
  16660. (extra org-agenda-text-search-extra-files))
  16661. (when (eq (car extra) 'agenda-archives)
  16662. (setq extra (cdr extra))
  16663. (setq files (org-add-archive-files files)))
  16664. (dolist (f extra)
  16665. (unless (member (file-truename f) tnames)
  16666. (unless (member f files) (setq files (append files (list f))))
  16667. (setq tnames (append tnames (list (file-truename f))))))
  16668. (multi-occur
  16669. (mapcar (lambda (x)
  16670. (with-current-buffer
  16671. ;; FIXME: Why not just (find-file-noselect x)?
  16672. ;; Is it to avoid the "revert buffer" prompt?
  16673. (or (get-file-buffer x) (find-file-noselect x))
  16674. (widen)
  16675. (current-buffer)))
  16676. files)
  16677. regexp)))
  16678. (add-hook 'occur-mode-find-occurrence-hook
  16679. (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  16680. (defun org-occur-link-in-agenda-files ()
  16681. "Create a link and search for it in the agendas.
  16682. The link is not stored in `org-stored-links', it is just created
  16683. for the search purpose."
  16684. (interactive)
  16685. (let ((link (condition-case nil
  16686. (org-store-link nil)
  16687. (error "Unable to create a link to here"))))
  16688. (org-occur-in-agenda-files (regexp-quote link))))
  16689. (defun org-back-over-empty-lines ()
  16690. "Move backwards over whitespace, to the beginning of the first empty line.
  16691. Returns the number of empty lines passed."
  16692. (let ((pos (point)))
  16693. (if (cdr (assq 'heading org-blank-before-new-entry))
  16694. (skip-chars-backward " \t\n\r")
  16695. (unless (eobp)
  16696. (forward-line -1)))
  16697. (beginning-of-line 2)
  16698. (goto-char (min (point) pos))
  16699. (count-lines (point) pos)))
  16700. ;;; TODO: Only called once, from ox-odt which should probably use
  16701. ;;; org-export-inline-image-p or something.
  16702. (defun org-file-image-p (file)
  16703. "Return non-nil if FILE is an image."
  16704. (save-match-data
  16705. (string-match (image-file-name-regexp) file)))
  16706. (defun org-get-cursor-date (&optional with-time)
  16707. "Return the date at cursor in as a time.
  16708. This works in the calendar and in the agenda, anywhere else it just
  16709. returns the current time.
  16710. If WITH-TIME is non-nil, returns the time of the event at point (in
  16711. the agenda) or the current time of the day; otherwise returns the
  16712. earliest time on the cursor date that Org treats as that date
  16713. (bearing in mind `org-extend-today-until')."
  16714. (let (date day defd tp hod mod)
  16715. (when with-time
  16716. (setq tp (get-text-property (point) 'time))
  16717. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  16718. (setq hod (string-to-number (match-string 1 tp))
  16719. mod (string-to-number (match-string 2 tp))))
  16720. (or tp (let ((now (decode-time)))
  16721. (setq hod (nth 2 now)
  16722. mod (nth 1 now)))))
  16723. (cond
  16724. ((eq major-mode 'calendar-mode)
  16725. (setq date (calendar-cursor-to-date)
  16726. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16727. (nth 1 date) (nth 0 date) (nth 2 date))))
  16728. ((eq major-mode 'org-agenda-mode)
  16729. (setq day (get-text-property (point) 'day))
  16730. (when day
  16731. (setq date (calendar-gregorian-from-absolute day)
  16732. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  16733. (nth 1 date) (nth 0 date) (nth 2 date))))))
  16734. (or defd (current-time))))
  16735. (defun org-mark-subtree (&optional up)
  16736. "Mark the current subtree.
  16737. This puts point at the start of the current subtree, and mark at
  16738. the end. If a numeric prefix UP is given, move up into the
  16739. hierarchy of headlines by UP levels before marking the subtree."
  16740. (interactive "P")
  16741. (org-with-limited-levels
  16742. (cond ((org-at-heading-p) (beginning-of-line))
  16743. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  16744. (t (outline-previous-visible-heading 1))))
  16745. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  16746. (if (called-interactively-p 'any)
  16747. (call-interactively 'org-mark-element)
  16748. (org-mark-element)))
  16749. ;;; Indentation
  16750. (defvar org-element-greater-elements)
  16751. (defun org--get-expected-indentation (element contentsp)
  16752. "Expected indentation column for current line, according to ELEMENT.
  16753. ELEMENT is an element containing point. CONTENTSP is non-nil
  16754. when indentation is to be computed according to contents of
  16755. ELEMENT."
  16756. (let ((type (org-element-type element))
  16757. (start (org-element-property :begin element))
  16758. (post-affiliated (org-element-property :post-affiliated element)))
  16759. (org-with-wide-buffer
  16760. (cond
  16761. (contentsp
  16762. (cl-case type
  16763. ((diary-sexp footnote-definition) 0)
  16764. (section
  16765. (org--get-expected-indentation
  16766. (org-element-property :parent element)
  16767. t))
  16768. ((headline inlinetask nil)
  16769. (if (not org-adapt-indentation) 0
  16770. (let ((level (org-current-level)))
  16771. (if level (1+ level) 0))))
  16772. ((item plain-list) (org-list-item-body-column post-affiliated))
  16773. (t
  16774. (goto-char start)
  16775. (current-indentation))))
  16776. ((memq type '(headline inlinetask nil))
  16777. (if (org-match-line "[ \t]*$")
  16778. (org--get-expected-indentation element t)
  16779. 0))
  16780. ((memq type '(diary-sexp footnote-definition)) 0)
  16781. ;; First paragraph of a footnote definition or an item.
  16782. ;; Indent like parent.
  16783. ((< (line-beginning-position) start)
  16784. (org--get-expected-indentation
  16785. (org-element-property :parent element) t))
  16786. ;; At first line: indent according to previous sibling, if any,
  16787. ;; ignoring footnote definitions and inline tasks, or parent's
  16788. ;; contents.
  16789. ((and ( = (line-beginning-position) start)
  16790. (eq org-adapt-indentation t))
  16791. (catch 'exit
  16792. (while t
  16793. (if (= (point-min) start) (throw 'exit 0)
  16794. (goto-char (1- start))
  16795. (let* ((previous (org-element-at-point))
  16796. (parent previous))
  16797. (while (and parent (<= (org-element-property :end parent) start))
  16798. (setq previous parent
  16799. parent (org-element-property :parent parent)))
  16800. (cond
  16801. ((not previous) (throw 'exit 0))
  16802. ((> (org-element-property :end previous) start)
  16803. (throw 'exit (org--get-expected-indentation previous t)))
  16804. ((memq (org-element-type previous)
  16805. '(footnote-definition inlinetask))
  16806. (setq start (org-element-property :begin previous)))
  16807. (t (goto-char (org-element-property :begin previous))
  16808. (throw 'exit
  16809. (if (bolp) (current-indentation)
  16810. ;; At first paragraph in an item or
  16811. ;; a footnote definition.
  16812. (org--get-expected-indentation
  16813. (org-element-property :parent previous) t))))))))))
  16814. ;; Otherwise, move to the first non-blank line above.
  16815. (t
  16816. (beginning-of-line)
  16817. (let ((pos (point)))
  16818. (skip-chars-backward " \r\t\n")
  16819. (cond
  16820. ;; Two blank lines end a footnote definition or a plain
  16821. ;; list. When we indent an empty line after them, the
  16822. ;; containing list or footnote definition is over, so it
  16823. ;; qualifies as a previous sibling. Therefore, we indent
  16824. ;; like its first line.
  16825. ((and (memq type '(footnote-definition plain-list))
  16826. (> (count-lines (point) pos) 2))
  16827. (goto-char start)
  16828. (current-indentation))
  16829. ;; Line above is the first one of a paragraph at the
  16830. ;; beginning of an item or a footnote definition. Indent
  16831. ;; like parent.
  16832. ((< (line-beginning-position) start)
  16833. (org--get-expected-indentation
  16834. (org-element-property :parent element) t))
  16835. ;; Line above is the beginning of an element, i.e., point
  16836. ;; was originally on the blank lines between element's start
  16837. ;; and contents.
  16838. ((= (line-beginning-position) post-affiliated)
  16839. (org--get-expected-indentation element t))
  16840. ;; POS is after contents in a greater element. Indent like
  16841. ;; the beginning of the element.
  16842. ((and (memq type org-element-greater-elements)
  16843. (let ((cend (org-element-property :contents-end element)))
  16844. (and cend (<= cend pos))))
  16845. ;; As a special case, if point is at the end of a footnote
  16846. ;; definition or an item, indent like the very last element
  16847. ;; within. If that last element is an item, indent like
  16848. ;; its contents.
  16849. (if (memq type '(footnote-definition item plain-list))
  16850. (let ((last (org-element-at-point)))
  16851. (goto-char pos)
  16852. (org--get-expected-indentation
  16853. last (eq (org-element-type last) 'item)))
  16854. (goto-char start)
  16855. (current-indentation)))
  16856. ;; In any other case, indent like the current line.
  16857. (t (current-indentation)))))
  16858. ;; Finally, no indentation is needed, fall back to 0.
  16859. (t (current-indentation))))))
  16860. (defun org--align-node-property ()
  16861. "Align node property at point.
  16862. Alignment is done according to `org-property-format', which see."
  16863. (when (save-excursion
  16864. (beginning-of-line)
  16865. (looking-at org-property-re))
  16866. (combine-change-calls (match-beginning 0) (match-end 0)
  16867. (let ((newtext (concat (match-string 4)
  16868. (org-trim
  16869. (format org-property-format (match-string 1) (match-string 3))))))
  16870. ;; Do not use `replace-match' here as we want to inherit folding
  16871. ;; properties if inside fold.
  16872. (setf (buffer-substring (match-beginning 0) (match-end 0)) "")
  16873. (insert-and-inherit newtext)))))
  16874. (defun org-indent-line ()
  16875. "Indent line depending on context.
  16876. Indentation is done according to the following rules:
  16877. - Footnote definitions, diary sexps, headlines and inline tasks
  16878. have to start at column 0.
  16879. - On the very first line of an element, consider, in order, the
  16880. next rules until one matches:
  16881. 1. If there's a sibling element before, ignoring footnote
  16882. definitions and inline tasks, indent like its first line.
  16883. 2. If element has a parent, indent like its contents. More
  16884. precisely, if parent is an item, indent after the bullet.
  16885. Else, indent like parent's first line.
  16886. 3. Otherwise, indent relatively to current level, if
  16887. `org-adapt-indentation' is t, or to left margin.
  16888. - On a blank line at the end of an element, indent according to
  16889. the type of the element. More precisely
  16890. 1. If element is a plain list, an item, or a footnote
  16891. definition, indent like the very last element within.
  16892. 2. If element is a paragraph, indent like its last non blank
  16893. line.
  16894. 3. Otherwise, indent like its very first line.
  16895. - In the code part of a source block, use language major mode
  16896. to indent current line if `org-src-tab-acts-natively' is
  16897. non-nil. If it is nil, do nothing.
  16898. - Otherwise, indent like the first non-blank line above.
  16899. The function doesn't indent an item as it could break the whole
  16900. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  16901. `\\[org-shiftmetaright]'.
  16902. Also align node properties according to `org-property-format'."
  16903. (interactive)
  16904. (unless (or (org-at-heading-p)
  16905. (and (eq org-adapt-indentation 'headline-data)
  16906. (not (or (org-at-clock-log-p)
  16907. (org-at-planning-p)))
  16908. (save-excursion
  16909. (beginning-of-line 1)
  16910. (skip-chars-backward "\n")
  16911. (or (org-at-heading-p)
  16912. (looking-back ":END:.*" (point-at-bol))))))
  16913. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  16914. (type (org-element-type element)))
  16915. (cond ((and (memq type '(plain-list item))
  16916. (= (line-beginning-position)
  16917. (org-element-property :post-affiliated element)))
  16918. nil)
  16919. ((and (eq type 'latex-environment)
  16920. (>= (point) (org-element-property :post-affiliated element))
  16921. (< (point)
  16922. (org-with-point-at (org-element-property :end element)
  16923. (skip-chars-backward " \t\n")
  16924. (line-beginning-position 2))))
  16925. nil)
  16926. ((and (eq type 'src-block)
  16927. org-src-tab-acts-natively
  16928. (> (line-beginning-position)
  16929. (org-element-property :post-affiliated element))
  16930. (< (line-beginning-position)
  16931. (org-with-point-at (org-element-property :end element)
  16932. (skip-chars-backward " \t\n")
  16933. (line-beginning-position))))
  16934. ;; At the beginning of a blank line, do some preindentation. This
  16935. ;; signals org-src--edit-element to preserve the indentation on exit
  16936. (when (and (looking-at-p "^[[:space:]]*$")
  16937. (not org-src-preserve-indentation))
  16938. (let ((element (org-element-at-point))
  16939. block-content-ind some-ind)
  16940. (org-with-point-at (org-element-property :begin element)
  16941. (setq block-content-ind (+ (current-indentation)
  16942. org-edit-src-content-indentation))
  16943. (forward-line)
  16944. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  16945. (backward-char)
  16946. (setq some-ind (if (looking-at-p "#\\+end_src")
  16947. block-content-ind (current-indentation))))
  16948. (indent-line-to (min block-content-ind some-ind))))
  16949. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  16950. (t
  16951. (let ((column (org--get-expected-indentation element nil)))
  16952. ;; Preserve current column.
  16953. (if (<= (current-column) (current-indentation))
  16954. (indent-line-to column)
  16955. (save-excursion (indent-line-to column))))
  16956. ;; Align node property. Also preserve current column.
  16957. (when (eq type 'node-property)
  16958. (let ((column (current-column)))
  16959. (org--align-node-property)
  16960. (org-move-to-column column))))))))
  16961. (defun org-indent-region (start end)
  16962. "Indent each non-blank line in the region.
  16963. Called from a program, START and END specify the region to
  16964. indent. The function will not indent contents of example blocks,
  16965. verse blocks and export blocks as leading white spaces are
  16966. assumed to be significant there."
  16967. (interactive "r")
  16968. (save-excursion
  16969. (goto-char start)
  16970. (skip-chars-forward " \r\t\n")
  16971. (unless (eobp) (beginning-of-line))
  16972. (let ((indent-to
  16973. (lambda (ind pos)
  16974. ;; Set IND as indentation for all lines between point and
  16975. ;; POS. Blank lines are ignored. Leave point after POS
  16976. ;; once done.
  16977. (let ((limit (copy-marker pos)))
  16978. (while (< (point) limit)
  16979. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  16980. (forward-line))
  16981. (set-marker limit nil))))
  16982. (end (copy-marker end)))
  16983. (while (< (point) end)
  16984. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  16985. (let* ((element (org-element-at-point-no-context))
  16986. (type (org-element-type element))
  16987. (element-end (copy-marker (org-element-property :end element)))
  16988. (ind (org--get-expected-indentation element nil)))
  16989. (cond
  16990. ;; Element indented as a single block. Example blocks
  16991. ;; preserving indentation are a special case since the
  16992. ;; "contents" must not be indented whereas the block
  16993. ;; boundaries can.
  16994. ((or (memq type '(export-block latex-environment))
  16995. (and (eq type 'example-block)
  16996. (not
  16997. (or org-src-preserve-indentation
  16998. (org-element-property :preserve-indent element)))))
  16999. (let ((offset (- ind (current-indentation))))
  17000. (unless (zerop offset)
  17001. (indent-rigidly (org-element-property :begin element)
  17002. (org-element-property :end element)
  17003. offset)))
  17004. (goto-char element-end))
  17005. ;; Elements indented line wise. Be sure to exclude
  17006. ;; example blocks (preserving indentation) and source
  17007. ;; blocks from this category as they are treated
  17008. ;; specially later.
  17009. ((or (memq type '(paragraph table table-row))
  17010. (not (or (org-element-property :contents-begin element)
  17011. (memq type '(example-block src-block)))))
  17012. (when (eq type 'node-property)
  17013. (org--align-node-property)
  17014. (beginning-of-line))
  17015. (funcall indent-to ind (min element-end end)))
  17016. ;; Elements consisting of three parts: before the
  17017. ;; contents, the contents, and after the contents. The
  17018. ;; contents are treated specially, according to the
  17019. ;; element type, or not indented at all. Other parts are
  17020. ;; indented as a single block.
  17021. (t
  17022. (let* ((post (copy-marker
  17023. (org-element-property :post-affiliated element)))
  17024. (cbeg
  17025. (copy-marker
  17026. (cond
  17027. ((not (org-element-property :contents-begin element))
  17028. ;; Fake contents for source blocks.
  17029. (org-with-wide-buffer
  17030. (goto-char post)
  17031. (line-beginning-position 2)))
  17032. ((memq type '(footnote-definition item plain-list))
  17033. ;; Contents in these elements could start on
  17034. ;; the same line as the beginning of the
  17035. ;; element. Make sure we start indenting
  17036. ;; from the second line.
  17037. (org-with-wide-buffer
  17038. (goto-char post)
  17039. (end-of-line)
  17040. (skip-chars-forward " \r\t\n")
  17041. (if (eobp) (point) (line-beginning-position))))
  17042. (t (org-element-property :contents-begin element)))))
  17043. (cend (copy-marker
  17044. (or (org-element-property :contents-end element)
  17045. ;; Fake contents for source blocks.
  17046. (org-with-wide-buffer
  17047. (goto-char element-end)
  17048. (skip-chars-backward " \r\t\n")
  17049. (line-beginning-position)))
  17050. t)))
  17051. ;; Do not change items indentation individually as it
  17052. ;; might break the list as a whole. On the other
  17053. ;; hand, when at a plain list, indent it as a whole.
  17054. (cond ((eq type 'plain-list)
  17055. (let ((offset (- ind (current-indentation))))
  17056. (unless (zerop offset)
  17057. (indent-rigidly (org-element-property :begin element)
  17058. (org-element-property :end element)
  17059. offset))
  17060. (goto-char cbeg)))
  17061. ((eq type 'item) (goto-char cbeg))
  17062. (t (funcall indent-to ind (min cbeg end))))
  17063. (when (< (point) end)
  17064. (cl-case type
  17065. ((example-block verse-block))
  17066. (src-block
  17067. ;; In a source block, indent source code
  17068. ;; according to language major mode, but only if
  17069. ;; `org-src-tab-acts-natively' is non-nil.
  17070. (when (and (< (point) end) org-src-tab-acts-natively)
  17071. (ignore-errors
  17072. (org-babel-do-in-edit-buffer
  17073. (indent-region (point-min) (point-max))))))
  17074. (t (org-indent-region (point) (min cend end))))
  17075. (goto-char (min cend end))
  17076. (when (< (point) end)
  17077. (funcall indent-to ind (min element-end end))))
  17078. (set-marker post nil)
  17079. (set-marker cbeg nil)
  17080. (set-marker cend nil))))
  17081. (set-marker element-end nil))))
  17082. (set-marker end nil))))
  17083. (defun org-indent-drawer ()
  17084. "Indent the drawer at point."
  17085. (interactive)
  17086. (unless (save-excursion
  17087. (beginning-of-line)
  17088. (looking-at-p org-drawer-regexp))
  17089. (user-error "Not at a drawer"))
  17090. (let ((element (org-element-at-point-no-context)))
  17091. (unless (memq (org-element-type element) '(drawer property-drawer))
  17092. (user-error "Not at a drawer"))
  17093. (org-with-wide-buffer
  17094. (org-indent-region (org-element-property :begin element)
  17095. (org-element-property :end element))))
  17096. (message "Drawer at point indented"))
  17097. (defun org-indent-block ()
  17098. "Indent the block at point."
  17099. (interactive)
  17100. (unless (save-excursion
  17101. (beginning-of-line)
  17102. (let ((case-fold-search t))
  17103. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17104. (user-error "Not at a block"))
  17105. (let ((element (org-element-at-point-no-context)))
  17106. (unless (memq (org-element-type element)
  17107. '(comment-block center-block dynamic-block example-block
  17108. export-block quote-block special-block
  17109. src-block verse-block))
  17110. (user-error "Not at a block"))
  17111. (org-with-wide-buffer
  17112. (org-indent-region (org-element-property :begin element)
  17113. (org-element-property :end element))))
  17114. (message "Block at point indented"))
  17115. ;;; Filling
  17116. ;; We use our own fill-paragraph and auto-fill functions.
  17117. ;; `org-fill-paragraph' relies on adaptive filling and context
  17118. ;; checking. Appropriate `fill-prefix' is computed with
  17119. ;; `org-adaptive-fill-function'.
  17120. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17121. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17122. ;; `org-adaptive-fill-function' value. Internally,
  17123. ;; `org-comment-line-break-function' breaks the line.
  17124. ;; `org-setup-filling' installs filling and auto-filling related
  17125. ;; variables during `org-mode' initialization.
  17126. (defun org-setup-filling ()
  17127. (require 'org-element)
  17128. ;; Prevent auto-fill from inserting unwanted new items.
  17129. (when (boundp 'fill-nobreak-predicate)
  17130. (setq-local
  17131. fill-nobreak-predicate
  17132. (org-uniquify
  17133. (append fill-nobreak-predicate
  17134. '(org-fill-line-break-nobreak-p
  17135. org-fill-n-macro-as-item-nobreak-p
  17136. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17137. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17138. (setq-local paragraph-start paragraph-ending)
  17139. (setq-local paragraph-separate paragraph-ending))
  17140. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17141. (setq-local auto-fill-inhibit-regexp nil)
  17142. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17143. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17144. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17145. (defun org-fill-line-break-nobreak-p ()
  17146. "Non-nil when a new line at point would create an Org line break."
  17147. (save-excursion
  17148. (skip-chars-backward " \t")
  17149. (skip-chars-backward "\\\\")
  17150. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17151. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17152. "Non-nil when a new line at point would split a timestamp."
  17153. (and (org-at-timestamp-p 'lax)
  17154. (not (looking-at org-ts-regexp-both))))
  17155. (defun org-fill-n-macro-as-item-nobreak-p ()
  17156. "Non-nil when a new line at point would create a new list."
  17157. ;; During export, a "n" macro followed by a dot or a closing
  17158. ;; parenthesis can end up being parsed as a new list item.
  17159. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17160. (defun org-adaptive-fill-function ()
  17161. "Compute a fill prefix for the current line.
  17162. Return fill prefix, as a string, or nil if current line isn't
  17163. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17164. matches in paragraphs or comments, use it."
  17165. (org-with-wide-buffer
  17166. (unless (org-at-heading-p)
  17167. (let* ((p (line-beginning-position))
  17168. (element (save-excursion
  17169. (beginning-of-line)
  17170. (org-element-at-point)))
  17171. (type (org-element-type element))
  17172. (post-affiliated (org-element-property :post-affiliated element)))
  17173. (unless (< p post-affiliated)
  17174. (cl-case type
  17175. (comment
  17176. (save-excursion
  17177. (beginning-of-line)
  17178. (looking-at "[ \t]*")
  17179. (concat (match-string 0) "# ")))
  17180. (footnote-definition "")
  17181. ((item plain-list)
  17182. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17183. (paragraph
  17184. ;; Fill prefix is usually the same as the current line,
  17185. ;; unless the paragraph is at the beginning of an item.
  17186. (let ((parent (org-element-property :parent element)))
  17187. (save-excursion
  17188. (beginning-of-line)
  17189. (cond ((eq (org-element-type parent) 'item)
  17190. (make-string (org-list-item-body-column
  17191. (org-element-property :begin parent))
  17192. ?\s))
  17193. ((and adaptive-fill-regexp
  17194. ;; Locally disable
  17195. ;; `adaptive-fill-function' to let
  17196. ;; `fill-context-prefix' handle
  17197. ;; `adaptive-fill-regexp' variable.
  17198. (let (adaptive-fill-function)
  17199. (fill-context-prefix
  17200. post-affiliated
  17201. (org-element-property :end element)))))
  17202. ((looking-at "[ \t]+") (match-string 0))
  17203. (t "")))))
  17204. (comment-block
  17205. ;; Only fill contents if P is within block boundaries.
  17206. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17207. (forward-line)
  17208. (point)))
  17209. (cend (save-excursion
  17210. (goto-char (org-element-property :end element))
  17211. (skip-chars-backward " \r\t\n")
  17212. (line-beginning-position))))
  17213. (when (and (>= p cbeg) (< p cend))
  17214. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17215. (match-string 0)
  17216. ""))))))))))
  17217. (defun org-fill-element (&optional justify)
  17218. "Fill element at point, when applicable.
  17219. This function only applies to comment blocks, comments, example
  17220. blocks and paragraphs. Also, as a special case, re-align table
  17221. when point is at one.
  17222. If JUSTIFY is non-nil (interactively, with prefix argument),
  17223. justify as well. If `sentence-end-double-space' is non-nil, then
  17224. period followed by one space does not end a sentence, so don't
  17225. break a line there. The variable `fill-column' controls the
  17226. width for filling.
  17227. For convenience, when point is at a plain list, an item or
  17228. a footnote definition, try to fill the first paragraph within."
  17229. (with-syntax-table org-mode-transpose-word-syntax-table
  17230. ;; Move to end of line in order to get the first paragraph within
  17231. ;; a plain list or a footnote definition.
  17232. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17233. ;; First check if point is in a blank line at the beginning of
  17234. ;; the buffer. In that case, ignore filling.
  17235. (cl-case (org-element-type element)
  17236. ;; Use major mode filling function is source blocks.
  17237. (src-block (org-babel-do-in-edit-buffer
  17238. (push-mark (point-min))
  17239. (goto-char (point-max))
  17240. (setq mark-active t)
  17241. (funcall-interactively #'fill-paragraph justify 'region)))
  17242. ;; Align Org tables, leave table.el tables as-is.
  17243. (table-row (org-table-align) t)
  17244. (table
  17245. (when (eq (org-element-property :type element) 'org)
  17246. (save-excursion
  17247. (goto-char (org-element-property :post-affiliated element))
  17248. (org-table-align)))
  17249. t)
  17250. (paragraph
  17251. ;; Paragraphs may contain `line-break' type objects.
  17252. (let ((beg (max (point-min)
  17253. (org-element-property :contents-begin element)))
  17254. (end (min (point-max)
  17255. (org-element-property :contents-end element))))
  17256. ;; Do nothing if point is at an affiliated keyword.
  17257. (if (< (line-end-position) beg) t
  17258. ;; Fill paragraph, taking line breaks into account.
  17259. (save-excursion
  17260. (goto-char beg)
  17261. (let ((cuts (list beg)))
  17262. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17263. (when (eq 'line-break
  17264. (org-element-type
  17265. (save-excursion (backward-char)
  17266. (org-element-context))))
  17267. (push (point) cuts)))
  17268. (dolist (c (delq end cuts))
  17269. (fill-region-as-paragraph c end justify)
  17270. (setq end c))))
  17271. t)))
  17272. ;; Contents of `comment-block' type elements should be
  17273. ;; filled as plain text, but only if point is within block
  17274. ;; markers.
  17275. (comment-block
  17276. (let* ((case-fold-search t)
  17277. (beg (save-excursion
  17278. (goto-char (org-element-property :begin element))
  17279. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17280. (forward-line)
  17281. (point)))
  17282. (end (save-excursion
  17283. (goto-char (org-element-property :end element))
  17284. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17285. (line-beginning-position))))
  17286. (if (or (< (point) beg) (> (point) end)) t
  17287. (fill-region-as-paragraph
  17288. (save-excursion (end-of-line)
  17289. (re-search-backward "^[ \t]*$" beg 'move)
  17290. (line-beginning-position))
  17291. (save-excursion (beginning-of-line)
  17292. (re-search-forward "^[ \t]*$" end 'move)
  17293. (line-beginning-position))
  17294. justify))))
  17295. ;; Fill comments.
  17296. (comment
  17297. (let ((begin (org-element-property :post-affiliated element))
  17298. (end (org-element-property :end element)))
  17299. (when (and (>= (point) begin) (<= (point) end))
  17300. (let ((begin (save-excursion
  17301. (end-of-line)
  17302. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17303. (progn (forward-line) (point))
  17304. begin)))
  17305. (end (save-excursion
  17306. (end-of-line)
  17307. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17308. (1- (line-beginning-position))
  17309. (skip-chars-backward " \r\t\n")
  17310. (line-end-position)))))
  17311. ;; Do not fill comments when at a blank line.
  17312. (when (> end begin)
  17313. (let ((fill-prefix
  17314. (save-excursion
  17315. (beginning-of-line)
  17316. (looking-at "[ \t]*#")
  17317. (let ((comment-prefix (match-string 0)))
  17318. (goto-char (match-end 0))
  17319. (if (looking-at adaptive-fill-regexp)
  17320. (concat comment-prefix (match-string 0))
  17321. (concat comment-prefix " "))))))
  17322. (save-excursion
  17323. (fill-region-as-paragraph begin end justify))))))
  17324. t))
  17325. ;; Ignore every other element.
  17326. (otherwise t)))))
  17327. (defun org-fill-paragraph (&optional justify region)
  17328. "Fill element at point, when applicable.
  17329. This function only applies to comment blocks, comments, example
  17330. blocks and paragraphs. Also, as a special case, re-align table
  17331. when point is at one.
  17332. For convenience, when point is at a plain list, an item or
  17333. a footnote definition, try to fill the first paragraph within.
  17334. If JUSTIFY is non-nil (interactively, with prefix argument),
  17335. justify as well. If `sentence-end-double-space' is non-nil, then
  17336. period followed by one space does not end a sentence, so don't
  17337. break a line there. The variable `fill-column' controls the
  17338. width for filling.
  17339. The REGION argument is non-nil if called interactively; in that
  17340. case, if Transient Mark mode is enabled and the mark is active,
  17341. fill each of the elements in the active region, instead of just
  17342. filling the current element."
  17343. (interactive (progn
  17344. (barf-if-buffer-read-only)
  17345. (list (when current-prefix-arg 'full) t)))
  17346. (let ((hash (and (not (buffer-modified-p))
  17347. (org-buffer-hash))))
  17348. (cond
  17349. ((and region transient-mark-mode mark-active
  17350. (not (eq (region-beginning) (region-end))))
  17351. (let ((origin (point-marker))
  17352. (start (region-beginning)))
  17353. (unwind-protect
  17354. (progn
  17355. (goto-char (region-end))
  17356. (skip-chars-backward " \t\n")
  17357. (while (> (point) start)
  17358. (org-fill-element justify)
  17359. (org-backward-paragraph)))
  17360. (goto-char origin)
  17361. (set-marker origin nil))))
  17362. (t
  17363. (save-excursion
  17364. (when (org-match-line "[ \t]*$")
  17365. (skip-chars-forward " \t\n"))
  17366. (org-fill-element justify))))
  17367. ;; If we didn't change anything in the buffer (and the buffer was
  17368. ;; previously unmodified), then flip the modification status back
  17369. ;; to "unchanged".
  17370. (when (and hash (equal hash (org-buffer-hash)))
  17371. (set-buffer-modified-p nil))
  17372. ;; Return non-nil.
  17373. t))
  17374. (defun org-auto-fill-function ()
  17375. "Auto-fill function."
  17376. ;; Check if auto-filling is meaningful.
  17377. (let ((fc (current-fill-column)))
  17378. (when (and fc (> (current-column) fc))
  17379. (let* ((fill-prefix (org-adaptive-fill-function))
  17380. ;; Enforce empty fill prefix, if required. Otherwise, it
  17381. ;; will be computed again.
  17382. (adaptive-fill-mode (not (equal fill-prefix ""))))
  17383. (when fill-prefix (do-auto-fill))))))
  17384. (defun org-comment-line-break-function (&optional soft)
  17385. "Break line at point and indent, continuing comment if within one.
  17386. The inserted newline is marked hard if variable
  17387. `use-hard-newlines' is true, unless optional argument SOFT is
  17388. non-nil."
  17389. (if soft (insert-and-inherit ?\n) (newline 1))
  17390. (save-excursion (forward-char -1) (delete-horizontal-space))
  17391. (delete-horizontal-space)
  17392. (indent-to-left-margin)
  17393. (insert-before-markers-and-inherit fill-prefix))
  17394. ;;; Fixed Width Areas
  17395. (defun org-toggle-fixed-width ()
  17396. "Toggle fixed-width markup.
  17397. Add or remove fixed-width markup on current line, whenever it
  17398. makes sense. Return an error otherwise.
  17399. If a region is active and if it contains only fixed-width areas
  17400. or blank lines, remove all fixed-width markup in it. If the
  17401. region contains anything else, convert all non-fixed-width lines
  17402. to fixed-width ones.
  17403. Blank lines at the end of the region are ignored unless the
  17404. region only contains such lines."
  17405. (interactive)
  17406. (if (not (org-region-active-p))
  17407. ;; No region:
  17408. ;;
  17409. ;; Remove fixed width marker only in a fixed-with element.
  17410. ;;
  17411. ;; Add fixed width maker in paragraphs, in blank lines after
  17412. ;; elements or at the beginning of a headline or an inlinetask,
  17413. ;; and before any one-line elements (e.g., a clock).
  17414. (progn
  17415. (beginning-of-line)
  17416. (let* ((element (org-element-at-point))
  17417. (type (org-element-type element)))
  17418. (cond
  17419. ((and (eq type 'fixed-width)
  17420. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  17421. (replace-match
  17422. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  17423. ((and (memq type '(babel-call clock comment diary-sexp headline
  17424. horizontal-rule keyword paragraph
  17425. planning))
  17426. (<= (org-element-property :post-affiliated element) (point)))
  17427. (skip-chars-forward " \t")
  17428. (insert ": "))
  17429. ((and (looking-at-p "[ \t]*$")
  17430. (or (eq type 'inlinetask)
  17431. (save-excursion
  17432. (skip-chars-forward " \r\t\n")
  17433. (<= (org-element-property :end element) (point)))))
  17434. (delete-region (point) (line-end-position))
  17435. (org-indent-line)
  17436. (insert ": "))
  17437. (t (user-error "Cannot insert a fixed-width line here")))))
  17438. ;; Region active.
  17439. (let* ((begin (save-excursion
  17440. (goto-char (region-beginning))
  17441. (line-beginning-position)))
  17442. (end (copy-marker
  17443. (save-excursion
  17444. (goto-char (region-end))
  17445. (unless (eolp) (beginning-of-line))
  17446. (if (save-excursion (re-search-backward "\\S-" begin t))
  17447. (progn (skip-chars-backward " \r\t\n") (point))
  17448. (point)))))
  17449. (all-fixed-width-p
  17450. (catch 'not-all-p
  17451. (save-excursion
  17452. (goto-char begin)
  17453. (skip-chars-forward " \r\t\n")
  17454. (when (eobp) (throw 'not-all-p nil))
  17455. (while (< (point) end)
  17456. (let ((element (org-element-at-point)))
  17457. (if (eq (org-element-type element) 'fixed-width)
  17458. (goto-char (org-element-property :end element))
  17459. (throw 'not-all-p nil))))
  17460. t))))
  17461. (if all-fixed-width-p
  17462. (save-excursion
  17463. (goto-char begin)
  17464. (while (< (point) end)
  17465. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  17466. (replace-match
  17467. "" nil nil nil
  17468. (if (= (line-end-position) (match-end 0)) 0 1)))
  17469. (forward-line)))
  17470. (let ((min-ind (point-max)))
  17471. ;; Find minimum indentation across all lines.
  17472. (save-excursion
  17473. (goto-char begin)
  17474. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  17475. (setq min-ind 0)
  17476. (catch 'zerop
  17477. (while (< (point) end)
  17478. (unless (looking-at-p "[ \t]*$")
  17479. (let ((ind (current-indentation)))
  17480. (setq min-ind (min min-ind ind))
  17481. (when (zerop ind) (throw 'zerop t))))
  17482. (forward-line)))))
  17483. ;; Loop over all lines and add fixed-width markup everywhere
  17484. ;; but in fixed-width lines.
  17485. (save-excursion
  17486. (goto-char begin)
  17487. (while (< (point) end)
  17488. (cond
  17489. ((org-at-heading-p)
  17490. (insert ": ")
  17491. (forward-line)
  17492. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  17493. (insert ":")
  17494. (forward-line)))
  17495. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  17496. (let* ((element (org-element-at-point))
  17497. (element-end (org-element-property :end element)))
  17498. (if (eq (org-element-type element) 'fixed-width)
  17499. (progn (goto-char element-end)
  17500. (skip-chars-backward " \r\t\n")
  17501. (forward-line))
  17502. (let ((limit (min end element-end)))
  17503. (while (< (point) limit)
  17504. (org-move-to-column min-ind t)
  17505. (insert ": ")
  17506. (forward-line))))))
  17507. (t
  17508. (org-move-to-column min-ind t)
  17509. (insert ": ")
  17510. (forward-line)))))))
  17511. (set-marker end nil))))
  17512. ;;; Blocks
  17513. (defun org-block-map (function &optional start end)
  17514. "Call FUNCTION at the head of all source blocks in the current buffer.
  17515. Optional arguments START and END can be used to limit the range."
  17516. (let ((start (or start (point-min)))
  17517. (end (or end (point-max))))
  17518. (save-excursion
  17519. (goto-char start)
  17520. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  17521. (save-excursion
  17522. (save-match-data
  17523. (goto-char (match-beginning 0))
  17524. (funcall function)))))))
  17525. (defun org-next-block (arg &optional backward block-regexp)
  17526. "Jump to the next block.
  17527. With a prefix argument ARG, jump forward ARG many blocks.
  17528. When BACKWARD is non-nil, jump to the previous block.
  17529. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  17530. Match data is set according to this regexp when the function
  17531. returns.
  17532. Return point at beginning of the opening line of found block.
  17533. Throw an error if no block is found."
  17534. (interactive "p")
  17535. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  17536. (case-fold-search t)
  17537. (search-fn (if backward #'re-search-backward #'re-search-forward))
  17538. (count (or arg 1))
  17539. (origin (point))
  17540. last-element)
  17541. (if backward (beginning-of-line) (end-of-line))
  17542. (while (and (> count 0) (funcall search-fn re nil t))
  17543. (let ((element (save-excursion
  17544. (goto-char (match-beginning 0))
  17545. (save-match-data (org-element-at-point)))))
  17546. (when (and (memq (org-element-type element)
  17547. '(center-block comment-block dynamic-block
  17548. example-block export-block quote-block
  17549. special-block src-block verse-block))
  17550. (<= (match-beginning 0)
  17551. (org-element-property :post-affiliated element)))
  17552. (setq last-element element)
  17553. (cl-decf count))))
  17554. (if (= count 0)
  17555. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  17556. (save-match-data (org-fold-show-context)))
  17557. (goto-char origin)
  17558. (user-error "No %s code blocks" (if backward "previous" "further")))))
  17559. (defun org-previous-block (arg &optional block-regexp)
  17560. "Jump to the previous block.
  17561. With a prefix argument ARG, jump backward ARG many source blocks.
  17562. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  17563. (interactive "p")
  17564. (org-next-block arg t block-regexp))
  17565. ;;; Comments
  17566. ;; Org comments syntax is quite complex. It requires the entire line
  17567. ;; to be just a comment. Also, even with the right syntax at the
  17568. ;; beginning of line, some elements (e.g., verse-block or
  17569. ;; example-block) don't accept comments. Usual Emacs comment commands
  17570. ;; cannot cope with those requirements. Therefore, Org replaces them.
  17571. ;; Org still relies on 'comment-dwim', but cannot trust
  17572. ;; 'comment-only-p'. So, 'comment-region-function' and
  17573. ;; 'uncomment-region-function' both point
  17574. ;; to 'org-comment-or-uncomment-region'. Eventually,
  17575. ;; 'org-insert-comment' takes care of insertion of comments at the
  17576. ;; beginning of line.
  17577. ;; 'org-setup-comments-handling' install comments related variables
  17578. ;; during 'org-mode' initialization.
  17579. (defun org-setup-comments-handling ()
  17580. (interactive)
  17581. (setq-local comment-use-syntax nil)
  17582. (setq-local comment-start "# ")
  17583. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  17584. (setq-local comment-insert-comment-function 'org-insert-comment)
  17585. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  17586. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  17587. (defun org-insert-comment ()
  17588. "Insert an empty comment above current line.
  17589. If the line is empty, insert comment at its beginning. When
  17590. point is within a source block, comment according to the related
  17591. major mode."
  17592. (if (let ((element (org-element-at-point)))
  17593. (and (eq (org-element-type element) 'src-block)
  17594. (< (save-excursion
  17595. (goto-char (org-element-property :post-affiliated element))
  17596. (line-end-position))
  17597. (point))
  17598. (> (save-excursion
  17599. (goto-char (org-element-property :end element))
  17600. (skip-chars-backward " \r\t\n")
  17601. (line-beginning-position))
  17602. (point))))
  17603. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  17604. (beginning-of-line)
  17605. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  17606. (open-line 1))
  17607. (org-indent-line)
  17608. (insert "# ")))
  17609. (defvar comment-empty-lines) ; From newcomment.el.
  17610. (defun org-comment-or-uncomment-region (beg end &rest _)
  17611. "Comment or uncomment each non-blank line in the region.
  17612. Uncomment each non-blank line between BEG and END if it only
  17613. contains commented lines. Otherwise, comment them. If region is
  17614. strictly within a source block, use appropriate comment syntax."
  17615. (if (let ((element (org-element-at-point)))
  17616. (and (eq (org-element-type element) 'src-block)
  17617. (< (save-excursion
  17618. (goto-char (org-element-property :post-affiliated element))
  17619. (line-end-position))
  17620. beg)
  17621. (>= (save-excursion
  17622. (goto-char (org-element-property :end element))
  17623. (skip-chars-backward " \r\t\n")
  17624. (line-beginning-position))
  17625. end)))
  17626. ;; Translate region boundaries for the Org buffer to the source
  17627. ;; buffer.
  17628. (let ((offset (- end beg)))
  17629. (save-excursion
  17630. (goto-char beg)
  17631. (org-babel-do-in-edit-buffer
  17632. (comment-or-uncomment-region (point) (+ offset (point))))))
  17633. (save-restriction
  17634. ;; Restrict region
  17635. (narrow-to-region (save-excursion (goto-char beg)
  17636. (skip-chars-forward " \r\t\n" end)
  17637. (line-beginning-position))
  17638. (save-excursion (goto-char end)
  17639. (skip-chars-backward " \r\t\n" beg)
  17640. (line-end-position)))
  17641. (let ((uncommentp
  17642. ;; UNCOMMENTP is non-nil when every non blank line between
  17643. ;; BEG and END is a comment.
  17644. (save-excursion
  17645. (goto-char (point-min))
  17646. (while (and (not (eobp))
  17647. (let ((element (org-element-at-point)))
  17648. (and (eq (org-element-type element) 'comment)
  17649. (goto-char (min (point-max)
  17650. (org-element-property
  17651. :end element)))))))
  17652. (eobp))))
  17653. (if uncommentp
  17654. ;; Only blank lines and comments in region: uncomment it.
  17655. (save-excursion
  17656. (goto-char (point-min))
  17657. (while (not (eobp))
  17658. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  17659. (replace-match "" nil nil nil 1))
  17660. (forward-line)))
  17661. ;; Comment each line in region.
  17662. (let ((min-indent (point-max)))
  17663. ;; First find the minimum indentation across all lines.
  17664. (save-excursion
  17665. (goto-char (point-min))
  17666. (while (and (not (eobp)) (not (zerop min-indent)))
  17667. (unless (looking-at "[ \t]*$")
  17668. (setq min-indent (min min-indent (current-indentation))))
  17669. (forward-line)))
  17670. ;; Then loop over all lines.
  17671. (save-excursion
  17672. (goto-char (point-min))
  17673. (while (not (eobp))
  17674. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  17675. ;; Don't get fooled by invisible text (e.g. link path)
  17676. ;; when moving to column MIN-INDENT.
  17677. (let ((buffer-invisibility-spec nil))
  17678. (org-move-to-column min-indent t))
  17679. (insert comment-start))
  17680. (forward-line)))))))))
  17681. (defun org-comment-dwim (_arg)
  17682. "Call the comment command you mean.
  17683. Call `org-toggle-comment' if on a heading, otherwise call
  17684. `comment-dwim', within a source edit buffer if needed."
  17685. (interactive "*P")
  17686. (cond ((org-at-heading-p)
  17687. (call-interactively #'org-toggle-comment))
  17688. ((org-in-src-block-p)
  17689. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  17690. (t (call-interactively #'comment-dwim))))
  17691. ;;; Timestamps API
  17692. ;; This section contains tools to operate on, or create, timestamp
  17693. ;; objects, as returned by, e.g. `org-element-context'.
  17694. (defun org-timestamp-from-string (s)
  17695. "Convert Org timestamp S, as a string, into a timestamp object.
  17696. Return nil if S is not a valid timestamp string."
  17697. (when (org-string-nw-p s)
  17698. (with-temp-buffer
  17699. (save-excursion (insert s))
  17700. (org-element-timestamp-parser))))
  17701. (defun org-timestamp-from-time (time &optional with-time inactive)
  17702. "Convert a time value into a timestamp object.
  17703. TIME is an Emacs internal time representation, as returned, e.g.,
  17704. by `current-time'.
  17705. When optional argument WITH-TIME is non-nil, return a timestamp
  17706. object with a time part, i.e., with hours and minutes.
  17707. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  17708. return an active timestamp."
  17709. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  17710. (org-element-create 'timestamp
  17711. (list :type (if inactive 'inactive 'active)
  17712. :year-start year
  17713. :month-start month
  17714. :day-start day
  17715. :hour-start (and with-time hour)
  17716. :minute-start (and with-time minute)))))
  17717. (defun org-timestamp-to-time (timestamp &optional end)
  17718. "Convert TIMESTAMP object into an Emacs internal time value.
  17719. Use end of date range or time range when END is non-nil.
  17720. Otherwise, use its start."
  17721. (apply #'encode-time 0
  17722. (mapcar
  17723. (lambda (prop) (or (org-element-property prop timestamp) 0))
  17724. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  17725. '(:minute-start :hour-start :day-start :month-start
  17726. :year-start)))))
  17727. (defun org-timestamp-has-time-p (timestamp)
  17728. "Non-nil when TIMESTAMP has a time specified."
  17729. (org-element-property :hour-start timestamp))
  17730. (defun org-timestamp-format (timestamp format &optional end utc)
  17731. "Format a TIMESTAMP object into a string.
  17732. FORMAT is a format specifier to be passed to
  17733. `format-time-string'.
  17734. When optional argument END is non-nil, use end of date-range or
  17735. time-range, if possible.
  17736. When optional argument UTC is non-nil, time is be expressed as
  17737. Universal Time."
  17738. (format-time-string format (org-timestamp-to-time timestamp end)
  17739. (and utc t)))
  17740. (defun org-timestamp-split-range (timestamp &optional end)
  17741. "Extract a TIMESTAMP object from a date or time range.
  17742. END, when non-nil, means extract the end of the range.
  17743. Otherwise, extract its start.
  17744. Return a new timestamp object."
  17745. (let ((type (org-element-property :type timestamp)))
  17746. (if (memq type '(active inactive diary)) timestamp
  17747. (let ((split-ts (org-element-copy timestamp)))
  17748. ;; Set new type.
  17749. (org-element-put-property
  17750. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  17751. ;; Copy start properties over end properties if END is
  17752. ;; non-nil. Otherwise, copy end properties over `start' ones.
  17753. (let ((p-alist '((:minute-start . :minute-end)
  17754. (:hour-start . :hour-end)
  17755. (:day-start . :day-end)
  17756. (:month-start . :month-end)
  17757. (:year-start . :year-end))))
  17758. (dolist (p-cell p-alist)
  17759. (org-element-put-property
  17760. split-ts
  17761. (funcall (if end #'car #'cdr) p-cell)
  17762. (org-element-property
  17763. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  17764. ;; Eventually refresh `:raw-value'.
  17765. (org-element-put-property split-ts :raw-value nil)
  17766. (org-element-put-property
  17767. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  17768. (defun org-timestamp-translate (timestamp &optional boundary)
  17769. "Translate TIMESTAMP object to custom format.
  17770. Format string is defined in `org-time-stamp-custom-formats',
  17771. which see.
  17772. When optional argument BOUNDARY is non-nil, it is either the
  17773. symbol `start' or `end'. In this case, only translate the
  17774. starting or ending part of TIMESTAMP if it is a date or time
  17775. range. Otherwise, translate both parts.
  17776. Return timestamp as-is if `org-display-custom-times' is nil or if
  17777. it has a `diary' type."
  17778. (let ((type (org-element-property :type timestamp)))
  17779. (if (or (not org-display-custom-times) (eq type 'diary))
  17780. (org-element-interpret-data timestamp)
  17781. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  17782. org-time-stamp-custom-formats)))
  17783. (if (and (not boundary) (memq type '(active-range inactive-range)))
  17784. (concat (org-timestamp-format timestamp fmt)
  17785. "--"
  17786. (org-timestamp-format timestamp fmt t))
  17787. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  17788. ;;; Other stuff
  17789. (defvar reftex-docstruct-symbol)
  17790. (defvar org--rds)
  17791. (defun org-reftex-citation ()
  17792. "Use `reftex-citation' to insert a citation into the buffer.
  17793. This looks for a line like
  17794. #+BIBLIOGRAPHY: foo plain option:-d
  17795. and derives from it that foo.bib is the bibliography file relevant
  17796. for this document. It then installs the necessary environment for RefTeX
  17797. to work in this buffer and calls `reftex-citation' to insert a citation
  17798. into the buffer.
  17799. Export of such citations to both LaTeX and HTML is handled by the contributed
  17800. package ox-bibtex by Taru Karttunen."
  17801. (interactive)
  17802. (let ((reftex-docstruct-symbol 'org--rds)
  17803. org--rds bib)
  17804. (org-with-wide-buffer
  17805. (let ((case-fold-search t)
  17806. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  17807. (if (not (save-excursion
  17808. (or (re-search-forward re nil t)
  17809. (re-search-backward re nil t))))
  17810. (user-error "No bibliography defined in file")
  17811. (setq bib (concat (match-string 1) ".bib")
  17812. org--rds (list (list 'bib bib))))))
  17813. (call-interactively 'reftex-citation)))
  17814. ;;;; Functions extending outline functionality
  17815. (defun org-beginning-of-line (&optional n)
  17816. "Go to the beginning of the current visible line.
  17817. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17818. symbol `reversed', on the first attempt move to where the
  17819. headline text starts, and only move to beginning of line when the
  17820. cursor is already before the start of the text of the headline.
  17821. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  17822. start of the text on the second attempt.
  17823. With argument N not nil or 1, move forward N - 1 lines first."
  17824. (interactive "^p")
  17825. (let ((origin (point))
  17826. (special (pcase org-special-ctrl-a/e
  17827. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  17828. deactivate-mark)
  17829. ;; First move to a visible line.
  17830. (if (bound-and-true-p visual-line-mode)
  17831. (beginning-of-visual-line n)
  17832. (move-beginning-of-line n)
  17833. ;; `move-beginning-of-line' may leave point after invisible
  17834. ;; characters if line starts with such of these (e.g., with
  17835. ;; a link at column 0). Really move to the beginning of the
  17836. ;; current visible line.
  17837. (beginning-of-line))
  17838. (cond
  17839. ;; No special behavior. Point is already at the beginning of
  17840. ;; a line, logical or visual.
  17841. ((not special))
  17842. ;; `beginning-of-visual-line' left point before logical beginning
  17843. ;; of line: point is at the beginning of a visual line. Bail
  17844. ;; out.
  17845. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  17846. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  17847. ;; At a headline, special position is before the title, but
  17848. ;; after any TODO keyword or priority cookie.
  17849. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  17850. (line-end-position)))
  17851. (bol (point)))
  17852. (if (eq special 'reversed)
  17853. (when (and (= origin bol) (eq last-command this-command))
  17854. (goto-char refpos))
  17855. (when (or (> origin refpos) (= origin bol))
  17856. (goto-char refpos)))))
  17857. ((and (looking-at org-list-full-item-re)
  17858. (memq (org-element-type (save-match-data (org-element-at-point)))
  17859. '(item plain-list)))
  17860. ;; Set special position at first white space character after
  17861. ;; bullet, and check-box, if any.
  17862. (let ((after-bullet
  17863. (let ((box (match-end 3)))
  17864. (cond ((not box) (match-end 1))
  17865. ((eq (char-after box) ?\s) (1+ box))
  17866. (t box)))))
  17867. (if (eq special 'reversed)
  17868. (when (and (= (point) origin) (eq last-command this-command))
  17869. (goto-char after-bullet))
  17870. (when (or (> origin after-bullet) (= (point) origin))
  17871. (goto-char after-bullet)))))
  17872. ;; No special context. Point is already at beginning of line.
  17873. (t nil))))
  17874. (defun org-end-of-line (&optional n)
  17875. "Go to the end of the line, but before ellipsis, if any.
  17876. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  17877. symbol `reversed', ignore tags on the first attempt, and only
  17878. move to after the tags when the cursor is already beyond the end
  17879. of the headline.
  17880. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  17881. on the second attempt.
  17882. With argument N not nil or 1, move forward N - 1 lines first."
  17883. (interactive "^p")
  17884. (let ((origin (point))
  17885. (special (pcase org-special-ctrl-a/e
  17886. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  17887. deactivate-mark)
  17888. ;; First move to a visible line.
  17889. (if (bound-and-true-p visual-line-mode)
  17890. (beginning-of-visual-line n)
  17891. (move-beginning-of-line n))
  17892. (cond
  17893. ;; At a headline, with tags.
  17894. ((and special
  17895. (save-excursion
  17896. (beginning-of-line)
  17897. (let ((case-fold-search nil))
  17898. (looking-at org-complex-heading-regexp)))
  17899. (match-end 5))
  17900. (let ((tags (save-excursion
  17901. (goto-char (match-beginning 5))
  17902. (skip-chars-backward " \t")
  17903. (point)))
  17904. (visual-end (and (bound-and-true-p visual-line-mode)
  17905. (save-excursion
  17906. (end-of-visual-line)
  17907. (point)))))
  17908. ;; If `end-of-visual-line' brings us before end of line or
  17909. ;; even tags, i.e., the headline spans over multiple visual
  17910. ;; lines, move there.
  17911. (cond ((and visual-end
  17912. (< visual-end tags)
  17913. (<= origin visual-end))
  17914. (goto-char visual-end))
  17915. ((eq special 'reversed)
  17916. (if (and (= origin (line-end-position))
  17917. (eq this-command last-command))
  17918. (goto-char tags)
  17919. (end-of-line)))
  17920. (t
  17921. (if (or (< origin tags) (= origin (line-end-position)))
  17922. (goto-char tags)
  17923. (end-of-line))))))
  17924. ((bound-and-true-p visual-line-mode)
  17925. (let ((bol (line-beginning-position)))
  17926. (end-of-visual-line)
  17927. ;; If `end-of-visual-line' gets us past the ellipsis at the
  17928. ;; end of a line, backtrack and use `end-of-line' instead.
  17929. (when (/= bol (line-beginning-position))
  17930. (goto-char bol)
  17931. (end-of-line))))
  17932. (t (end-of-line)))))
  17933. (defun org-backward-sentence (&optional _arg)
  17934. "Go to beginning of sentence, or beginning of table field.
  17935. This will call `backward-sentence' or `org-table-beginning-of-field',
  17936. depending on context."
  17937. (interactive)
  17938. (let* ((element (org-element-at-point))
  17939. (contents-begin (org-element-property :contents-begin element))
  17940. (table (org-element-lineage element '(table) t)))
  17941. (if (and table
  17942. (> (point) contents-begin)
  17943. (<= (point) (org-element-property :contents-end table)))
  17944. (call-interactively #'org-table-beginning-of-field)
  17945. (save-restriction
  17946. (when (and contents-begin
  17947. (< (point-min) contents-begin)
  17948. (> (point) contents-begin))
  17949. (narrow-to-region contents-begin
  17950. (org-element-property :contents-end element)))
  17951. (call-interactively #'backward-sentence)))))
  17952. (defun org-forward-sentence (&optional _arg)
  17953. "Go to end of sentence, or end of table field.
  17954. This will call `forward-sentence' or `org-table-end-of-field',
  17955. depending on context."
  17956. (interactive)
  17957. (if (and (org-at-heading-p)
  17958. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  17959. (save-restriction
  17960. (narrow-to-region (line-beginning-position) (line-end-position))
  17961. (call-interactively #'forward-sentence))
  17962. (let* ((element (org-element-at-point))
  17963. (contents-end (org-element-property :contents-end element))
  17964. (table (org-element-lineage element '(table) t)))
  17965. (if (and table
  17966. (>= (point) (org-element-property :contents-begin table))
  17967. (< (point) contents-end))
  17968. (call-interactively #'org-table-end-of-field)
  17969. (save-restriction
  17970. (when (and contents-end
  17971. (> (point-max) contents-end)
  17972. ;; Skip blank lines between elements.
  17973. (< (org-element-property :end element)
  17974. (save-excursion (goto-char contents-end)
  17975. (skip-chars-forward " \r\t\n"))))
  17976. (narrow-to-region (org-element-property :contents-begin element)
  17977. contents-end))
  17978. ;; End of heading is considered as the end of a sentence.
  17979. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  17980. (call-interactively #'forward-sentence)))))))
  17981. (defun org-kill-line (&optional _arg)
  17982. "Kill line, to tags or end of line."
  17983. (interactive)
  17984. (cond
  17985. ((or (not org-special-ctrl-k)
  17986. (bolp)
  17987. (not (org-at-heading-p)))
  17988. (when (and (org-invisible-p (line-end-position))
  17989. org-ctrl-k-protect-subtree
  17990. (or (eq org-ctrl-k-protect-subtree 'error)
  17991. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  17992. (user-error
  17993. (substitute-command-keys
  17994. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  17995. (call-interactively
  17996. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  17997. ((org-match-line org-tag-line-re)
  17998. (let ((end (save-excursion
  17999. (goto-char (match-beginning 1))
  18000. (skip-chars-backward " \t")
  18001. (point))))
  18002. (if (<= end (point)) ;on tags part
  18003. (kill-region (point) (line-end-position))
  18004. (kill-region (point) end)))
  18005. ;; Only align tags when we are still on a heading:
  18006. (if (org-at-heading-p) (org-align-tags)))
  18007. (t (kill-region (point) (line-end-position)))))
  18008. (defun org-yank (&optional arg)
  18009. "Yank. If the kill is a subtree, treat it specially.
  18010. This command will look at the current kill and check if is a single
  18011. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18012. cursor is at the beginning of a line or after the stars of a currently
  18013. empty headline, then the yank is handled specially. How exactly depends
  18014. on the value of the following variables.
  18015. `org-yank-folded-subtrees'
  18016. By default, this variable is non-nil, which results in
  18017. subtree(s) being folded after insertion, except if doing so
  18018. would swallow text after the yanked text.
  18019. `org-yank-adjusted-subtrees'
  18020. When non-nil (the default value is nil), the subtree will be
  18021. promoted or demoted in order to fit into the local outline tree
  18022. structure, which means that the level will be adjusted so that it
  18023. becomes the smaller one of the two *visible* surrounding headings.
  18024. Any prefix to this command will cause `yank' to be called directly with
  18025. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18026. will just
  18027. plainly yank the text as it is.
  18028. \[1] The test checks if the first non-white line is a heading
  18029. and if there are no other headings with fewer stars."
  18030. (interactive "P")
  18031. (org-yank-generic 'yank arg))
  18032. (defun org-yank-generic (command arg)
  18033. "Perform some yank-like command.
  18034. This function implements the behavior described in the `org-yank'
  18035. documentation. However, it has been generalized to work for any
  18036. interactive command with similar behavior."
  18037. ;; pretend to be command COMMAND
  18038. (setq this-command command)
  18039. (if arg
  18040. (call-interactively command)
  18041. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18042. (and (org-kill-is-subtree-p)
  18043. (or (bolp)
  18044. (and (looking-at "[ \t]*$")
  18045. (string-match
  18046. "\\`\\*+\\'"
  18047. (buffer-substring (point-at-bol) (point)))))))
  18048. swallowp)
  18049. (cond
  18050. ((and subtreep org-yank-folded-subtrees)
  18051. (let ((beg (point))
  18052. end)
  18053. (if (and subtreep org-yank-adjusted-subtrees)
  18054. (org-paste-subtree nil nil 'for-yank)
  18055. (call-interactively command))
  18056. (setq end (point))
  18057. (goto-char beg)
  18058. (when (and (bolp) subtreep
  18059. (not (setq swallowp
  18060. (org-yank-folding-would-swallow-text beg end))))
  18061. (org-with-limited-levels
  18062. (or (looking-at org-outline-regexp)
  18063. (re-search-forward org-outline-regexp-bol end t))
  18064. (while (and (< (point) end) (looking-at org-outline-regexp))
  18065. (org-fold-subtree t)
  18066. (org-cycle-show-empty-lines 'folded)
  18067. (condition-case nil
  18068. (outline-forward-same-level 1)
  18069. (error (goto-char end))))))
  18070. (when swallowp
  18071. (message
  18072. "Inserted text not folded because that would swallow text"))
  18073. (goto-char end)
  18074. (skip-chars-forward " \t\n\r")
  18075. (beginning-of-line 1)
  18076. (push-mark beg 'nomsg)))
  18077. ((and subtreep org-yank-adjusted-subtrees)
  18078. (let ((beg (point-at-bol)))
  18079. (org-paste-subtree nil nil 'for-yank)
  18080. (push-mark beg 'nomsg)))
  18081. (t
  18082. (call-interactively command))))))
  18083. (defun org-yank-folding-would-swallow-text (beg end)
  18084. "Would `hide-subtree' at BEG swallow any text after END?"
  18085. (let (level)
  18086. (org-with-limited-levels
  18087. (save-excursion
  18088. (goto-char beg)
  18089. (when (or (looking-at org-outline-regexp)
  18090. (re-search-forward org-outline-regexp-bol end t))
  18091. (setq level (org-outline-level)))
  18092. (goto-char end)
  18093. (skip-chars-forward " \t\r\n\v\f")
  18094. (not (or (eobp)
  18095. (and (bolp) (looking-at-p org-outline-regexp)
  18096. (<= (org-outline-level) level))))))))
  18097. (defun org-back-to-heading (&optional invisible-ok)
  18098. "Go back to beginning of heading."
  18099. (beginning-of-line)
  18100. (or (org-at-heading-p (not invisible-ok))
  18101. (let (found)
  18102. (save-excursion
  18103. ;; At inlinetask end. Move to bol, so that the following
  18104. ;; search goes to the beginning of the inlinetask.
  18105. (when (and (featurep 'org-inlinetask)
  18106. (fboundp 'org-inlinetask-end-p)
  18107. (org-inlinetask-end-p))
  18108. (goto-char (line-beginning-position)))
  18109. (while (not found)
  18110. (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  18111. nil t)
  18112. (user-error "Before first headline at position %d in buffer %s"
  18113. (point) (current-buffer)))
  18114. ;; Skip inlinetask end.
  18115. (if (and (featurep 'org-inlinetask)
  18116. (fboundp 'org-inlinetask-end-p)
  18117. (org-inlinetask-end-p))
  18118. (org-inlinetask-goto-beginning)
  18119. (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  18120. (point))))))
  18121. (goto-char found)
  18122. found)))
  18123. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18124. "Go back to heading or first point in buffer.
  18125. If point is before first heading go to first point in buffer
  18126. instead of back to heading."
  18127. (if (org-before-first-heading-p)
  18128. (goto-char (point-min))
  18129. (org-back-to-heading invisible-ok)))
  18130. (defun org-before-first-heading-p ()
  18131. "Before first heading?
  18132. Respect narrowing."
  18133. (let ((cached (org-element-at-point nil 'cached)))
  18134. (if cached
  18135. (let ((cached-headline (org-element-lineage cached '(headline) t)))
  18136. (or (not cached-headline)
  18137. (< (org-element-property :begin cached-headline) (point-min))))
  18138. (org-with-limited-levels
  18139. (save-excursion
  18140. (end-of-line)
  18141. (null (re-search-backward org-outline-regexp-bol nil t)))))))
  18142. (defun org-at-heading-p (&optional invisible-not-ok)
  18143. "Return t if point is on a (possibly invisible) heading line.
  18144. If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  18145. (save-excursion
  18146. (beginning-of-line)
  18147. (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  18148. (looking-at outline-regexp))))
  18149. (defun org-in-commented-heading-p (&optional no-inheritance element)
  18150. "Non-nil if point is under a commented heading.
  18151. This function also checks ancestors of the current headline,
  18152. unless optional argument NO-INHERITANCE is non-nil.
  18153. Optional argument ELEMENT contains element at point."
  18154. (save-match-data
  18155. (let ((el (or element
  18156. (org-element-at-point nil 'cached)
  18157. (org-with-wide-buffer
  18158. (org-back-to-heading-or-point-min t)
  18159. (org-element-at-point)))))
  18160. (catch :found
  18161. (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  18162. (if no-inheritance
  18163. (org-element-property :commentedp el)
  18164. (while el
  18165. (when (org-element-property :commentedp el)
  18166. (throw :found t))
  18167. (setq el (org-element-property :parent el))))))))
  18168. (defun org-in-archived-heading-p (&optional no-inheritance element)
  18169. "Non-nil if point is under an archived heading.
  18170. This function also checks ancestors of the current headline,
  18171. unless optional argument NO-INHERITANCE is non-nil.
  18172. Optional argument ELEMENT contains element at point."
  18173. (cond
  18174. ((and (not element) (org-before-first-heading-p)) nil)
  18175. ((if element
  18176. (org-element-property :archivedp element)
  18177. (let ((tags (org-get-tags element 'local)))
  18178. (and tags
  18179. (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  18180. (no-inheritance nil)
  18181. (t
  18182. (if (org-element--cache-active-p)
  18183. (cl-some (lambda (el) (org-element-property :archivedp el))
  18184. (org-element-lineage (or element (org-element-at-point)) nil t))
  18185. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  18186. (defun org-at-comment-p nil
  18187. "Return t if cursor is in a commented line."
  18188. (save-excursion
  18189. (save-match-data
  18190. (beginning-of-line)
  18191. (looking-at org-comment-regexp))))
  18192. (defun org-at-keyword-p nil
  18193. "Return t if cursor is at a keyword-line."
  18194. (save-excursion
  18195. (move-beginning-of-line 1)
  18196. (looking-at org-keyword-regexp)))
  18197. (defun org-at-drawer-p nil
  18198. "Return t if cursor is at a drawer keyword."
  18199. (save-excursion
  18200. (move-beginning-of-line 1)
  18201. (looking-at org-drawer-regexp)))
  18202. (defun org-at-block-p nil
  18203. "Return t if cursor is at a block keyword."
  18204. (save-excursion
  18205. (move-beginning-of-line 1)
  18206. (looking-at org-block-regexp)))
  18207. (defun org-point-at-end-of-empty-headline ()
  18208. "If point is at the end of an empty headline, return t, else nil.
  18209. If the heading only contains a TODO keyword, it is still considered
  18210. empty."
  18211. (let ((case-fold-search nil))
  18212. (and (looking-at "[ \t]*$")
  18213. org-todo-line-regexp
  18214. (save-excursion
  18215. (beginning-of-line)
  18216. (looking-at org-todo-line-regexp)
  18217. (string= (match-string 3) "")))))
  18218. (defun org-at-heading-or-item-p ()
  18219. (or (org-at-heading-p) (org-at-item-p)))
  18220. (defun org-up-heading-all (arg)
  18221. "Move to the heading line of which the present line is a subheading.
  18222. This function considers both visible and invisible heading lines.
  18223. With argument, move up ARG levels."
  18224. (outline-up-heading arg t))
  18225. (defvar-local org--up-heading-cache nil
  18226. "Buffer-local `org-up-heading-safe' cache.")
  18227. (defvar-local org--up-heading-cache-tick nil
  18228. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18229. (defun org-up-heading-safe ()
  18230. "Move to the heading line of which the present line is a subheading.
  18231. This version will not throw an error. It will return the level of the
  18232. headline found, or nil if no higher level is found.
  18233. Also, this function will be a lot faster than `outline-up-heading',
  18234. because it relies on stars being the outline starters. This can really
  18235. make a significant difference in outlines with very many siblings."
  18236. (let ((element (and (org-element--cache-active-p)
  18237. (org-element-at-point nil t))))
  18238. (if element
  18239. (let* ((current-heading (org-element-lineage element '(headline) 'with-self))
  18240. (parent (org-element-lineage current-heading '(headline))))
  18241. (if (and parent
  18242. (<= (point-min) (org-element-property :begin parent)))
  18243. (progn
  18244. (goto-char (org-element-property :begin parent))
  18245. (org-element-property :level parent))
  18246. (when (and current-heading
  18247. (<= (point-min) (org-element-property :begin current-heading)))
  18248. (goto-char (org-element-property :begin current-heading))
  18249. nil)))
  18250. (when (ignore-errors (org-back-to-heading t))
  18251. (let (level-cache)
  18252. (unless org--up-heading-cache
  18253. (setq org--up-heading-cache (make-hash-table)))
  18254. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18255. (setq level-cache (gethash (point) org--up-heading-cache)))
  18256. (when (<= (point-min) (car level-cache) (point-max))
  18257. ;; Parent is inside accessible part of the buffer.
  18258. (progn (goto-char (car level-cache))
  18259. (cdr level-cache)))
  18260. ;; Buffer modified. Invalidate cache.
  18261. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18262. (setq-local org--up-heading-cache-tick
  18263. (buffer-chars-modified-tick))
  18264. (clrhash org--up-heading-cache))
  18265. (let* ((level-up (1- (funcall outline-level)))
  18266. (pos (point))
  18267. (result (and (> level-up 0)
  18268. (re-search-backward
  18269. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18270. (funcall outline-level))))
  18271. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18272. result)))))))
  18273. (defun org-up-heading-or-point-min ()
  18274. "Move to the heading line of which the present is a subheading, or point-min.
  18275. This version is needed to make point-min behave like a virtual
  18276. heading of level 0 for property-inheritance. It will return the
  18277. level of the headline found (down to 0) or nil if already at a
  18278. point before the first headline or at point-min."
  18279. (when (ignore-errors (org-back-to-heading t))
  18280. (if (< 1 (funcall outline-level))
  18281. (or (org-up-heading-safe)
  18282. ;; The first heading may not be level 1 heading.
  18283. (goto-char (point-min)))
  18284. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18285. (defun org-first-sibling-p ()
  18286. "Is this heading the first child of its parents?"
  18287. (interactive)
  18288. (let ((re org-outline-regexp-bol)
  18289. level l)
  18290. (unless (org-at-heading-p t)
  18291. (user-error "Not at a heading"))
  18292. (setq level (funcall outline-level))
  18293. (save-excursion
  18294. (if (not (re-search-backward re nil t))
  18295. t
  18296. (setq l (funcall outline-level))
  18297. (< l level)))))
  18298. (defun org-goto-sibling (&optional previous)
  18299. "Goto the next sibling, even if it is invisible.
  18300. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18301. when a sibling was found. When none is found, return nil and don't
  18302. move point."
  18303. (let ((fun (if previous 're-search-backward 're-search-forward))
  18304. (pos (point))
  18305. (re org-outline-regexp-bol)
  18306. level l)
  18307. (when (ignore-errors (org-back-to-heading t))
  18308. (setq level (funcall outline-level))
  18309. (catch 'exit
  18310. (or previous (forward-char 1))
  18311. (while (funcall fun re nil t)
  18312. (setq l (funcall outline-level))
  18313. (when (< l level) (goto-char pos) (throw 'exit nil))
  18314. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18315. (goto-char pos)
  18316. nil))))
  18317. (defun org-goto-first-child (&optional element)
  18318. "Goto the first child, even if it is invisible.
  18319. Return t when a child was found. Otherwise don't move point and
  18320. return nil."
  18321. (if (org-element--cache-active-p)
  18322. (let ((heading (org-element-lineage
  18323. (or element (org-element-at-point))
  18324. '(headline inlinetask org-data)
  18325. t)))
  18326. (when heading
  18327. (unless (or (eq 'inlinetask (org-element-type heading))
  18328. (not (org-element-property :contents-begin heading)))
  18329. (let ((pos (point)))
  18330. (goto-char (org-element-property :contents-begin heading))
  18331. (if (re-search-forward
  18332. org-outline-regexp-bol
  18333. (org-element-property :end heading)
  18334. t)
  18335. (progn (goto-char (match-beginning 0)) t)
  18336. (goto-char pos) nil)))))
  18337. (let (level (pos (point)) (re org-outline-regexp-bol))
  18338. (when (org-back-to-heading-or-point-min t)
  18339. (setq level (org-outline-level))
  18340. (forward-char 1)
  18341. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18342. (progn (goto-char (match-beginning 0)) t)
  18343. (goto-char pos) nil)))))
  18344. (defun org-get-next-sibling ()
  18345. "Move to next heading of the same level, and return point.
  18346. If there is no such heading, return nil.
  18347. This is like outline-next-sibling, but invisible headings are ok."
  18348. (let ((level (funcall outline-level)))
  18349. (outline-next-heading)
  18350. (while (and (not (eobp)) (> (funcall outline-level) level))
  18351. (outline-next-heading))
  18352. (unless (or (eobp) (< (funcall outline-level) level))
  18353. (point))))
  18354. (defun org-get-previous-sibling ()
  18355. "Move to previous heading of the same level, and return point.
  18356. If there is no such heading, return nil."
  18357. (let ((opoint (point))
  18358. (level (funcall outline-level)))
  18359. (outline-previous-heading)
  18360. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18361. (while (and (> (funcall outline-level) level)
  18362. (not (bobp)))
  18363. (outline-previous-heading))
  18364. (unless (< (funcall outline-level) level)
  18365. (point)))))
  18366. (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  18367. "Goto to the end of a subtree at point or for ELEMENT heading."
  18368. ;; This contains an exact copy of the original function, but it uses
  18369. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18370. ;; trees and before first headline. And is uses an invisible-ok argument.
  18371. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18372. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18373. ;; with many children and grandchildren etc, this can be much faster
  18374. ;; than the outline version.
  18375. (org-back-to-heading-or-point-min invisible-ok)
  18376. (unless (and (org-element--cache-active-p)
  18377. (let ((cached (or element (org-element-at-point nil t))))
  18378. (and cached
  18379. (eq 'headline (org-element-type cached))
  18380. (goto-char (org-element-property
  18381. :end cached)))))
  18382. (let ((first t)
  18383. (level (funcall outline-level)))
  18384. (cond ((= level 0)
  18385. (goto-char (point-max)))
  18386. ((and (derived-mode-p 'org-mode) (< level 1000))
  18387. ;; A true heading (not a plain list item), in Org
  18388. ;; This means we can easily find the end by looking
  18389. ;; only for the right number of stars. Using a regexp to do
  18390. ;; this is so much faster than using a Lisp loop.
  18391. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18392. (forward-char 1)
  18393. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18394. (t
  18395. ;; something else, do it the slow way
  18396. (while (and (not (eobp))
  18397. (or first (> (funcall outline-level) level)))
  18398. (setq first nil)
  18399. (outline-next-heading))))))
  18400. (unless to-heading
  18401. (when (memq (preceding-char) '(?\n ?\^M))
  18402. ;; Go to end of line before heading
  18403. (forward-char -1)
  18404. (when (memq (preceding-char) '(?\n ?\^M))
  18405. ;; leave blank line before heading
  18406. (forward-char -1))))
  18407. (point))
  18408. (defun org-end-of-meta-data (&optional full)
  18409. "Skip planning line and properties drawer in current entry.
  18410. When optional argument FULL is t, also skip planning information,
  18411. clocking lines and any kind of drawer.
  18412. When FULL is non-nil but not t, skip planning information,
  18413. properties, clocking lines and logbook drawers."
  18414. (org-back-to-heading t)
  18415. (forward-line)
  18416. ;; Skip planning information.
  18417. (when (looking-at-p org-planning-line-re) (forward-line))
  18418. ;; Skip property drawer.
  18419. (when (looking-at org-property-drawer-re)
  18420. (goto-char (match-end 0))
  18421. (forward-line))
  18422. ;; When FULL is not nil, skip more.
  18423. (when (and full (not (org-at-heading-p)))
  18424. (catch 'exit
  18425. (let ((end (save-excursion (outline-next-heading) (point)))
  18426. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  18427. (while (not (eobp))
  18428. (cond ;; Skip clock lines.
  18429. ((looking-at-p re) (forward-line))
  18430. ;; Skip logbook drawer.
  18431. ((looking-at-p org-logbook-drawer-re)
  18432. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18433. (forward-line)
  18434. (throw 'exit t)))
  18435. ;; When FULL is t, skip regular drawer too.
  18436. ((and (eq full t) (looking-at-p org-drawer-regexp))
  18437. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  18438. (forward-line)
  18439. (throw 'exit t)))
  18440. (t (throw 'exit t))))))))
  18441. (defun org--line-fully-invisible-p ()
  18442. "Return non-nil if the current line is fully invisible."
  18443. (let ((line-beg (line-beginning-position))
  18444. (line-pos (1- (line-end-position)))
  18445. (is-invisible t))
  18446. (while (and (< line-beg line-pos) is-invisible)
  18447. (setq is-invisible (org-invisible-p line-pos))
  18448. (setq line-pos (1- line-pos)))
  18449. is-invisible))
  18450. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  18451. "Move forward to the ARG'th subheading at same level as this one.
  18452. Stop at the first and last subheadings of a superior heading.
  18453. Normally this only looks at visible headings, but when INVISIBLE-OK is
  18454. non-nil it will also look at invisible ones."
  18455. (interactive "p")
  18456. (let ((backward? (and arg (< arg 0))))
  18457. (if (org-before-first-heading-p)
  18458. (if backward? (goto-char (point-min)) (outline-next-heading))
  18459. (org-back-to-heading invisible-ok)
  18460. (unless backward? (end-of-line)) ;do not match current headline
  18461. (let ((level (- (match-end 0) (match-beginning 0) 1))
  18462. (f (if backward? #'re-search-backward #'re-search-forward))
  18463. (count (if arg (abs arg) 1))
  18464. (result (point)))
  18465. (while (and (> count 0)
  18466. (funcall f org-outline-regexp-bol nil 'move))
  18467. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  18468. (cond ((< l level) (setq count 0))
  18469. ((and (= l level)
  18470. (or invisible-ok
  18471. ;; FIXME: See commit a700fadd72 and the
  18472. ;; related discussion on why using
  18473. ;; `org--line-fully-invisible-p' is needed
  18474. ;; here, which is to serve the needs of an
  18475. ;; external package. If the change is
  18476. ;; wrong regarding Org itself, it should
  18477. ;; be removed.
  18478. (not (org--line-fully-invisible-p))))
  18479. (cl-decf count)
  18480. (when (= l level) (setq result (point)))))))
  18481. (goto-char result))
  18482. (beginning-of-line))))
  18483. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  18484. "Move backward to the ARG'th subheading at same level as this one.
  18485. Stop at the first and last subheadings of a superior heading."
  18486. (interactive "p")
  18487. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  18488. (defun org-next-visible-heading--overlays (arg)
  18489. "Move to the next visible heading line.
  18490. With ARG, repeats or can move backward if negative."
  18491. (interactive "p")
  18492. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18493. (if (< arg 0)
  18494. (beginning-of-line)
  18495. (end-of-line))
  18496. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18497. (unless (bobp)
  18498. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18499. (`(outline . ,o)
  18500. (goto-char (overlay-start o))
  18501. (re-search-backward regexp nil :move))
  18502. (_ nil))))
  18503. (cl-incf arg))
  18504. (while (and (> arg 0) (re-search-forward regexp nil t))
  18505. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  18506. (`(outline . ,o)
  18507. (goto-char (overlay-end o))
  18508. (re-search-forward regexp nil :move))
  18509. (_
  18510. (end-of-line)
  18511. nil))) ;leave the loop
  18512. (cl-decf arg))
  18513. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18514. (defun org-next-visible-heading--text-properties (arg)
  18515. "Move to the next visible heading line.
  18516. With ARG, repeats or can move backward if negative."
  18517. (interactive "p")
  18518. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  18519. (if (< arg 0)
  18520. (beginning-of-line)
  18521. (end-of-line))
  18522. (while (and (< arg 0) (re-search-backward regexp nil :move))
  18523. (unless (bobp)
  18524. (when (org-fold-folded-p)
  18525. (goto-char (org-fold-previous-visibility-change))
  18526. (unless (looking-at-p regexp)
  18527. (re-search-backward regexp nil :mode))))
  18528. (cl-incf arg))
  18529. (while (and (> arg 0) (re-search-forward regexp nil :move))
  18530. (when (org-fold-folded-p)
  18531. (goto-char (org-fold-next-visibility-change))
  18532. (skip-chars-forward " \t\n")
  18533. (end-of-line))
  18534. (cl-decf arg))
  18535. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  18536. (defun org-next-visible-heading (arg)
  18537. "Move to the next visible heading line.
  18538. With ARG, repeats or can move backward if negative."
  18539. (interactive "p")
  18540. (if (eq org-fold-core-style 'text-properties)
  18541. (org-next-visible-heading--text-properties arg)
  18542. (org-next-visible-heading--overlays arg)))
  18543. (defun org-previous-visible-heading (arg)
  18544. "Move to the previous visible heading.
  18545. With ARG, repeats or can move forward if negative."
  18546. (interactive "p")
  18547. (org-next-visible-heading (- arg)))
  18548. (defun org-forward-paragraph (&optional arg)
  18549. "Move forward by a paragraph, or equivalent, unit.
  18550. With argument ARG, do it ARG times;
  18551. a negative argument ARG = -N means move backward N paragraphs.
  18552. The function moves point between two structural
  18553. elements (paragraphs, tables, lists, etc.).
  18554. It also provides the following special moves for convenience:
  18555. - on a table or a property drawer, move to its beginning;
  18556. - on comment, example, export, source and verse blocks, stop
  18557. at blank lines;
  18558. - skip consecutive clocks, diary S-exps, and keywords."
  18559. (interactive "^p")
  18560. (unless arg (setq arg 1))
  18561. (if (< arg 0) (org-backward-paragraph (- arg))
  18562. (while (and (> arg 0) (not (eobp)))
  18563. (org--forward-paragraph-once)
  18564. (cl-decf arg))
  18565. ;; Return moves left.
  18566. arg))
  18567. (defun org-backward-paragraph (&optional arg)
  18568. "Move backward by a paragraph, or equivalent, unit.
  18569. With argument ARG, do it ARG times;
  18570. a negative argument ARG = -N means move forward N paragraphs.
  18571. The function moves point between two structural
  18572. elements (paragraphs, tables, lists, etc.).
  18573. It also provides the following special moves for convenience:
  18574. - on a table or a property drawer, move to its beginning;
  18575. - on comment, example, export, source and verse blocks, stop
  18576. at blank lines;
  18577. - skip consecutive clocks, diary S-exps, and keywords."
  18578. (interactive "^p")
  18579. (unless arg (setq arg 1))
  18580. (if (< arg 0) (org-forward-paragraph (- arg))
  18581. (while (and (> arg 0) (not (bobp)))
  18582. (org--backward-paragraph-once)
  18583. (cl-decf arg))
  18584. ;; Return moves left.
  18585. arg))
  18586. (defun org--paragraph-at-point ()
  18587. "Return paragraph, or equivalent, element at point.
  18588. Paragraph element at point is the element at point, with the
  18589. following special cases:
  18590. - treat table rows (resp. node properties) as the table
  18591. \(resp. property drawer) containing them.
  18592. - treat plain lists with an item every line as a whole.
  18593. - treat consecutive keywords, clocks, and diary-sexps as a single
  18594. block.
  18595. Function may return a real element, or a pseudo-element with type
  18596. `pseudo-paragraph'."
  18597. (let* ((e (org-element-at-point))
  18598. (type (org-element-type e))
  18599. ;; If we need to fake a new pseudo-element, triplet is
  18600. ;;
  18601. ;; (BEG END PARENT)
  18602. ;;
  18603. ;; where BEG and END are element boundaries, and PARENT the
  18604. ;; element containing it, or nil.
  18605. (triplet
  18606. (cond
  18607. ((memq type '(table property-drawer))
  18608. (list (org-element-property :begin e)
  18609. (org-element-property :end e)
  18610. (org-element-property :parent e)))
  18611. ((memq type '(node-property table-row))
  18612. (let ((e (org-element-property :parent e)))
  18613. (list (org-element-property :begin e)
  18614. (org-element-property :end e)
  18615. (org-element-property :parent e))))
  18616. ((memq type '(clock diary-sexp keyword))
  18617. (let* ((regexp (pcase type
  18618. (`clock org-clock-line-re)
  18619. (`diary-sexp "%%(")
  18620. (_ org-keyword-regexp)))
  18621. (end (if (< 0 (org-element-property :post-blank e))
  18622. (org-element-property :end e)
  18623. (org-with-wide-buffer
  18624. (forward-line)
  18625. (while (looking-at regexp) (forward-line))
  18626. (skip-chars-forward " \t\n")
  18627. (line-beginning-position))))
  18628. (begin (org-with-point-at (org-element-property :begin e)
  18629. (while (and (not (bobp)) (looking-at regexp))
  18630. (forward-line -1))
  18631. ;; We may have gotten one line too far.
  18632. (if (looking-at regexp)
  18633. (point)
  18634. (line-beginning-position 2)))))
  18635. (list begin end (org-element-property :parent e))))
  18636. ;; Find the full plain list containing point, the check it
  18637. ;; contains exactly one line per item.
  18638. ((let ((l (org-element-lineage e '(plain-list) t)))
  18639. (while (memq (org-element-type (org-element-property :parent l))
  18640. '(item plain-list))
  18641. (setq l (org-element-property :parent l)))
  18642. (and l
  18643. (org-with-point-at (org-element-property :post-affiliated l)
  18644. (forward-line (length (org-element-property :structure l)))
  18645. (= (point) (org-element-property :contents-end l)))
  18646. ;; Return value.
  18647. (list (org-element-property :begin l)
  18648. (org-element-property :end l)
  18649. (org-element-property :parent l)))))
  18650. (t nil)))) ;no triplet: return element
  18651. (pcase triplet
  18652. (`(,b ,e ,p)
  18653. (org-element-create
  18654. 'pseudo-paragraph
  18655. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  18656. (_ e))))
  18657. (defun org--forward-paragraph-once--overlays ()
  18658. "Move forward to end of paragraph or equivalent, once.
  18659. See `org-forward-paragraph'."
  18660. (interactive)
  18661. (save-restriction
  18662. (widen)
  18663. (skip-chars-forward " \t\n")
  18664. (cond
  18665. ((eobp) nil)
  18666. ;; When inside a folded part, move out of it.
  18667. ((pcase (get-char-property-and-overlay (point) 'invisible)
  18668. (`(,(or `outline `org-hide-block) . ,o)
  18669. (goto-char (overlay-end o))
  18670. (forward-line)
  18671. t)
  18672. (_ nil)))
  18673. (t
  18674. (let* ((element (org--paragraph-at-point))
  18675. (type (org-element-type element))
  18676. (contents-begin (org-element-property :contents-begin element))
  18677. (end (org-element-property :end element))
  18678. (post-affiliated (org-element-property :post-affiliated element)))
  18679. (cond
  18680. ((eq type 'plain-list)
  18681. (forward-char)
  18682. (org--forward-paragraph-once))
  18683. ;; If the element is folded, skip it altogether.
  18684. ((pcase (org-with-point-at post-affiliated
  18685. (get-char-property-and-overlay (line-end-position)
  18686. 'invisible))
  18687. (`(,(or `outline `org-hide-block) . ,o)
  18688. (goto-char (overlay-end o))
  18689. (forward-line)
  18690. t)
  18691. (_ nil)))
  18692. ;; At a greater element, move inside.
  18693. ((and contents-begin
  18694. (> contents-begin (point))
  18695. (not (eq type 'paragraph)))
  18696. (goto-char contents-begin)
  18697. ;; Items and footnote definitions contents may not start at
  18698. ;; the beginning of the line. In this case, skip until the
  18699. ;; next paragraph.
  18700. (cond
  18701. ((not (bolp)) (org--forward-paragraph-once))
  18702. ((org-previous-line-empty-p) (forward-line -1))
  18703. (t nil)))
  18704. ;; Move between empty lines in some blocks.
  18705. ((memq type '(comment-block example-block export-block src-block
  18706. verse-block))
  18707. (let ((contents-start
  18708. (org-with-point-at post-affiliated
  18709. (line-beginning-position 2))))
  18710. (if (< (point) contents-start)
  18711. (goto-char contents-start)
  18712. (let ((contents-end
  18713. (org-with-point-at end
  18714. (skip-chars-backward " \t\n")
  18715. (line-beginning-position))))
  18716. (cond
  18717. ((>= (point) contents-end)
  18718. (goto-char end)
  18719. (skip-chars-backward " \t\n")
  18720. (forward-line))
  18721. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18722. (forward-line -1))
  18723. (t nil))))))
  18724. (t
  18725. ;; Move to element's end.
  18726. (goto-char end)
  18727. (skip-chars-backward " \t\n")
  18728. (forward-line))))))))
  18729. (defun org--forward-paragraph-once--text-properties ()
  18730. "Move forward to end of paragraph or equivalent, once.
  18731. See `org-forward-paragraph'."
  18732. (interactive)
  18733. (save-restriction
  18734. (widen)
  18735. (skip-chars-forward " \t\n")
  18736. (cond
  18737. ((eobp) nil)
  18738. ;; When inside a folded part, move out of it.
  18739. ((when (org-invisible-p nil t)
  18740. (goto-char (cdr (org-fold-get-region-at-point)))
  18741. (forward-line)
  18742. t))
  18743. (t
  18744. (let* ((element (org--paragraph-at-point))
  18745. (type (org-element-type element))
  18746. (contents-begin (org-element-property :contents-begin element))
  18747. (end (org-element-property :end element))
  18748. (post-affiliated (org-element-property :post-affiliated element)))
  18749. (cond
  18750. ((eq type 'plain-list)
  18751. (forward-char)
  18752. (org--forward-paragraph-once))
  18753. ;; If the element is folded, skip it altogether.
  18754. ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18755. (goto-char (cdr (org-fold-get-region-at-point
  18756. nil
  18757. (org-with-point-at post-affiliated
  18758. (line-end-position)))))
  18759. (forward-line)
  18760. t))
  18761. ;; At a greater element, move inside.
  18762. ((and contents-begin
  18763. (> contents-begin (point))
  18764. (not (eq type 'paragraph)))
  18765. (goto-char contents-begin)
  18766. ;; Items and footnote definitions contents may not start at
  18767. ;; the beginning of the line. In this case, skip until the
  18768. ;; next paragraph.
  18769. (cond
  18770. ((not (bolp)) (org--forward-paragraph-once))
  18771. ((org-previous-line-empty-p) (forward-line -1))
  18772. (t nil)))
  18773. ;; Move between empty lines in some blocks.
  18774. ((memq type '(comment-block example-block export-block src-block
  18775. verse-block))
  18776. (let ((contents-start
  18777. (org-with-point-at post-affiliated
  18778. (line-beginning-position 2))))
  18779. (if (< (point) contents-start)
  18780. (goto-char contents-start)
  18781. (let ((contents-end
  18782. (org-with-point-at end
  18783. (skip-chars-backward " \t\n")
  18784. (line-beginning-position))))
  18785. (cond
  18786. ((>= (point) contents-end)
  18787. (goto-char end)
  18788. (skip-chars-backward " \t\n")
  18789. (forward-line))
  18790. ((re-search-forward "^[ \t]*\n" contents-end :move)
  18791. (forward-line -1))
  18792. (t nil))))))
  18793. (t
  18794. ;; Move to element's end.
  18795. (goto-char end)
  18796. (skip-chars-backward " \t\n")
  18797. (forward-line))))))))
  18798. (defun org--forward-paragraph-once ()
  18799. "Move forward to end of paragraph or equivalent, once.
  18800. See `org-forward-paragraph'."
  18801. (interactive)
  18802. (if (eq org-fold-core-style 'text-properties)
  18803. (org--forward-paragraph-once--text-properties)
  18804. (org--forward-paragraph-once--overlays)))
  18805. (defun org--backward-paragraph-once--overlays ()
  18806. "Move backward to start of paragraph or equivalent, once.
  18807. See `org-backward-paragraph'."
  18808. (interactive)
  18809. (save-restriction
  18810. (widen)
  18811. (cond
  18812. ((bobp) nil)
  18813. ;; Blank lines at the beginning of the buffer.
  18814. ((and (org-match-line "^[ \t]*$")
  18815. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18816. (goto-char (point-min)))
  18817. ;; When inside a folded part, move out of it.
  18818. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  18819. (`(,(or `outline `org-hide-block) . ,o)
  18820. (goto-char (1- (overlay-start o)))
  18821. (org--backward-paragraph-once)
  18822. t)
  18823. (_ nil)))
  18824. (t
  18825. (let* ((element (org--paragraph-at-point))
  18826. (type (org-element-type element))
  18827. (begin (org-element-property :begin element))
  18828. (post-affiliated (org-element-property :post-affiliated element))
  18829. (contents-end (org-element-property :contents-end element))
  18830. (end (org-element-property :end element))
  18831. (parent (org-element-property :parent element))
  18832. (reach
  18833. ;; Move to the visible empty line above position P, or
  18834. ;; to position P. Return t.
  18835. (lambda (p)
  18836. (goto-char p)
  18837. (when (and (org-previous-line-empty-p)
  18838. (let ((end (line-end-position 0)))
  18839. (or (= end (point-min))
  18840. (not (org-invisible-p (1- end))))))
  18841. (forward-line -1))
  18842. t)))
  18843. (cond
  18844. ;; Already at the beginning of an element.
  18845. ((= begin (point))
  18846. (cond
  18847. ;; There is a blank line above. Move there.
  18848. ((and (org-previous-line-empty-p)
  18849. (let ((lep (line-end-position 0)))
  18850. ;; When the first headline start at point 2, don't choke while
  18851. ;; checking with `org-invisible-p'.
  18852. (or (= lep 1)
  18853. (not (org-invisible-p (1- (line-end-position 0)))))))
  18854. (forward-line -1))
  18855. ;; At the beginning of the first element within a greater
  18856. ;; element. Move to the beginning of the greater element.
  18857. ((and parent
  18858. (not (eq 'section (org-element-type parent)))
  18859. (= begin (org-element-property :contents-begin parent)))
  18860. (funcall reach (org-element-property :begin parent)))
  18861. ;; Since we have to move anyway, find the beginning
  18862. ;; position of the element above.
  18863. (t
  18864. (forward-char -1)
  18865. (org--backward-paragraph-once))))
  18866. ;; Skip paragraphs at the very beginning of footnote
  18867. ;; definitions or items.
  18868. ((and (eq type 'paragraph)
  18869. (org-with-point-at begin (not (bolp))))
  18870. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18871. ;; If the element is folded, skip it altogether.
  18872. ((org-with-point-at post-affiliated
  18873. (org-invisible-p (line-end-position) t))
  18874. (funcall reach begin))
  18875. ;; At the end of a greater element, move inside.
  18876. ((and contents-end
  18877. (<= contents-end (point))
  18878. (not (eq type 'paragraph)))
  18879. (cond
  18880. ((memq type '(footnote-definition plain-list))
  18881. (skip-chars-backward " \t\n")
  18882. (org--backward-paragraph-once))
  18883. ((= contents-end (point))
  18884. (forward-char -1)
  18885. (org--backward-paragraph-once))
  18886. (t
  18887. (goto-char contents-end))))
  18888. ;; Move between empty lines in some blocks.
  18889. ((and (memq type '(comment-block example-block export-block src-block
  18890. verse-block))
  18891. (let ((contents-start
  18892. (org-with-point-at post-affiliated
  18893. (line-beginning-position 2))))
  18894. (when (> (point) contents-start)
  18895. (let ((contents-end
  18896. (org-with-point-at end
  18897. (skip-chars-backward " \t\n")
  18898. (line-beginning-position))))
  18899. (if (> (point) contents-end)
  18900. (progn (goto-char contents-end) t)
  18901. (skip-chars-backward " \t\n" begin)
  18902. (re-search-backward "^[ \t]*\n" contents-start :move)
  18903. t))))))
  18904. ;; Move to element's start.
  18905. (t
  18906. (funcall reach begin))))))))
  18907. (defun org--backward-paragraph-once--text-properties ()
  18908. "Move backward to start of paragraph or equivalent, once.
  18909. See `org-backward-paragraph'."
  18910. (interactive)
  18911. (save-restriction
  18912. (widen)
  18913. (cond
  18914. ((bobp) nil)
  18915. ;; Blank lines at the beginning of the buffer.
  18916. ((and (org-match-line "^[ \t]*$")
  18917. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  18918. (goto-char (point-min)))
  18919. ;; When inside a folded part, move out of it.
  18920. ((when (org-invisible-p (1- (point)) t)
  18921. (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  18922. (org--backward-paragraph-once)
  18923. t))
  18924. (t
  18925. (let* ((element (org--paragraph-at-point))
  18926. (type (org-element-type element))
  18927. (begin (org-element-property :begin element))
  18928. (post-affiliated (org-element-property :post-affiliated element))
  18929. (contents-end (org-element-property :contents-end element))
  18930. (end (org-element-property :end element))
  18931. (parent (org-element-property :parent element))
  18932. (reach
  18933. ;; Move to the visible empty line above position P, or
  18934. ;; to position P. Return t.
  18935. (lambda (p)
  18936. (goto-char p)
  18937. (when (and (org-previous-line-empty-p)
  18938. (let ((end (line-end-position 0)))
  18939. (or (= end (point-min))
  18940. (not (org-invisible-p (1- end))))))
  18941. (forward-line -1))
  18942. t)))
  18943. (cond
  18944. ;; Already at the beginning of an element.
  18945. ((= begin (point))
  18946. (cond
  18947. ;; There is a blank line above. Move there.
  18948. ((and (org-previous-line-empty-p)
  18949. (not (org-invisible-p (1- (line-end-position 0)))))
  18950. (forward-line -1))
  18951. ;; At the beginning of the first element within a greater
  18952. ;; element. Move to the beginning of the greater element.
  18953. ((and parent
  18954. (not (eq 'section (org-element-type parent)))
  18955. (= begin (org-element-property :contents-begin parent)))
  18956. (funcall reach (org-element-property :begin parent)))
  18957. ;; Since we have to move anyway, find the beginning
  18958. ;; position of the element above.
  18959. (t
  18960. (forward-char -1)
  18961. (org--backward-paragraph-once))))
  18962. ;; Skip paragraphs at the very beginning of footnote
  18963. ;; definitions or items.
  18964. ((and (eq type 'paragraph)
  18965. (org-with-point-at begin (not (bolp))))
  18966. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  18967. ;; If the element is folded, skip it altogether.
  18968. ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  18969. (funcall reach begin))
  18970. ;; At the end of a greater element, move inside.
  18971. ((and contents-end
  18972. (<= contents-end (point))
  18973. (not (eq type 'paragraph)))
  18974. (cond
  18975. ((memq type '(footnote-definition plain-list))
  18976. (skip-chars-backward " \t\n")
  18977. (org--backward-paragraph-once))
  18978. ((= contents-end (point))
  18979. (forward-char -1)
  18980. (org--backward-paragraph-once))
  18981. (t
  18982. (goto-char contents-end))))
  18983. ;; Move between empty lines in some blocks.
  18984. ((and (memq type '(comment-block example-block export-block src-block
  18985. verse-block))
  18986. (let ((contents-start
  18987. (org-with-point-at post-affiliated
  18988. (line-beginning-position 2))))
  18989. (when (> (point) contents-start)
  18990. (let ((contents-end
  18991. (org-with-point-at end
  18992. (skip-chars-backward " \t\n")
  18993. (line-beginning-position))))
  18994. (if (> (point) contents-end)
  18995. (progn (goto-char contents-end) t)
  18996. (skip-chars-backward " \t\n" begin)
  18997. (re-search-backward "^[ \t]*\n" contents-start :move)
  18998. t))))))
  18999. ;; Move to element's start.
  19000. (t
  19001. (funcall reach begin))))))))
  19002. (defun org--backward-paragraph-once ()
  19003. "Move backward to start of paragraph or equivalent, once.
  19004. See `org-backward-paragraph'."
  19005. (interactive)
  19006. (if (eq org-fold-core-style 'text-properties)
  19007. (org--backward-paragraph-once--text-properties)
  19008. (org--backward-paragraph-once--overlays)))
  19009. (defun org-forward-element ()
  19010. "Move forward by one element.
  19011. Move to the next element at the same level, when possible."
  19012. (interactive)
  19013. (cond ((eobp) (user-error "Cannot move further down"))
  19014. ((org-with-limited-levels (org-at-heading-p))
  19015. (let ((origin (point)))
  19016. (goto-char (org-end-of-subtree nil t))
  19017. (unless (org-with-limited-levels (org-at-heading-p))
  19018. (goto-char origin)
  19019. (user-error "Cannot move further down"))))
  19020. (t
  19021. (let* ((elem (org-element-at-point))
  19022. (end (org-element-property :end elem))
  19023. (parent (org-element-property :parent elem)))
  19024. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19025. (goto-char (org-element-property :end parent)))
  19026. ((integer-or-marker-p end) (goto-char end))
  19027. (t (message "No element at point")))))))
  19028. (defun org-backward-element ()
  19029. "Move backward by one element.
  19030. Move to the previous element at the same level, when possible."
  19031. (interactive)
  19032. (cond ((bobp) (user-error "Cannot move further up"))
  19033. ((org-with-limited-levels (org-at-heading-p))
  19034. ;; At a headline, move to the previous one, if any, or stay
  19035. ;; here.
  19036. (let ((origin (point)))
  19037. (org-with-limited-levels (org-backward-heading-same-level 1))
  19038. ;; When current headline has no sibling above, move to its
  19039. ;; parent.
  19040. (when (= (point) origin)
  19041. (or (org-with-limited-levels (org-up-heading-safe))
  19042. (progn (goto-char origin)
  19043. (user-error "Cannot move further up"))))))
  19044. (t
  19045. (let* ((elem (org-element-at-point))
  19046. (beg (org-element-property :begin elem)))
  19047. (cond
  19048. ;; Move to beginning of current element if point isn't
  19049. ;; there already.
  19050. ((null beg) (message "No element at point"))
  19051. ((/= (point) beg) (goto-char beg))
  19052. (t (goto-char beg)
  19053. (skip-chars-backward " \r\t\n")
  19054. (unless (bobp)
  19055. (let ((prev (org-element-at-point)))
  19056. (goto-char (org-element-property :begin prev))
  19057. (while (and (setq prev (org-element-property :parent prev))
  19058. (<= (org-element-property :end prev) beg))
  19059. (goto-char (org-element-property :begin prev)))))))))))
  19060. (defun org-up-element ()
  19061. "Move to upper element."
  19062. (interactive)
  19063. (if (org-with-limited-levels (org-at-heading-p))
  19064. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19065. (let* ((elem (org-element-at-point))
  19066. (parent (org-element-property :parent elem)))
  19067. (if (and parent
  19068. (not (memq (org-element-type parent) '(section org-data))))
  19069. (goto-char (org-element-property :begin parent))
  19070. (if (org-with-limited-levels (org-before-first-heading-p))
  19071. (user-error "No surrounding element")
  19072. (org-with-limited-levels (org-back-to-heading)))))))
  19073. (defun org-down-element ()
  19074. "Move to inner element."
  19075. (interactive)
  19076. (let ((element (org-element-at-point)))
  19077. (cond
  19078. ((memq (org-element-type element) '(plain-list table))
  19079. (goto-char (org-element-property :contents-begin element))
  19080. (forward-char))
  19081. ((memq (org-element-type element) org-element-greater-elements)
  19082. ;; If contents are hidden, first disclose them.
  19083. (when (org-invisible-p (line-end-position)) (org-cycle))
  19084. (goto-char (or (org-element-property :contents-begin element)
  19085. (user-error "No content for this element"))))
  19086. (t (user-error "No inner element")))))
  19087. (defun org-drag-element-backward ()
  19088. "Move backward element at point."
  19089. (interactive)
  19090. (let ((elem (or (org-element-at-point)
  19091. (user-error "No element at point"))))
  19092. (if (eq (org-element-type elem) 'headline)
  19093. ;; Preserve point when moving a whole tree, even if point was
  19094. ;; on blank lines below the headline.
  19095. (let ((offset (skip-chars-backward " \t\n")))
  19096. (unwind-protect (org-move-subtree-up)
  19097. (forward-char (- offset))))
  19098. (let ((prev-elem
  19099. (save-excursion
  19100. (goto-char (org-element-property :begin elem))
  19101. (skip-chars-backward " \r\t\n")
  19102. (unless (bobp)
  19103. (let* ((beg (org-element-property :begin elem))
  19104. (prev (org-element-at-point))
  19105. (up prev))
  19106. (while (and (setq up (org-element-property :parent up))
  19107. (<= (org-element-property :end up) beg))
  19108. (setq prev up))
  19109. prev)))))
  19110. ;; Error out if no previous element or previous element is
  19111. ;; a parent of the current one.
  19112. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19113. (user-error "Cannot drag element backward")
  19114. (let ((pos (point)))
  19115. (org-element-swap-A-B prev-elem elem)
  19116. (goto-char (+ (org-element-property :begin prev-elem)
  19117. (- pos (org-element-property :begin elem))))))))))
  19118. (defun org-drag-element-forward ()
  19119. "Move forward element at point."
  19120. (interactive)
  19121. (let* ((pos (point))
  19122. (elem (or (org-element-at-point)
  19123. (user-error "No element at point"))))
  19124. (when (= (point-max) (org-element-property :end elem))
  19125. (user-error "Cannot drag element forward"))
  19126. (goto-char (org-element-property :end elem))
  19127. (let ((next-elem (org-element-at-point)))
  19128. (when (or (org-element-nested-p elem next-elem)
  19129. (and (eq (org-element-type next-elem) 'headline)
  19130. (not (eq (org-element-type elem) 'headline))))
  19131. (goto-char pos)
  19132. (user-error "Cannot drag element forward"))
  19133. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19134. ;; body's length (without final blanks) and by the length of
  19135. ;; blanks between ELEM and NEXT-ELEM.
  19136. (let ((size-next (- (save-excursion
  19137. (goto-char (org-element-property :end next-elem))
  19138. (skip-chars-backward " \r\t\n")
  19139. (forward-line)
  19140. ;; Small correction if buffer doesn't end
  19141. ;; with a newline character.
  19142. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19143. (org-element-property :begin next-elem)))
  19144. (size-blank (- (org-element-property :end elem)
  19145. (save-excursion
  19146. (goto-char (org-element-property :end elem))
  19147. (skip-chars-backward " \r\t\n")
  19148. (forward-line)
  19149. (point)))))
  19150. (org-element-swap-A-B elem next-elem)
  19151. (goto-char (+ pos size-next size-blank))))))
  19152. (defun org-drag-line-forward (arg)
  19153. "Drag the line at point ARG lines forward."
  19154. (interactive "p")
  19155. (dotimes (_ (abs arg))
  19156. (let ((c (current-column)))
  19157. (if (< 0 arg)
  19158. (progn
  19159. (beginning-of-line 2)
  19160. (transpose-lines 1)
  19161. (beginning-of-line 0))
  19162. (transpose-lines 1)
  19163. (beginning-of-line -1))
  19164. (org-move-to-column c))))
  19165. (defun org-drag-line-backward (arg)
  19166. "Drag the line at point ARG lines backward."
  19167. (interactive "p")
  19168. (org-drag-line-forward (- arg)))
  19169. (defun org-mark-element ()
  19170. "Put point at beginning of this element, mark at end.
  19171. Interactively, if this command is repeated or (in Transient Mark
  19172. mode) if the mark is active, it marks the next element after the
  19173. ones already marked."
  19174. (interactive)
  19175. (let (deactivate-mark)
  19176. (if (and (called-interactively-p 'any)
  19177. (or (and (eq last-command this-command) (mark t))
  19178. (and transient-mark-mode mark-active)))
  19179. (set-mark
  19180. (save-excursion
  19181. (goto-char (mark))
  19182. (goto-char (org-element-property :end (org-element-at-point)))
  19183. (point)))
  19184. (let ((element (org-element-at-point)))
  19185. (end-of-line)
  19186. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19187. (goto-char (org-element-property :begin element))))))
  19188. (defun org-narrow-to-element ()
  19189. "Narrow buffer to current element."
  19190. (interactive)
  19191. (let ((elem (org-element-at-point)))
  19192. (cond
  19193. ((eq (car elem) 'headline)
  19194. (narrow-to-region
  19195. (org-element-property :begin elem)
  19196. (org-element-property :end elem)))
  19197. ((memq (car elem) org-element-greater-elements)
  19198. (narrow-to-region
  19199. (org-element-property :contents-begin elem)
  19200. (org-element-property :contents-end elem)))
  19201. (t
  19202. (narrow-to-region
  19203. (org-element-property :begin elem)
  19204. (org-element-property :end elem))))))
  19205. (defun org-transpose-element ()
  19206. "Transpose current and previous elements, keeping blank lines between.
  19207. Point is moved after both elements."
  19208. (interactive)
  19209. (org-skip-whitespace)
  19210. (let ((end (org-element-property :end (org-element-at-point))))
  19211. (org-drag-element-backward)
  19212. (goto-char end)))
  19213. (defun org-unindent-buffer ()
  19214. "Un-indent the visible part of the buffer.
  19215. Relative indentation (between items, inside blocks, etc.) isn't
  19216. modified."
  19217. (interactive)
  19218. (unless (eq major-mode 'org-mode)
  19219. (user-error "Cannot un-indent a buffer not in Org mode"))
  19220. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19221. (unindent-tree
  19222. (lambda (contents)
  19223. (dolist (element (reverse contents))
  19224. (if (memq (org-element-type element) '(headline section))
  19225. (funcall unindent-tree (org-element-contents element))
  19226. (save-excursion
  19227. (save-restriction
  19228. (narrow-to-region
  19229. (org-element-property :begin element)
  19230. (org-element-property :end element))
  19231. (org-do-remove-indentation))))))))
  19232. (funcall unindent-tree (org-element-contents parse-tree))))
  19233. (defun org-make-options-regexp (kwds &optional extra)
  19234. "Make a regular expression for keyword lines.
  19235. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19236. when non-nil, is a regexp matching keywords names."
  19237. (concat "^[ \t]*#\\+\\("
  19238. (regexp-opt kwds)
  19239. (and extra (concat (and kwds "\\|") extra))
  19240. "\\):[ \t]*\\(.*\\)"))
  19241. ;;; Conveniently switch to Info nodes
  19242. (defun org-info-find-node (&optional nodename)
  19243. "Find Info documentation NODENAME or Org documentation according context.
  19244. Started from `gnus-info-find-node'."
  19245. (interactive)
  19246. (Info-goto-node
  19247. (or nodename
  19248. (let ((default-org-info-node "(org) Top"))
  19249. (cond
  19250. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19251. ((eq 'org-mode major-mode)
  19252. (let* ((context (org-element-at-point))
  19253. (element-info-nodes ; compare to `org-element-all-elements'.
  19254. `((babel-call . "(org) Evaluating Code Blocks")
  19255. (center-block . "(org) Paragraphs")
  19256. (clock . ,default-org-info-node)
  19257. (comment . "(org) Comment Lines")
  19258. (comment-block . "(org) Comment Lines")
  19259. (diary-sexp . ,default-org-info-node)
  19260. (drawer . "(org) Drawers")
  19261. (dynamic-block . "(org) Dynamic Blocks")
  19262. (example-block . "(org) Literal Examples")
  19263. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19264. (fixed-width . ,default-org-info-node)
  19265. (footnote-definition . "(org) Creating Footnotes")
  19266. (headline . "(org) Document Structure")
  19267. (horizontal-rule . "(org) Built-in Table Editor")
  19268. (inlinetask . ,default-org-info-node)
  19269. (item . "(org) Plain Lists")
  19270. (keyword . "(org) Per-file keywords")
  19271. (latex-environment . "(org) LaTeX Export")
  19272. (node-property . "(org) Properties and Columns")
  19273. (paragraph . "(org) Paragraphs")
  19274. (plain-list . "(org) Plain Lists")
  19275. (planning . "(org) Deadlines and Scheduling")
  19276. (property-drawer . "(org) Properties and Columns")
  19277. (quote-block . "(org) Paragraphs")
  19278. (section . ,default-org-info-node)
  19279. (special-block . ,default-org-info-node)
  19280. (src-block . "(org) Working with Source Code")
  19281. (table . "(org) Tables")
  19282. (table-row . "(org) Tables")
  19283. (verse-block . "(org) Paragraphs"))))
  19284. (or (cdr (assoc (car context) element-info-nodes))
  19285. default-org-info-node)))
  19286. (t default-org-info-node))))))
  19287. ;;; Finish up
  19288. (add-hook 'org-mode-hook ;remove folds when changing major mode
  19289. (lambda () (add-hook 'change-major-mode-hook
  19290. 'org-fold-show-all 'append 'local)))
  19291. (provide 'org)
  19292. (run-hooks 'org-load-hook)
  19293. ;;; org.el ends here