org.el 815 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490
  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-2021 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. ;; `org-outline-regexp' ought to be a defconst but is let-bound in
  88. ;; some places -- e.g. see the macro `org-with-limited-levels'.
  89. (defvar org-outline-regexp "\\*+ "
  90. "Regexp to match Org headlines.")
  91. (defvar org-outline-regexp-bol "^\\*+ "
  92. "Regexp to match Org headlines.
  93. This is similar to `org-outline-regexp' but additionally makes
  94. sure that we are at the beginning of the line.")
  95. (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  96. "Matches a headline, putting stars and text into groups.
  97. Stars are put in group 1 and the trimmed body in group 2.")
  98. (declare-function calendar-check-holidays "holidays" (date))
  99. (declare-function cdlatex-environment "ext:cdlatex" (environment item))
  100. (declare-function cdlatex-math-symbol "ext:cdlatex")
  101. (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
  102. (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
  103. (declare-function org-add-archive-files "org-archive" (files))
  104. (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
  105. (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
  106. (declare-function org-agenda-redo "org-agenda" (&optional all))
  107. (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
  108. (declare-function org-archive-subtree "org-archive" (&optional find-done))
  109. (declare-function org-archive-subtree-default "org-archive" ())
  110. (declare-function org-archive-to-archive-sibling "org-archive" ())
  111. (declare-function org-attach "org-attach" ())
  112. (declare-function org-attach-dir "org-attach"
  113. (&optional create-if-not-exists-p no-fs-check))
  114. (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
  115. (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
  116. (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
  117. (declare-function org-clock-auto-clockout "org-clock" ())
  118. (declare-function org-clock-cancel "org-clock" ())
  119. (declare-function org-clock-display "org-clock" (&optional arg))
  120. (declare-function org-clock-get-last-clock-out-time "org-clock" ())
  121. (declare-function org-clock-goto "org-clock" (&optional select))
  122. (declare-function org-clock-in "org-clock" (&optional select start-time))
  123. (declare-function org-clock-in-last "org-clock" (&optional arg))
  124. (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
  125. (declare-function org-clock-out-if-current "org-clock" ())
  126. (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
  127. (declare-function org-clock-report "org-clock" (&optional arg))
  128. (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
  129. (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
  130. (declare-function org-clock-timestamps-down "org-clock" (&optional n))
  131. (declare-function org-clock-timestamps-up "org-clock" (&optional n))
  132. (declare-function org-clock-update-time-maybe "org-clock" ())
  133. (declare-function org-clocktable-shift "org-clock" (dir n))
  134. (declare-function org-columns-quit "org-colview" ())
  135. (declare-function org-columns-insert-dblock "org-colview" ())
  136. (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
  137. (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
  138. (declare-function org-element-at-point "org-element" ())
  139. (declare-function org-element-cache-refresh "org-element" (pos))
  140. (declare-function org-element-cache-reset "org-element" (&optional all))
  141. (declare-function org-element-contents "org-element" (element))
  142. (declare-function org-element-context "org-element" (&optional element))
  143. (declare-function org-element-copy "org-element" (datum))
  144. (declare-function org-element-create "org-element" (type &optional props &rest children))
  145. (declare-function org-element-extract-element "org-element" (element))
  146. (declare-function org-element-insert-before "org-element" (element location))
  147. (declare-function org-element-interpret-data "org-element" (data))
  148. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  149. (declare-function org-element-link-parser "org-element" ())
  150. (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
  151. (declare-function org-element-nested-p "org-element" (elem-a elem-b))
  152. (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
  153. (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
  154. (declare-function org-element-property "org-element" (property element))
  155. (declare-function org-element-put-property "org-element" (element property value))
  156. (declare-function org-element-restriction "org-element" (element))
  157. (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
  158. (declare-function org-element-timestamp-parser "org-element" ())
  159. (declare-function org-element-type "org-element" (element))
  160. (declare-function org-export-dispatch "ox" (&optional arg))
  161. (declare-function org-export-get-backend "ox" (name))
  162. (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
  163. (declare-function org-feed-goto-inbox "org-feed" (feed))
  164. (declare-function org-feed-update-all "org-feed" ())
  165. (declare-function org-goto "org-goto" (&optional alternative-interface))
  166. (declare-function org-id-find-id-file "org-id" (id))
  167. (declare-function org-id-get-create "org-id" (&optional force))
  168. (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
  169. (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
  170. (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
  171. (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
  172. (declare-function org-num-mode "org-num" (&optional arg))
  173. (declare-function org-plot/gnuplot "org-plot" (&optional params))
  174. (declare-function org-tags-view "org-agenda" (&optional todo-only match))
  175. (declare-function org-timer "org-timer" (&optional restart no-insert))
  176. (declare-function org-timer-item "org-timer" (&optional arg))
  177. (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
  178. (declare-function org-timer-set-timer "org-timer" (&optional opt))
  179. (declare-function org-timer-start "org-timer" (&optional offset))
  180. (declare-function org-timer-stop "org-timer" ())
  181. (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
  182. (declare-function org-update-radio-target-regexp "ol" ())
  183. (defvar org-element-paragraph-separate)
  184. (defvar org-indent-indentation-per-level)
  185. (defvar org-radio-target-regexp)
  186. (defvar org-target-link-regexp)
  187. (defvar org-target-regexp)
  188. (defvar org-id-overriding-file-name)
  189. ;; load languages based on value of `org-babel-load-languages'
  190. (defvar org-babel-load-languages)
  191. (defvar crm-separator) ; dynamically scoped param
  192. ;;;###autoload
  193. (defun org-babel-do-load-languages (sym value)
  194. "Load the languages defined in `org-babel-load-languages'."
  195. (set-default sym value)
  196. (dolist (pair org-babel-load-languages)
  197. (let ((active (cdr pair)) (lang (symbol-name (car pair))))
  198. (if active
  199. (require (intern (concat "ob-" lang)))
  200. (fmakunbound
  201. (intern (concat "org-babel-execute:" lang)))
  202. (fmakunbound
  203. (intern (concat "org-babel-expand-body:" lang)))))))
  204. ;;;###autoload
  205. (defun org-babel-load-file (file &optional compile)
  206. "Load Emacs Lisp source code blocks in the Org FILE.
  207. This function exports the source code using `org-babel-tangle'
  208. and then loads the resulting file using `load-file'. With
  209. optional prefix argument COMPILE, the tangled Emacs Lisp file is
  210. byte-compiled before it is loaded."
  211. (interactive "fFile to load: \nP")
  212. (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
  213. ;; Tangle only if the Org file is newer than the Elisp file.
  214. (unless (org-file-newer-than-p
  215. tangled-file
  216. (file-attribute-modification-time
  217. (file-attributes (file-truename file))))
  218. (org-babel-tangle-file file
  219. tangled-file
  220. (rx string-start
  221. (or "emacs-lisp" "elisp")
  222. string-end)))
  223. (if compile
  224. (progn
  225. (byte-compile-file tangled-file)
  226. (load tangled-file)
  227. (message "Compiled and loaded %s" tangled-file))
  228. (load-file tangled-file)
  229. (message "Loaded %s" tangled-file))))
  230. (defcustom org-babel-load-languages '((emacs-lisp . t))
  231. "Languages which can be evaluated in Org buffers.
  232. \\<org-mode-map>
  233. This list can be used to load support for any of the languages
  234. below. Each language will depend on a different set of system
  235. executables and/or Emacs modes.
  236. When a language is \"loaded\", code blocks in that language can
  237. be evaluated with `org-babel-execute-src-block', which is bound
  238. by default to \\[org-ctrl-c-ctrl-c].
  239. The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
  240. remove code block evaluation from \\[org-ctrl-c-ctrl-c]. By
  241. default, only Emacs Lisp is loaded, since it has no specific
  242. requirement."
  243. :group 'org-babel
  244. :set 'org-babel-do-load-languages
  245. :version "24.1"
  246. :type '(alist :tag "Babel Languages"
  247. :key-type
  248. (choice
  249. (const :tag "Awk" awk)
  250. (const :tag "C" C)
  251. (const :tag "R" R)
  252. (const :tag "Calc" calc)
  253. (const :tag "Clojure" clojure)
  254. (const :tag "CSS" css)
  255. (const :tag "Ditaa" ditaa)
  256. (const :tag "Dot" dot)
  257. (const :tag "Emacs Lisp" emacs-lisp)
  258. (const :tag "Forth" forth)
  259. (const :tag "Fortran" fortran)
  260. (const :tag "Gnuplot" gnuplot)
  261. (const :tag "Haskell" haskell)
  262. (const :tag "Java" java)
  263. (const :tag "Javascript" js)
  264. (const :tag "LaTeX" latex)
  265. (const :tag "Lilypond" lilypond)
  266. (const :tag "Lisp" lisp)
  267. (const :tag "Makefile" makefile)
  268. (const :tag "Maxima" maxima)
  269. (const :tag "Matlab" matlab)
  270. (const :tag "Ocaml" ocaml)
  271. (const :tag "Octave" octave)
  272. (const :tag "Org" org)
  273. (const :tag "Perl" perl)
  274. (const :tag "Pico Lisp" picolisp)
  275. (const :tag "PlantUML" plantuml)
  276. (const :tag "Python" python)
  277. (const :tag "Ruby" ruby)
  278. (const :tag "Sass" sass)
  279. (const :tag "Scala" scala)
  280. (const :tag "Scheme" scheme)
  281. (const :tag "Screen" screen)
  282. (const :tag "Shell Script" shell)
  283. (const :tag "Sql" sql)
  284. (const :tag "Sqlite" sqlite)
  285. (const :tag "Stan" stan))
  286. :value-type (boolean :tag "Activate" :value t)))
  287. ;;;; Customization variables
  288. (defcustom org-clone-delete-id nil
  289. "Remove ID property of clones of a subtree.
  290. When non-nil, clones of a subtree don't inherit the ID property.
  291. Otherwise they inherit the ID property with a new unique
  292. identifier."
  293. :type 'boolean
  294. :version "24.1"
  295. :group 'org-id)
  296. ;;; Version
  297. (org-check-version)
  298. ;;;###autoload
  299. (defun org-version (&optional here full message)
  300. "Show the Org version.
  301. Interactively, or when MESSAGE is non-nil, show it in echo area.
  302. With prefix argument, or when HERE is non-nil, insert it at point.
  303. In non-interactive uses, a reduced version string is output unless
  304. FULL is given."
  305. (interactive (list current-prefix-arg t (not current-prefix-arg)))
  306. (let ((org-dir (ignore-errors (org-find-library-dir "org")))
  307. (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  308. (load-suffixes (list ".el"))
  309. (org-install-dir
  310. (ignore-errors (org-find-library-dir "org-loaddefs"))))
  311. (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
  312. (org-load-noerror-mustsuffix (concat org-dir "org-version")))
  313. (let* ((load-suffixes save-load-suffixes)
  314. (release (org-release))
  315. (git-version (org-git-version))
  316. (version (format "Org mode version %s (%s @ %s)"
  317. release
  318. git-version
  319. (if org-install-dir
  320. (if (string= org-dir org-install-dir)
  321. org-install-dir
  322. (concat "mixed installation! "
  323. org-install-dir
  324. " and "
  325. org-dir))
  326. "org-loaddefs.el can not be found!")))
  327. (version1 (if full version release)))
  328. (when here (insert version1))
  329. (when message (message "%s" version1))
  330. version1)))
  331. (defconst org-version (org-version))
  332. ;;; Syntax Constants
  333. ;;;; Comments
  334. (defconst org-comment-regexp
  335. (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
  336. "Regular expression for comment lines.")
  337. ;;;; Keyword
  338. (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
  339. "Regular expression for keyword-lines.")
  340. ;;;; Block
  341. (defconst org-block-regexp
  342. "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
  343. "Regular expression for hiding blocks.")
  344. (defconst org-dblock-start-re
  345. "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
  346. "Matches the start line of a dynamic block, with parameters.")
  347. (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
  348. "Matches the end of a dynamic block.")
  349. ;;;; Timestamp
  350. (defconst org-ts--internal-regexp
  351. (rx (seq
  352. (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
  353. (optional " " (*? nonl))))
  354. "Regular expression matching the innards of a time stamp.")
  355. (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
  356. "Regular expression for fast time stamp matching.")
  357. (defconst org-ts-regexp-inactive
  358. (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
  359. "Regular expression for fast inactive time stamp matching.")
  360. (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
  361. "Regular expression for fast time stamp matching.")
  362. (defconst org-ts-regexp0
  363. "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  364. "Regular expression matching time strings for analysis.
  365. This one does not require the space after the date, so it can be used
  366. on a string that terminates immediately after the date.")
  367. (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
  368. "Regular expression matching time strings for analysis.")
  369. (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
  370. "Regular expression matching time stamps, with groups.")
  371. (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
  372. "Regular expression matching time stamps (also [..]), with groups.")
  373. (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
  374. "Regular expression matching a time stamp range.")
  375. (defconst org-tr-regexp-both
  376. (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
  377. "Regular expression matching a time stamp range.")
  378. (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
  379. org-ts-regexp "\\)?")
  380. "Regular expression matching a time stamp or time stamp range.")
  381. (defconst org-tsr-regexp-both
  382. (concat org-ts-regexp-both "\\(--?-?"
  383. org-ts-regexp-both "\\)?")
  384. "Regular expression matching a time stamp or time stamp range.
  385. The time stamps may be either active or inactive.")
  386. (defconst org-repeat-re
  387. "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
  388. \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
  389. "Regular expression for specifying repeated events.
  390. After a match, group 1 contains the repeat expression.")
  391. (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
  392. "Formats for `format-time-string' which are used for time stamps.")
  393. ;;;; Clock and Planning
  394. (defconst org-clock-string "CLOCK:"
  395. "String used as prefix for timestamps clocking work hours on an item.")
  396. (defvar org-closed-string "CLOSED:"
  397. "String used as the prefix for timestamps logging closing a TODO entry.")
  398. (defvar org-deadline-string "DEADLINE:"
  399. "String to mark deadline entries.
  400. \\<org-mode-map>
  401. A deadline is this string, followed by a time stamp. It must be
  402. a word, terminated by a colon. You can insert a schedule keyword
  403. and a timestamp with `\\[org-deadline]'.")
  404. (defvar org-scheduled-string "SCHEDULED:"
  405. "String to mark scheduled TODO entries.
  406. \\<org-mode-map>
  407. A schedule is this string, followed by a time stamp. It must be
  408. a word, terminated by a colon. You can insert a schedule keyword
  409. and a timestamp with `\\[org-schedule]'.")
  410. (defconst org-ds-keyword-length
  411. (+ 2
  412. (apply #'max
  413. (mapcar #'length
  414. (list org-deadline-string org-scheduled-string
  415. org-clock-string org-closed-string))))
  416. "Maximum length of the DEADLINE and SCHEDULED keywords.")
  417. (defconst org-planning-line-re
  418. (concat "^[ \t]*"
  419. (regexp-opt
  420. (list org-closed-string org-deadline-string org-scheduled-string)
  421. t))
  422. "Matches a line with planning info.
  423. Matched keyword is in group 1.")
  424. (defconst org-clock-line-re
  425. (concat "^[ \t]*" org-clock-string)
  426. "Matches a line with clock info.")
  427. (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
  428. "Matches the DEADLINE keyword.")
  429. (defconst org-deadline-time-regexp
  430. (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
  431. "Matches the DEADLINE keyword together with a time stamp.")
  432. (defconst org-deadline-time-hour-regexp
  433. (concat "\\<" org-deadline-string
  434. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  435. "Matches the DEADLINE keyword together with a time-and-hour stamp.")
  436. (defconst org-deadline-line-regexp
  437. (concat "\\<\\(" org-deadline-string "\\).*")
  438. "Matches the DEADLINE keyword and the rest of the line.")
  439. (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
  440. "Matches the SCHEDULED keyword.")
  441. (defconst org-scheduled-time-regexp
  442. (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
  443. "Matches the SCHEDULED keyword together with a time stamp.")
  444. (defconst org-scheduled-time-hour-regexp
  445. (concat "\\<" org-scheduled-string
  446. " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
  447. "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
  448. (defconst org-closed-time-regexp
  449. (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
  450. "Matches the CLOSED keyword together with a time stamp.")
  451. (defconst org-keyword-time-regexp
  452. (concat "\\<"
  453. (regexp-opt
  454. (list org-scheduled-string org-deadline-string org-closed-string
  455. org-clock-string)
  456. t)
  457. " *[[<]\\([^]>]+\\)[]>]")
  458. "Matches any of the 4 keywords, together with the time stamp.")
  459. (defconst org-keyword-time-not-clock-regexp
  460. (concat
  461. "\\<"
  462. (regexp-opt
  463. (list org-scheduled-string org-deadline-string org-closed-string) t)
  464. " *[[<]\\([^]>]+\\)[]>]")
  465. "Matches any of the 3 keywords, together with the time stamp.")
  466. (defconst org-all-time-keywords
  467. (mapcar (lambda (w) (substring w 0 -1))
  468. (list org-scheduled-string org-deadline-string
  469. org-clock-string org-closed-string))
  470. "List of time keywords.")
  471. ;;;; Drawer
  472. (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
  473. "Matches first or last line of a hidden block.
  474. Group 1 contains drawer's name or \"END\".")
  475. (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
  476. "Regular expression matching the first line of a property drawer.")
  477. (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
  478. "Regular expression matching the last line of a property drawer.")
  479. (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
  480. "Regular expression matching the first line of a clock drawer.")
  481. (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
  482. "Regular expression matching the last line of a clock drawer.")
  483. (defconst org-logbook-drawer-re
  484. (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
  485. (*? (0+ nonl) "\n")
  486. (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
  487. "Matches an entire LOGBOOK drawer.")
  488. (defconst org-property-drawer-re
  489. (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
  490. "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
  491. "[ \t]*:END:[ \t]*$")
  492. "Matches an entire property drawer.")
  493. (defconst org-clock-drawer-re
  494. (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
  495. org-clock-drawer-end-re "\\)\n?")
  496. "Matches an entire clock drawer.")
  497. ;;;; Headline
  498. (defconst org-heading-keyword-regexp-format
  499. "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
  500. "Printf format for a regexp matching a headline with some keyword.
  501. This regexp will match the headline of any node which has the
  502. exact keyword that is put into the format. The keyword isn't in
  503. any group by default, but the stars and the body are.")
  504. (defconst org-heading-keyword-maybe-regexp-format
  505. "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
  506. "Printf format for a regexp matching a headline, possibly with some keyword.
  507. This regexp can match any headline with the specified keyword, or
  508. without a keyword. The keyword isn't in any group by default,
  509. but the stars and the body are.")
  510. (defconst org-archive-tag "ARCHIVE"
  511. "The tag that marks a subtree as archived.
  512. An archived subtree does not open during visibility cycling, and does
  513. not contribute to the agenda listings.")
  514. (defconst org-tag-re "[[:alnum:]_@#%]+"
  515. "Regexp matching a single tag.")
  516. (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  517. "Regexp matching the tag group at the end of a line, with leading spaces.
  518. Tags are stored in match group 1. Match group 2 stores the tags
  519. without the enclosing colons.")
  520. (defconst org-tag-line-re
  521. "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
  522. "Regexp matching tags in a headline.
  523. Tags are stored in match group 1. Match group 2 stores the tags
  524. without the enclosing colons.")
  525. (eval-and-compile
  526. (defconst org-comment-string "COMMENT"
  527. "Entries starting with this keyword will never be exported.
  528. \\<org-mode-map>
  529. An entry can be toggled between COMMENT and normal with
  530. `\\[org-toggle-comment]'."))
  531. ;;;; LaTeX Environments and Fragments
  532. (defconst org-latex-regexps
  533. '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
  534. ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
  535. ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
  536. ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  537. ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
  538. ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
  539. ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
  540. ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
  541. "Regular expressions for matching embedded LaTeX.")
  542. ;;;; Node Property
  543. (defconst org-effort-property "Effort"
  544. "The property that is being used to keep track of effort estimates.
  545. Effort estimates given in this property need to be in the format
  546. defined in org-duration.el.")
  547. ;;; The custom variables
  548. (defgroup org nil
  549. "Outline-based notes management and organizer."
  550. :tag "Org"
  551. :group 'outlines
  552. :group 'calendar)
  553. (defcustom org-mode-hook nil
  554. "Mode hook for Org mode, run after the mode was turned on."
  555. :group 'org
  556. :type 'hook)
  557. (defcustom org-load-hook nil
  558. "Hook that is run after org.el has been loaded."
  559. :group 'org
  560. :type 'hook)
  561. (make-obsolete-variable
  562. 'org-load-hook
  563. "use `with-eval-after-load' instead." "9.5")
  564. (defcustom org-log-buffer-setup-hook nil
  565. "Hook that is run after an Org log buffer is created."
  566. :group 'org
  567. :version "24.1"
  568. :type 'hook)
  569. (defvar org-modules) ; defined below
  570. (defvar org-modules-loaded nil
  571. "Have the modules been loaded already?")
  572. ;;;###autoload
  573. (defun org-load-modules-maybe (&optional force)
  574. "Load all extensions listed in `org-modules'."
  575. (when (or force (not org-modules-loaded))
  576. (dolist (ext org-modules)
  577. (condition-case nil (require ext)
  578. (error (message "Problems while trying to load feature `%s'" ext))))
  579. (setq org-modules-loaded t)))
  580. (defun org-set-modules (var value)
  581. "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
  582. (set var value)
  583. (when (featurep 'org)
  584. (org-load-modules-maybe 'force)
  585. (org-element-cache-reset 'all)))
  586. (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)
  587. "Modules that should always be loaded together with org.el.
  588. If a description starts with <C>, the file is not part of Emacs and Org mode,
  589. so loading it will require that you have properly installed org-contrib
  590. package from NonGNU Emacs Lisp Package Archive
  591. http://elpa.nongnu.org/nongnu/org-contrib.html
  592. You can also use this system to load external packages (i.e. neither Org
  593. core modules, nor org-contrib modules). Just add symbols
  594. to the end of the list. If the package is called org-xyz.el, then you need
  595. to add the symbol `xyz', and the package must have a call to:
  596. (provide \\='org-xyz)
  597. For export specific modules, see also `org-export-backends'."
  598. :group 'org
  599. :set 'org-set-modules
  600. :package-version '(Org . "9.5")
  601. :type
  602. '(set :greedy t
  603. (const :tag " bbdb: Links to BBDB entries" ol-bbdb)
  604. (const :tag " bibtex: Links to BibTeX entries" ol-bibtex)
  605. (const :tag " crypt: Encryption of subtrees" org-crypt)
  606. (const :tag " ctags: Access to Emacs tags with links" org-ctags)
  607. (const :tag " docview: Links to Docview buffers" ol-docview)
  608. (const :tag " doi: Links to DOI references" ol-doi)
  609. (const :tag " eww: Store link to URL of Eww" ol-eww)
  610. (const :tag " gnus: Links to GNUS folders/messages" ol-gnus)
  611. (const :tag " habit: Track your consistency with habits" org-habit)
  612. (const :tag " id: Global IDs for identifying entries" org-id)
  613. (const :tag " info: Links to Info nodes" ol-info)
  614. (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
  615. (const :tag " irc: Links to IRC/ERC chat sessions" ol-irc)
  616. (const :tag " mhe: Links to MHE folders/messages" ol-mhe)
  617. (const :tag " mouse: Additional mouse support" org-mouse)
  618. (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
  619. (const :tag " rmail: Links to RMAIL folders/messages" ol-rmail)
  620. (const :tag " tempo: Fast completion for structures" org-tempo)
  621. (const :tag " w3m: Special cut/paste from w3m to Org mode." ol-w3m)
  622. (const :tag " eshell: Links to working directories in Eshell" ol-eshell)
  623. (const :tag "C annotate-file: Annotate a file with Org syntax" org-annotate-file)
  624. (const :tag "C bookmark: Links to bookmarks" ol-bookmark)
  625. (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
  626. (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
  627. (const :tag "C collector: Collect properties into tables" org-collector)
  628. (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
  629. (const :tag "C elisp-symbol: Links to emacs-lisp symbols" ol-elisp-symbol)
  630. (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
  631. (const :tag "C eval: Include command output as text" org-eval)
  632. (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
  633. (const :tag "C git-link: Links to specific file version" ol-git-link)
  634. (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
  635. (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
  636. (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
  637. (const :tag "C mac-iCal: Imports events from iCal.app to the Emacs diary" org-mac-iCal)
  638. (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
  639. (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
  640. (const :tag "C man: Links to man pages in Org mode" ol-man)
  641. (const :tag "C mew: Links to Mew folders/messages" ol-mew)
  642. (const :tag "C notify: Notifications for Org mode" org-notify)
  643. (const :tag "C notmuch: Provide Org links to notmuch searches or messages" ol-notmuch)
  644. (const :tag "C panel: Simple routines for us with bad memory" org-panel)
  645. (const :tag "C registry: A registry for Org links" org-registry)
  646. (const :tag "C screen: Visit screen sessions through links" org-screen)
  647. (const :tag "C screenshot: Take and manage screenshots in Org files" org-screenshot)
  648. (const :tag "C secretary: Team management with Org" org-secretary)
  649. (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
  650. (const :tag "C toc: Table of contents for Org buffer" org-toc)
  651. (const :tag "C track: Keep up with Org mode development" org-track)
  652. (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
  653. (const :tag "C vm: Links to VM folders/messages" ol-vm)
  654. (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
  655. (const :tag "C wl: Links to Wanderlust folders/messages" ol-wl)
  656. (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
  657. (defvar org-export-registered-backends) ; From ox.el.
  658. (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
  659. (declare-function org-export-backend-name "ox" (backend) t)
  660. (defcustom org-export-backends '(ascii html icalendar latex odt)
  661. "List of export back-ends that should be always available.
  662. If a description starts with <C>, the file is not part of Emacs and Org mode,
  663. so loading it will require that you have properly installed org-contrib
  664. package from NonGNU Emacs Lisp Package Archive
  665. http://elpa.nongnu.org/nongnu/org-contrib.html
  666. Unlike to `org-modules', libraries in this list will not be
  667. loaded along with Org, but only once the export framework is
  668. needed.
  669. This variable needs to be set before org.el is loaded. If you
  670. need to make a change while Emacs is running, use the customize
  671. interface or run the following code, where VAL stands for the new
  672. value of the variable, after updating it:
  673. (progn
  674. (setq org-export-registered-backends
  675. (cl-remove-if-not
  676. (lambda (backend)
  677. (let ((name (org-export-backend-name backend)))
  678. (or (memq name val)
  679. (catch \\='parentp
  680. (dolist (b val)
  681. (and (org-export-derived-backend-p b name)
  682. (throw \\='parentp t)))))))
  683. org-export-registered-backends))
  684. (let ((new-list (mapcar #\\='org-export-backend-name
  685. org-export-registered-backends)))
  686. (dolist (backend val)
  687. (cond
  688. ((not (load (format \"ox-%s\" backend) t t))
  689. (message \"Problems while trying to load export back-end \\=`%s\\='\"
  690. backend))
  691. ((not (memq backend new-list)) (push backend new-list))))
  692. (set-default \\='org-export-backends new-list)))
  693. Adding a back-end to this list will also pull the back-end it
  694. depends on, if any."
  695. :group 'org
  696. :group 'org-export
  697. :version "26.1"
  698. :package-version '(Org . "9.0")
  699. :initialize 'custom-initialize-set
  700. :set (lambda (var val)
  701. (if (not (featurep 'ox)) (set-default var val)
  702. ;; Any back-end not required anymore (not present in VAL and not
  703. ;; a parent of any back-end in the new value) is removed from the
  704. ;; list of registered back-ends.
  705. (setq org-export-registered-backends
  706. (cl-remove-if-not
  707. (lambda (backend)
  708. (let ((name (org-export-backend-name backend)))
  709. (or (memq name val)
  710. (catch 'parentp
  711. (dolist (b val)
  712. (and (org-export-derived-backend-p b name)
  713. (throw 'parentp t)))))))
  714. org-export-registered-backends))
  715. ;; Now build NEW-LIST of both new back-ends and required
  716. ;; parents.
  717. (let ((new-list (mapcar #'org-export-backend-name
  718. org-export-registered-backends)))
  719. (dolist (backend val)
  720. (cond
  721. ((not (load (format "ox-%s" backend) t t))
  722. (message "Problems while trying to load export back-end `%s'"
  723. backend))
  724. ((not (memq backend new-list)) (push backend new-list))))
  725. ;; Set VAR to that list with fixed dependencies.
  726. (set-default var new-list))))
  727. :type '(set :greedy t
  728. (const :tag " ascii Export buffer to ASCII format" ascii)
  729. (const :tag " beamer Export buffer to Beamer presentation" beamer)
  730. (const :tag " html Export buffer to HTML format" html)
  731. (const :tag " icalendar Export buffer to iCalendar format" icalendar)
  732. (const :tag " latex Export buffer to LaTeX format" latex)
  733. (const :tag " man Export buffer to MAN format" man)
  734. (const :tag " md Export buffer to Markdown format" md)
  735. (const :tag " odt Export buffer to ODT format" odt)
  736. (const :tag " org Export buffer to Org format" org)
  737. (const :tag " texinfo Export buffer to Texinfo format" texinfo)
  738. (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
  739. (const :tag "C deck Export buffer to deck.js presentations" deck)
  740. (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
  741. (const :tag "C groff Export buffer to Groff format" groff)
  742. (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
  743. (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
  744. (const :tag "C s5 Export buffer to s5 presentations" s5)
  745. (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
  746. (eval-after-load 'ox
  747. '(dolist (backend org-export-backends)
  748. (condition-case nil (require (intern (format "ox-%s" backend)))
  749. (error (message "Problems while trying to load export back-end `%s'"
  750. backend)))))
  751. (defcustom org-support-shift-select nil
  752. "Non-nil means make shift-cursor commands select text when possible.
  753. \\<org-mode-map>
  754. In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
  755. start selecting a region, or enlarge regions started in this way.
  756. In Org mode, in special contexts, these same keys are used for
  757. other purposes, important enough to compete with shift selection.
  758. Org tries to balance these needs by supporting `shift-select-mode'
  759. outside these special contexts, under control of this variable.
  760. The default of this variable is nil, to avoid confusing behavior. Shifted
  761. cursor keys will then execute Org commands in the following contexts:
  762. - on a headline, changing TODO state (left/right) and priority (up/down)
  763. - on a time stamp, changing the time
  764. - in a plain list item, changing the bullet type
  765. - in a property definition line, switching between allowed values
  766. - in the BEGIN line of a clock table (changing the time block).
  767. - in a table, moving the cell in the specified direction.
  768. Outside these contexts, the commands will throw an error.
  769. When this variable is t and the cursor is not in a special
  770. context, Org mode will support shift-selection for making and
  771. enlarging regions. To make this more effective, the bullet
  772. cycling will no longer happen anywhere in an item line, but only
  773. if the cursor is exactly on the bullet.
  774. If you set this variable to the symbol `always', then the keys
  775. will not be special in headlines, property lines, item lines, and
  776. table cells, to make shift selection work there as well. If this is
  777. what you want, you can use the following alternative commands:
  778. `\\[org-todo]' and `\\[org-priority]' \
  779. to change TODO state and priority,
  780. `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
  781. can be used to switch TODO sets,
  782. `\\[org-ctrl-c-minus]' to cycle item bullet types,
  783. and properties can be edited by hand or in column view.
  784. However, when the cursor is on a timestamp, shift-cursor commands
  785. will still edit the time stamp - this is just too good to give up."
  786. :group 'org
  787. :type '(choice
  788. (const :tag "Never" nil)
  789. (const :tag "When outside special context" t)
  790. (const :tag "Everywhere except timestamps" always)))
  791. (defcustom org-loop-over-headlines-in-active-region t
  792. "Shall some commands act upon headlines in the active region?
  793. When set to t, some commands will be performed in all headlines
  794. within the active region.
  795. When set to `start-level', some commands will be performed in all
  796. headlines within the active region, provided that these headlines
  797. are of the same level than the first one.
  798. When set to a string, those commands will be performed on the
  799. matching headlines within the active region. Such string must be
  800. a tags/property/todo match as it is used in the agenda tags view.
  801. The list of commands is: `org-schedule', `org-deadline',
  802. `org-todo', `org-set-tags-command', `org-archive-subtree',
  803. `org-archive-set-tag', `org-toggle-archive-tag' and
  804. `org-archive-to-archive-sibling'. The archiving commands skip
  805. already archived entries.
  806. See `org-agenda-loop-over-headlines-in-active-region' for the
  807. equivalent option for agenda views."
  808. :type '(choice (const :tag "Don't loop" nil)
  809. (const :tag "All headlines in active region" t)
  810. (const :tag "In active region, headlines at the same level than the first one" start-level)
  811. (string :tag "Tags/Property/Todo matcher"))
  812. :package-version '(Org . "9.4")
  813. :group 'org-todo
  814. :group 'org-archive)
  815. (defcustom org-startup-folded 'showeverything
  816. "Non-nil means entering Org mode will switch to OVERVIEW.
  817. This can also be configured on a per-file basis by adding one of
  818. the following lines anywhere in the buffer:
  819. #+STARTUP: fold (or `overview', this is equivalent)
  820. #+STARTUP: nofold (or `showall', this is equivalent)
  821. #+STARTUP: content
  822. #+STARTUP: show<n>levels (<n> = 2..5)
  823. #+STARTUP: showeverything
  824. Set `org-agenda-inhibit-startup' to a non-nil value if you want
  825. to ignore this option when Org opens agenda files for the first
  826. time."
  827. :group 'org-startup
  828. :package-version '(Org . "9.4")
  829. :type '(choice
  830. (const :tag "nofold: show all" nil)
  831. (const :tag "fold: overview" t)
  832. (const :tag "fold: show two levels" show2levels)
  833. (const :tag "fold: show three levels" show3levels)
  834. (const :tag "fold: show four levels" show4evels)
  835. (const :tag "fold: show five levels" show5levels)
  836. (const :tag "content: all headlines" content)
  837. (const :tag "show everything, even drawers" showeverything)))
  838. (defcustom org-startup-truncated t
  839. "Non-nil means entering Org mode will set `truncate-lines'.
  840. This is useful since some lines containing links can be very long and
  841. uninteresting. Also tables look terrible when wrapped.
  842. The variable `org-startup-truncated' allows to configure
  843. truncation for Org mode different to the other modes that use the
  844. variable `truncate-lines' and as a shortcut instead of putting
  845. the variable `truncate-lines' into the `org-mode-hook'. If one
  846. wants to configure truncation for Org mode not statically but
  847. dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
  848. the variable `truncate-lines' has to be used because in such a
  849. case it is too late to set the variable `org-startup-truncated'."
  850. :group 'org-startup
  851. :type 'boolean)
  852. (defcustom org-startup-indented nil
  853. "Non-nil means turn on `org-indent-mode' on startup.
  854. This can also be configured on a per-file basis by adding one of
  855. the following lines anywhere in the buffer:
  856. #+STARTUP: indent
  857. #+STARTUP: noindent"
  858. :group 'org-structure
  859. :type '(choice
  860. (const :tag "Not" nil)
  861. (const :tag "Globally (slow on startup in large files)" t)))
  862. (defcustom org-startup-numerated nil
  863. "Non-nil means turn on `org-num-mode' on startup.
  864. This can also be configured on a per-file basis by adding one of
  865. the following lines anywhere in the buffer:
  866. #+STARTUP: num
  867. #+STARTUP: nonum"
  868. :group 'org-structure
  869. :package-version '(Org . "9.4")
  870. :type '(choice
  871. (const :tag "Not" nil)
  872. (const :tag "Globally" t)))
  873. (defcustom org-use-sub-superscripts t
  874. "Non-nil means interpret \"_\" and \"^\" for display.
  875. If you want to control how Org exports those characters, see
  876. `org-export-with-sub-superscripts'.
  877. When this option is turned on, you can use TeX-like syntax for
  878. sub- and superscripts within the buffer. Several characters after
  879. \"_\" or \"^\" will be considered as a single item - so grouping
  880. with {} is normally not needed. For example, the following things
  881. will be parsed as single sub- or superscripts:
  882. 10^24 or 10^tau several digits will be considered 1 item.
  883. 10^-12 or 10^-tau a leading sign with digits or a word
  884. x^2-y^3 will be read as x^2 - y^3, because items are
  885. terminated by almost any nonword/nondigit char.
  886. x_{i^2} or x^(2-i) braces or parenthesis do grouping.
  887. Still, ambiguity is possible. So when in doubt, use {} to enclose
  888. the sub/superscript. If you set this variable to the symbol `{}',
  889. the braces are *required* in order to trigger interpretations as
  890. sub/superscript. This can be helpful in documents that need \"_\"
  891. frequently in plain text."
  892. :group 'org-startup
  893. :version "24.4"
  894. :package-version '(Org . "8.0")
  895. :type '(choice
  896. (const :tag "Always interpret" t)
  897. (const :tag "Only with braces" {})
  898. (const :tag "Never interpret" nil)))
  899. (defcustom org-startup-with-beamer-mode nil
  900. "Non-nil means turn on `org-beamer-mode' on startup.
  901. This can also be configured on a per-file basis by adding one of
  902. the following lines anywhere in the buffer:
  903. #+STARTUP: beamer"
  904. :group 'org-startup
  905. :version "24.1"
  906. :type 'boolean)
  907. (defcustom org-startup-align-all-tables nil
  908. "Non-nil means align all tables when visiting a file.
  909. This can also be configured on a per-file basis by adding one of
  910. the following lines anywhere in the buffer:
  911. #+STARTUP: align
  912. #+STARTUP: noalign"
  913. :group 'org-startup
  914. :type 'boolean)
  915. (defcustom org-startup-shrink-all-tables nil
  916. "Non-nil means shrink all table columns with a width cookie.
  917. This can also be configured on a per-file basis by adding one of
  918. the following lines anywhere in the buffer:
  919. #+STARTUP: shrink"
  920. :group 'org-startup
  921. :type 'boolean
  922. :version "27.1"
  923. :package-version '(Org . "9.2")
  924. :safe #'booleanp)
  925. (defcustom org-startup-with-inline-images nil
  926. "Non-nil means show inline images when loading a new Org file.
  927. This can also be configured on a per-file basis by adding one of
  928. the following lines anywhere in the buffer:
  929. #+STARTUP: inlineimages
  930. #+STARTUP: noinlineimages"
  931. :group 'org-startup
  932. :version "24.1"
  933. :type 'boolean)
  934. (defcustom org-startup-with-latex-preview nil
  935. "Non-nil means preview LaTeX fragments when loading a new Org file.
  936. This can also be configured on a per-file basis by adding one of
  937. the following lines anywhere in the buffer:
  938. #+STARTUP: latexpreview
  939. #+STARTUP: nolatexpreview"
  940. :group 'org-startup
  941. :version "24.4"
  942. :package-version '(Org . "8.0")
  943. :type 'boolean)
  944. (defcustom org-insert-mode-line-in-empty-file nil
  945. "Non-nil means insert the first line setting Org mode in empty files.
  946. When the function `org-mode' is called interactively in an empty file, this
  947. normally means that the file name does not automatically trigger Org mode.
  948. To ensure that the file will always be in Org mode in the future, a
  949. line enforcing Org mode will be inserted into the buffer, if this option
  950. has been set."
  951. :group 'org-startup
  952. :type 'boolean)
  953. (defcustom org-ellipsis nil
  954. "The ellipsis to use in the Org mode outline.
  955. When nil, just use the standard three dots. When a non-empty string,
  956. use that string instead.
  957. The change affects only Org mode (which will then use its own display table).
  958. Changing this requires executing `\\[org-mode]' in a buffer to become
  959. effective. It cannot be set as a local variable."
  960. :group 'org-startup
  961. :type '(choice (const :tag "Default" nil)
  962. (string :tag "String" :value "...#")))
  963. (defvar org-display-table nil
  964. "The display table for Org mode, in case `org-ellipsis' is non-nil.")
  965. (defcustom org-directory "~/org"
  966. "Directory with Org files.
  967. This is just a default location to look for Org files. There is no need
  968. at all to put your files into this directory. It is used in the
  969. following situations:
  970. 1. When a capture template specifies a target file that is not an
  971. absolute path. The path will then be interpreted relative to
  972. `org-directory'
  973. 2. When the value of variable `org-agenda-files' is a single file, any
  974. relative paths in this file will be taken as relative to
  975. `org-directory'."
  976. :group 'org-refile
  977. :group 'org-capture
  978. :type 'directory)
  979. (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
  980. "Default target for storing notes.
  981. Used as a fall back file for org-capture.el, for templates that
  982. do not specify a target file."
  983. :group 'org-refile
  984. :group 'org-capture
  985. :type 'file)
  986. (defcustom org-reverse-note-order nil
  987. "Non-nil means store new notes at the beginning of a file or entry.
  988. When nil, new notes will be filed to the end of a file or entry.
  989. This can also be a list with cons cells of regular expressions that
  990. are matched against file names, and values."
  991. :group 'org-capture
  992. :group 'org-refile
  993. :type '(choice
  994. (const :tag "Reverse always" t)
  995. (const :tag "Reverse never" nil)
  996. (repeat :tag "By file name regexp"
  997. (cons regexp boolean))))
  998. (defgroup org-keywords nil
  999. "Keywords in Org mode."
  1000. :tag "Org Keywords"
  1001. :group 'org)
  1002. (defcustom org-closed-keep-when-no-todo nil
  1003. "Remove CLOSED: time-stamp when switching back to a non-todo state?"
  1004. :group 'org-todo
  1005. :group 'org-keywords
  1006. :version "24.4"
  1007. :package-version '(Org . "8.0")
  1008. :type 'boolean)
  1009. (defgroup org-structure nil
  1010. "Options concerning the general structure of Org files."
  1011. :tag "Org Structure"
  1012. :group 'org)
  1013. (defgroup org-reveal-location nil
  1014. "Options about how to make context of a location visible."
  1015. :tag "Org Reveal Location"
  1016. :group 'org-structure)
  1017. (defcustom org-show-context-detail '((agenda . local)
  1018. (bookmark-jump . lineage)
  1019. (isearch . lineage)
  1020. (default . ancestors))
  1021. "Alist between context and visibility span when revealing a location.
  1022. \\<org-mode-map>Some actions may move point into invisible
  1023. locations. As a consequence, Org always exposes a neighborhood
  1024. around point. How much is shown depends on the initial action,
  1025. or context. Valid contexts are
  1026. agenda when exposing an entry from the agenda
  1027. org-goto when using the command `org-goto' (`\\[org-goto]')
  1028. occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
  1029. tags-tree when constructing a sparse tree based on tags matches
  1030. link-search when exposing search matches associated with a link
  1031. mark-goto when exposing the jump goal of a mark
  1032. bookmark-jump when exposing a bookmark location
  1033. isearch when exiting from an incremental search
  1034. default default for all contexts not set explicitly
  1035. Allowed visibility spans are
  1036. minimal show current headline; if point is not on headline,
  1037. also show entry
  1038. local show current headline, entry and next headline
  1039. ancestors show current headline and its direct ancestors; if
  1040. point is not on headline, also show entry
  1041. ancestors-full show current subtree and its direct ancestors
  1042. lineage show current headline, its direct ancestors and all
  1043. their children; if point is not on headline, also show
  1044. entry and first child
  1045. tree show current headline, its direct ancestors and all
  1046. their children; if point is not on headline, also show
  1047. entry and all children
  1048. canonical show current headline, its direct ancestors along with
  1049. their entries and children; if point is not located on
  1050. the headline, also show current entry and all children
  1051. As special cases, a nil or t value means show all contexts in
  1052. `minimal' or `canonical' view, respectively.
  1053. Some views can make displayed information very compact, but also
  1054. make it harder to edit the location of the match. In such
  1055. a case, use the command `org-reveal' (`\\[org-reveal]') to show
  1056. more context."
  1057. :group 'org-reveal-location
  1058. :version "26.1"
  1059. :package-version '(Org . "9.0")
  1060. :type '(choice
  1061. (const :tag "Canonical" t)
  1062. (const :tag "Minimal" nil)
  1063. (repeat :greedy t :tag "Individual contexts"
  1064. (cons
  1065. (choice :tag "Context"
  1066. (const agenda)
  1067. (const org-goto)
  1068. (const occur-tree)
  1069. (const tags-tree)
  1070. (const link-search)
  1071. (const mark-goto)
  1072. (const bookmark-jump)
  1073. (const isearch)
  1074. (const default))
  1075. (choice :tag "Detail level"
  1076. (const minimal)
  1077. (const local)
  1078. (const ancestors)
  1079. (const ancestors-full)
  1080. (const lineage)
  1081. (const tree)
  1082. (const canonical))))))
  1083. (defcustom org-indirect-buffer-display 'other-window
  1084. "How should indirect tree buffers be displayed?
  1085. This applies to indirect buffers created with the commands
  1086. `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
  1087. Valid values are:
  1088. current-window Display in the current window
  1089. other-window Just display in another window.
  1090. dedicated-frame Create one new frame, and re-use it each time.
  1091. new-frame Make a new frame each time. Note that in this case
  1092. previously-made indirect buffers are kept, and you need to
  1093. kill these buffers yourself."
  1094. :group 'org-structure
  1095. :group 'org-agenda-windows
  1096. :type '(choice
  1097. (const :tag "In current window" current-window)
  1098. (const :tag "In current frame, other window" other-window)
  1099. (const :tag "Each time a new frame" new-frame)
  1100. (const :tag "One dedicated frame" dedicated-frame)))
  1101. (defconst org-file-apps-gnu
  1102. '((remote . emacs)
  1103. (system . mailcap)
  1104. (t . mailcap))
  1105. "Default file applications on a UNIX or GNU/Linux system.
  1106. See `org-file-apps'.")
  1107. (defconst org-file-apps-macos
  1108. '((remote . emacs)
  1109. (system . "open %s")
  1110. ("ps.gz" . "gv %s")
  1111. ("eps.gz" . "gv %s")
  1112. ("dvi" . "xdvi %s")
  1113. ("fig" . "xfig %s")
  1114. (t . "open %s"))
  1115. "Default file applications on a macOS system.
  1116. The system \"open\" is known as a default, but we use X11 applications
  1117. for some files for which the OS does not have a good default.
  1118. See `org-file-apps'.")
  1119. (defconst org-file-apps-windowsnt
  1120. (list '(remote . emacs)
  1121. (cons 'system (lambda (file _path)
  1122. (with-no-warnings (w32-shell-execute "open" file))))
  1123. (cons t (lambda (file _path)
  1124. (with-no-warnings (w32-shell-execute "open" file)))))
  1125. "Default file applications on a Windows NT system.
  1126. The system \"open\" is used for most files.
  1127. See `org-file-apps'.")
  1128. (defcustom org-file-apps
  1129. '((auto-mode . emacs)
  1130. (directory . emacs)
  1131. ("\\.mm\\'" . default)
  1132. ("\\.x?html?\\'" . default)
  1133. ("\\.pdf\\'" . default))
  1134. "Applications for opening `file:path' items in a document.
  1135. \\<org-mode-map>
  1136. Org mode uses system defaults for different file types, but you
  1137. can use this variable to set the application for a given file
  1138. extension. The entries in this list are cons cells where the car
  1139. identifies files and the cdr the corresponding command.
  1140. Possible values for the file identifier are:
  1141. \"string\" A string as a file identifier can be interpreted in different
  1142. ways, depending on its contents:
  1143. - Alphanumeric characters only:
  1144. Match links with this file extension.
  1145. Example: (\"pdf\" . \"evince %s\")
  1146. to open PDFs with evince.
  1147. - Regular expression: Match links where the
  1148. filename matches the regexp. If you want to
  1149. use groups here, use shy groups.
  1150. Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
  1151. (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
  1152. to open *.html and *.xhtml with firefox.
  1153. - Regular expression which contains (non-shy) groups:
  1154. Match links where the whole link, including \"::\", and
  1155. anything after that, matches the regexp.
  1156. In a custom command string, %1, %2, etc. are replaced with
  1157. the parts of the link that were matched by the groups.
  1158. For backwards compatibility, if a command string is given
  1159. that does not use any of the group matches, this case is
  1160. handled identically to the second one (i.e. match against
  1161. file name only).
  1162. In a custom function, you can access the group matches with
  1163. (match-string n link).
  1164. Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
  1165. \"evince -p %1 %s\")
  1166. to open [[file:document.pdf::5]] with evince at page 5.
  1167. `directory' Matches a directory
  1168. `remote' Matches a remote file, accessible through tramp or efs.
  1169. Remote files most likely should be visited through Emacs
  1170. because external applications cannot handle such paths.
  1171. `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
  1172. so all files Emacs knows how to handle. Using this with
  1173. command `emacs' will open most files in Emacs. Beware that this
  1174. will also open html files inside Emacs, unless you add
  1175. (\"html\" . default) to the list as well.
  1176. `system' The system command to open files, like `open' on Windows
  1177. and macOS, and mailcap under GNU/Linux. This is the command
  1178. that will be selected if you call `org-open-at-point' with a
  1179. double prefix argument (`\\[universal-argument] \
  1180. \\[universal-argument] \\[org-open-at-point]').
  1181. t Default for files not matched by any of the other options.
  1182. Possible values for the command are:
  1183. `emacs' The file will be visited by the current Emacs process.
  1184. `default' Use the default application for this file type, which is the
  1185. association for t in the list, most likely in the system-specific
  1186. part. This can be used to overrule an unwanted setting in the
  1187. system-specific variable.
  1188. `system' Use the system command for opening files, like \"open\".
  1189. This command is specified by the entry whose car is `system'.
  1190. Most likely, the system-specific version of this variable
  1191. does define this command, but you can overrule/replace it
  1192. here.
  1193. `mailcap' Use command specified in the mailcaps.
  1194. string A command to be executed by a shell; %s will be replaced
  1195. by the path to the file.
  1196. function A Lisp function, which will be called with two arguments:
  1197. the file path and the original link string, without the
  1198. \"file:\" prefix.
  1199. For more examples, see the system specific constants
  1200. `org-file-apps-macos'
  1201. `org-file-apps-windowsnt'
  1202. `org-file-apps-gnu'."
  1203. :group 'org
  1204. :package-version '(Org . "9.4")
  1205. :type '(repeat
  1206. (cons (choice :value ""
  1207. (string :tag "Extension")
  1208. (const :tag "System command to open files" system)
  1209. (const :tag "Default for unrecognized files" t)
  1210. (const :tag "Remote file" remote)
  1211. (const :tag "Links to a directory" directory)
  1212. (const :tag "Any files that have Emacs modes"
  1213. auto-mode))
  1214. (choice :value ""
  1215. (const :tag "Visit with Emacs" emacs)
  1216. (const :tag "Use default" default)
  1217. (const :tag "Use the system command" system)
  1218. (string :tag "Command")
  1219. (function :tag "Function")))))
  1220. (defcustom org-open-non-existing-files nil
  1221. "Non-nil means `org-open-file' opens non-existing files.
  1222. When nil, an error is thrown.
  1223. This variable applies only to external applications because they
  1224. might choke on non-existing files. If the link is to a file that
  1225. will be opened in Emacs, the variable is ignored."
  1226. :group 'org
  1227. :type 'boolean
  1228. :safe #'booleanp)
  1229. (defcustom org-open-directory-means-index-dot-org nil
  1230. "When non-nil a link to a directory really means to \"index.org\".
  1231. When nil, following a directory link runs Dired or opens
  1232. a finder/explorer window on that directory."
  1233. :group 'org
  1234. :type 'boolean
  1235. :safe #'booleanp)
  1236. (defcustom org-bookmark-names-plist
  1237. '(:last-capture "org-capture-last-stored"
  1238. :last-refile "org-refile-last-stored"
  1239. :last-capture-marker "org-capture-last-stored-marker")
  1240. "Names for bookmarks automatically set by some Org commands.
  1241. This can provide strings as names for a number of bookmarks Org sets
  1242. automatically. The following keys are currently implemented:
  1243. :last-capture
  1244. :last-capture-marker
  1245. :last-refile
  1246. When a key does not show up in the property list, the corresponding bookmark
  1247. is not set."
  1248. :group 'org-structure
  1249. :type 'plist)
  1250. (defgroup org-cycle nil
  1251. "Options concerning visibility cycling in Org mode."
  1252. :tag "Org Cycle"
  1253. :group 'org-structure)
  1254. (defcustom org-cycle-skip-children-state-if-no-children t
  1255. "Non-nil means skip CHILDREN state in entries that don't have any."
  1256. :group 'org-cycle
  1257. :type 'boolean)
  1258. (defcustom org-cycle-max-level nil
  1259. "Maximum level which should still be subject to visibility cycling.
  1260. Levels higher than this will, for cycling, be treated as text, not a headline.
  1261. When `org-odd-levels-only' is set, a value of N in this variable actually
  1262. means 2N-1 stars as the limiting headline.
  1263. When nil, cycle all levels.
  1264. Note that the limiting level of cycling is also influenced by
  1265. `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
  1266. `org-inlinetask-min-level' is, cycling will be limited to levels one less
  1267. than its value."
  1268. :group 'org-cycle
  1269. :type '(choice
  1270. (const :tag "No limit" nil)
  1271. (integer :tag "Maximum level")))
  1272. (defcustom org-hide-block-startup nil
  1273. "Non-nil means entering Org mode will fold all blocks.
  1274. This can also be set in on a per-file basis with
  1275. #+STARTUP: hideblocks
  1276. #+STARTUP: showblocks"
  1277. :group 'org-startup
  1278. :group 'org-cycle
  1279. :type 'boolean)
  1280. (defcustom org-cycle-global-at-bob nil
  1281. "Cycle globally if cursor is at beginning of buffer and not at a headline.
  1282. This makes it possible to do global cycling without having to use `S-TAB'
  1283. or `\\[universal-argument] TAB'. For this special case to work, the first \
  1284. line of the buffer
  1285. must not be a headline -- it may be empty or some other text.
  1286. When used in this way, `org-cycle-hook' is disabled temporarily to make
  1287. sure the cursor stays at the beginning of the buffer.
  1288. When this option is nil, don't do anything special at the beginning of
  1289. the buffer."
  1290. :group 'org-cycle
  1291. :type 'boolean)
  1292. (defcustom org-cycle-level-after-item/entry-creation t
  1293. "Non-nil means cycle entry level or item indentation in new empty entries.
  1294. When the cursor is at the end of an empty headline, i.e., with only stars
  1295. and maybe a TODO keyword, TAB will then switch the entry to become a child,
  1296. and then all possible ancestor states, before returning to the original state.
  1297. This makes data entry extremely fast: M-RET to create a new headline,
  1298. on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
  1299. When the cursor is at the end of an empty plain list item, one TAB will
  1300. make it a subitem, two or more tabs will back up to make this an item
  1301. higher up in the item hierarchy."
  1302. :group 'org-cycle
  1303. :type 'boolean)
  1304. (defcustom org-cycle-emulate-tab t
  1305. "Where should `org-cycle' emulate TAB.
  1306. nil Never
  1307. white Only in completely white lines
  1308. whitestart Only at the beginning of lines, before the first non-white char
  1309. t Everywhere except in headlines
  1310. exc-hl-bol Everywhere except at the start of a headline
  1311. If TAB is used in a place where it does not emulate TAB, the current subtree
  1312. visibility is cycled."
  1313. :group 'org-cycle
  1314. :type '(choice (const :tag "Never" nil)
  1315. (const :tag "Only in completely white lines" white)
  1316. (const :tag "Before first char in a line" whitestart)
  1317. (const :tag "Everywhere except in headlines" t)
  1318. (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
  1319. (defcustom org-cycle-separator-lines 2
  1320. "Number of empty lines needed to keep an empty line between collapsed trees.
  1321. If you leave an empty line between the end of a subtree and the following
  1322. headline, this empty line is hidden when the subtree is folded.
  1323. Org mode will leave (exactly) one empty line visible if the number of
  1324. empty lines is equal or larger to the number given in this variable.
  1325. So the default 2 means at least 2 empty lines after the end of a subtree
  1326. are needed to produce free space between a collapsed subtree and the
  1327. following headline.
  1328. If the number is negative, and the number of empty lines is at least -N,
  1329. all empty lines are shown.
  1330. Special case: when 0, never leave empty lines in collapsed view."
  1331. :group 'org-cycle
  1332. :type 'integer)
  1333. (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
  1334. (defcustom org-pre-cycle-hook nil
  1335. "Hook that is run before visibility cycling is happening.
  1336. The function(s) in this hook must accept a single argument which indicates
  1337. the new state that will be set right after running this hook. The
  1338. argument is a symbol. Before a global state change, it can have the values
  1339. `overview', `content', or `all'. Before a local state change, it can have
  1340. the values `folded', `children', or `subtree'."
  1341. :group 'org-cycle
  1342. :type 'hook)
  1343. (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
  1344. org-cycle-hide-drawers
  1345. org-cycle-show-empty-lines
  1346. org-optimize-window-after-visibility-change)
  1347. "Hook that is run after `org-cycle' has changed the buffer visibility.
  1348. The function(s) in this hook must accept a single argument which indicates
  1349. the new state that was set by the most recent `org-cycle' command. The
  1350. argument is a symbol. After a global state change, it can have the values
  1351. `overview', `contents', or `all'. After a local state change, it can have
  1352. the values `folded', `children', or `subtree'."
  1353. :group 'org-cycle
  1354. :package-version '(Org . "9.4")
  1355. :type 'hook)
  1356. (defgroup org-edit-structure nil
  1357. "Options concerning structure editing in Org mode."
  1358. :tag "Org Edit Structure"
  1359. :group 'org-structure)
  1360. (defcustom org-odd-levels-only nil
  1361. "Non-nil means skip even levels and only use odd levels for the outline.
  1362. This has the effect that two stars are being added/taken away in
  1363. promotion/demotion commands. It also influences how levels are
  1364. handled by the exporters.
  1365. Changing it requires restart of `font-lock-mode' to become effective
  1366. for fontification also in regions already fontified.
  1367. You may also set this on a per-file basis by adding one of the following
  1368. lines to the buffer:
  1369. #+STARTUP: odd
  1370. #+STARTUP: oddeven"
  1371. :group 'org-edit-structure
  1372. :group 'org-appearance
  1373. :type 'boolean)
  1374. (defcustom org-adapt-indentation nil
  1375. "Non-nil means adapt indentation to outline node level.
  1376. When set to t, Org assumes that you write outlines by indenting
  1377. text in each node to align with the headline, after the stars.
  1378. When this variable is set to `headline-data', Org only adapts the
  1379. indentation of the data lines right below the headline, such as
  1380. planning/clock lines and property/logbook drawers.
  1381. The following issues are influenced by this variable:
  1382. - The indentation is increased by one space in a demotion
  1383. command, and decreased by one in a promotion command. However,
  1384. in the latter case, if shifting some line in the entry body
  1385. would alter document structure (e.g., insert a new headline),
  1386. indentation is not changed at all.
  1387. - Property drawers and planning information is inserted indented
  1388. when this variable is set. When nil, they will not be indented.
  1389. - TAB indents a line relative to current level. The lines below
  1390. a headline will be indented when this variable is set to t.
  1391. Note that this is all about true indentation, by adding and
  1392. removing space characters. See also \"org-indent.el\" which does
  1393. level-dependent indentation in a virtual way, i.e. at display
  1394. time in Emacs."
  1395. :group 'org-edit-structure
  1396. :type '(choice
  1397. (const :tag "Adapt indentation for all lines" t)
  1398. (const :tag "Adapt indentation for headline data lines"
  1399. headline-data)
  1400. (const :tag "Do not adapt indentation at all" nil))
  1401. :safe (lambda (x) (memq x '(t nil headline-data))))
  1402. (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
  1403. (defcustom org-special-ctrl-a/e nil
  1404. "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
  1405. When t, `C-a' will bring back the cursor to the beginning of the
  1406. headline text, i.e. after the stars and after a possible TODO
  1407. keyword. In an item, this will be the position after bullet and
  1408. check-box, if any. When the cursor is already at that position,
  1409. another `C-a' will bring it to the beginning of the line.
  1410. `C-e' will jump to the end of the headline, ignoring the presence
  1411. of tags in the headline. A second `C-e' will then jump to the
  1412. true end of the line, after any tags. This also means that, when
  1413. this variable is non-nil, `C-e' also will never jump beyond the
  1414. end of the heading of a folded section, i.e. not after the
  1415. ellipses.
  1416. When set to the symbol `reversed', the first `C-a' or `C-e' works
  1417. normally, going to the true line boundary first. Only a directly
  1418. following, identical keypress will bring the cursor to the
  1419. special positions.
  1420. This may also be a cons cell where the behavior for `C-a' and
  1421. `C-e' is set separately."
  1422. :group 'org-edit-structure
  1423. :type '(choice
  1424. (const :tag "off" nil)
  1425. (const :tag "on: after stars/bullet and before tags first" t)
  1426. (const :tag "reversed: true line boundary first" reversed)
  1427. (cons :tag "Set C-a and C-e separately"
  1428. (choice :tag "Special C-a"
  1429. (const :tag "off" nil)
  1430. (const :tag "on: after stars/bullet first" t)
  1431. (const :tag "reversed: before stars/bullet first" reversed))
  1432. (choice :tag "Special C-e"
  1433. (const :tag "off" nil)
  1434. (const :tag "on: before tags first" t)
  1435. (const :tag "reversed: after tags first" reversed)))))
  1436. (defcustom org-special-ctrl-k nil
  1437. "Non-nil means `C-k' will behave specially in headlines.
  1438. When nil, `C-k' will call the default `kill-line' command.
  1439. When t, the following will happen while the cursor is in the headline:
  1440. - When at the beginning of a headline, kill the entire subtree.
  1441. - When in the middle of the headline text, kill the text up to the tags.
  1442. - When after the headline text and before the tags, kill all the tags."
  1443. :group 'org-edit-structure
  1444. :type 'boolean)
  1445. (defcustom org-ctrl-k-protect-subtree nil
  1446. "Non-nil means, do not delete a hidden subtree with `C-k'.
  1447. When set to the symbol `error', simply throw an error when `C-k' is
  1448. used to kill (part-of) a headline that has hidden text behind it.
  1449. Any other non-nil value will result in a query to the user, if it is
  1450. OK to kill that hidden subtree. When nil, kill without remorse."
  1451. :group 'org-edit-structure
  1452. :version "24.1"
  1453. :type '(choice
  1454. (const :tag "Do not protect hidden subtrees" nil)
  1455. (const :tag "Protect hidden subtrees with a security query" t)
  1456. (const :tag "Never kill a hidden subtree with C-k" error)))
  1457. (defcustom org-special-ctrl-o t
  1458. "Non-nil means, make `C-o' insert a row in tables."
  1459. :group 'org-edit-structure
  1460. :type 'boolean)
  1461. (defcustom org-catch-invisible-edits nil
  1462. "Check if in invisible region before inserting or deleting a character.
  1463. Valid values are:
  1464. nil Do not check, so just do invisible edits.
  1465. error Throw an error and do nothing.
  1466. show Make point visible, and do the requested edit.
  1467. show-and-error Make point visible, then throw an error and abort the edit.
  1468. smart Make point visible, and do insertion/deletion if it is
  1469. adjacent to visible text and the change feels predictable.
  1470. Never delete a previously invisible character or add in the
  1471. middle or right after an invisible region. Basically, this
  1472. allows insertion and backward-delete right before ellipses.
  1473. FIXME: maybe in this case we should not even show?"
  1474. :group 'org-edit-structure
  1475. :version "24.1"
  1476. :type '(choice
  1477. (const :tag "Do not check" nil)
  1478. (const :tag "Throw error when trying to edit" error)
  1479. (const :tag "Unhide, but do not do the edit" show-and-error)
  1480. (const :tag "Show invisible part and do the edit" show)
  1481. (const :tag "Be smart and do the right thing" smart)))
  1482. (defcustom org-yank-folded-subtrees t
  1483. "Non-nil means when yanking subtrees, fold them.
  1484. If the kill is a single subtree, or a sequence of subtrees, i.e. if
  1485. it starts with a heading and all other headings in it are either children
  1486. or siblings, then fold all the subtrees. However, do this only if no
  1487. text after the yank would be swallowed into a folded tree by this action."
  1488. :group 'org-edit-structure
  1489. :type 'boolean)
  1490. (defcustom org-yank-adjusted-subtrees nil
  1491. "Non-nil means when yanking subtrees, adjust the level.
  1492. With this setting, `org-paste-subtree' is used to insert the subtree, see
  1493. this function for details."
  1494. :group 'org-edit-structure
  1495. :type 'boolean)
  1496. (defcustom org-M-RET-may-split-line '((default . t))
  1497. "Non-nil means M-RET will split the line at the cursor position.
  1498. When nil, it will go to the end of the line before making a
  1499. new line.
  1500. You may also set this option in a different way for different
  1501. contexts. Valid contexts are:
  1502. headline when creating a new headline
  1503. item when creating a new item
  1504. table in a table field
  1505. default the value to be used for all contexts not explicitly
  1506. customized"
  1507. :group 'org-structure
  1508. :group 'org-table
  1509. :type '(choice
  1510. (const :tag "Always" t)
  1511. (const :tag "Never" nil)
  1512. (repeat :greedy t :tag "Individual contexts"
  1513. (cons
  1514. (choice :tag "Context"
  1515. (const headline)
  1516. (const item)
  1517. (const table)
  1518. (const default))
  1519. (boolean)))))
  1520. (defcustom org-insert-heading-respect-content nil
  1521. "Non-nil means insert new headings after the current subtree.
  1522. \\<org-mode-map>
  1523. When nil, the new heading is created directly after the current line.
  1524. The commands `\\[org-insert-heading-respect-content]' and \
  1525. `\\[org-insert-todo-heading-respect-content]' turn this variable on
  1526. for the duration of the command."
  1527. :group 'org-structure
  1528. :type 'boolean)
  1529. (defcustom org-blank-before-new-entry '((heading . auto)
  1530. (plain-list-item . auto))
  1531. "Should `org-insert-heading' leave a blank line before new heading/item?
  1532. The value is an alist, with `heading' and `plain-list-item' as CAR,
  1533. and a boolean flag as CDR. The cdr may also be the symbol `auto', in
  1534. which case Org will look at the surrounding headings/items and try to
  1535. make an intelligent decision whether to insert a blank line or not."
  1536. :group 'org-edit-structure
  1537. :type '(list
  1538. (cons (const heading)
  1539. (choice (const :tag "Never" nil)
  1540. (const :tag "Always" t)
  1541. (const :tag "Auto" auto)))
  1542. (cons (const plain-list-item)
  1543. (choice (const :tag "Never" nil)
  1544. (const :tag "Always" t)
  1545. (const :tag "Auto" auto)))))
  1546. (defcustom org-insert-heading-hook nil
  1547. "Hook being run after inserting a new heading."
  1548. :group 'org-edit-structure
  1549. :type 'hook)
  1550. (defgroup org-sparse-trees nil
  1551. "Options concerning sparse trees in Org mode."
  1552. :tag "Org Sparse Trees"
  1553. :group 'org-structure)
  1554. (defcustom org-highlight-sparse-tree-matches t
  1555. "Non-nil means highlight all matches that define a sparse tree.
  1556. The highlights will automatically disappear the next time the buffer is
  1557. changed by an edit command."
  1558. :group 'org-sparse-trees
  1559. :type 'boolean)
  1560. (defcustom org-remove-highlights-with-change t
  1561. "Non-nil means any change to the buffer will remove temporary highlights.
  1562. \\<org-mode-map>\
  1563. Such highlights are created by `org-occur' and `org-clock-display'.
  1564. When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
  1565. to get rid of the highlights.
  1566. The highlights created by `org-latex-preview' always need
  1567. `\\[org-latex-preview]' to be removed."
  1568. :group 'org-sparse-trees
  1569. :group 'org-time
  1570. :type 'boolean)
  1571. (defcustom org-occur-case-fold-search t
  1572. "Non-nil means `org-occur' should be case-insensitive.
  1573. If set to `smart' the search will be case-insensitive only if it
  1574. doesn't specify any upper case character."
  1575. :group 'org-sparse-trees
  1576. :version "26.1"
  1577. :type '(choice
  1578. (const :tag "Case-sensitive" nil)
  1579. (const :tag "Case-insensitive" t)
  1580. (const :tag "Case-insensitive for lower case searches only" smart)))
  1581. (defcustom org-occur-hook '(org-first-headline-recenter)
  1582. "Hook that is run after `org-occur' has constructed a sparse tree.
  1583. This can be used to recenter the window to show as much of the structure
  1584. as possible."
  1585. :group 'org-sparse-trees
  1586. :type 'hook)
  1587. (defcustom org-self-insert-cluster-for-undo nil
  1588. "Non-nil means cluster self-insert commands for undo when possible.
  1589. If this is set, then, like in the Emacs command loop, 20 consecutive
  1590. characters will be undone together.
  1591. This is configurable, because there is some impact on typing performance."
  1592. :group 'org-table
  1593. :type 'boolean)
  1594. (defvaralias 'org-activate-links 'org-highlight-links)
  1595. (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
  1596. "Types of links that should be highlighted in Org files.
  1597. This is a list of symbols, each one of them leading to the
  1598. highlighting of a certain link type.
  1599. You can still open links that are not highlighted.
  1600. In principle, it does not hurt to turn on highlighting for all
  1601. link types. There may be a small gain when turning off unused
  1602. link types. The types are:
  1603. bracket The recommended [[link][description]] or [[link]] links with hiding.
  1604. angle Links in angular brackets that may contain whitespace like
  1605. <bbdb:Carsten Dominik>.
  1606. plain Plain links in normal text, no whitespace, like https://gnu.org.
  1607. radio Text that is matched by a radio target, see manual for details.
  1608. tag Tag settings in a headline (link to tag search).
  1609. date Time stamps (link to calendar).
  1610. footnote Footnote labels.
  1611. If you set this variable during an Emacs session, use `org-mode-restart'
  1612. in the Org buffer so that the change takes effect."
  1613. :group 'org-appearance
  1614. :type '(set :greedy t
  1615. (const :tag "Double bracket links" bracket)
  1616. (const :tag "Angular bracket links" angle)
  1617. (const :tag "Plain text links" plain)
  1618. (const :tag "Radio target matches" radio)
  1619. (const :tag "Tags" tag)
  1620. (const :tag "Timestamps" date)
  1621. (const :tag "Footnotes" footnote)))
  1622. (defcustom org-mark-ring-length 4
  1623. "Number of different positions to be recorded in the ring.
  1624. Changing this requires a restart of Emacs to work correctly."
  1625. :group 'org-link-follow
  1626. :type 'integer)
  1627. (defgroup org-todo nil
  1628. "Options concerning TODO items in Org mode."
  1629. :tag "Org TODO"
  1630. :group 'org)
  1631. (defgroup org-progress nil
  1632. "Options concerning Progress logging in Org mode."
  1633. :tag "Org Progress"
  1634. :group 'org-time)
  1635. (defvar org-todo-interpretation-widgets
  1636. '((:tag "Sequence (cycling hits every state)" sequence)
  1637. (:tag "Type (cycling directly to DONE)" type))
  1638. "The available interpretation symbols for customizing `org-todo-keywords'.
  1639. Interested libraries should add to this list.")
  1640. (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
  1641. "List of TODO entry keyword sequences and their interpretation.
  1642. \\<org-mode-map>This is a list of sequences.
  1643. Each sequence starts with a symbol, either `sequence' or `type',
  1644. indicating if the keywords should be interpreted as a sequence of
  1645. action steps, or as different types of TODO items. The first
  1646. keywords are states requiring action - these states will select a headline
  1647. for inclusion into the global TODO list Org produces. If one of the
  1648. \"keywords\" is the vertical bar, \"|\", the remaining keywords
  1649. signify that no further action is necessary. If \"|\" is not found,
  1650. the last keyword is treated as the only DONE state of the sequence.
  1651. The command `\\[org-todo]' cycles an entry through these states, and one
  1652. additional state where no keyword is present. For details about this
  1653. cycling, see the manual.
  1654. TODO keywords and interpretation can also be set on a per-file basis with
  1655. the special #+SEQ_TODO and #+TYP_TODO lines.
  1656. Each keyword can optionally specify a character for fast state selection
  1657. \(in combination with the variable `org-use-fast-todo-selection')
  1658. and specifiers for state change logging, using the same syntax that
  1659. is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
  1660. the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
  1661. indicates to record a time stamp each time this state is selected.
  1662. Each keyword may also specify if a timestamp or a note should be
  1663. recorded when entering or leaving the state, by adding additional
  1664. characters in the parenthesis after the keyword. This looks like this:
  1665. \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
  1666. record only the time of the state change. With X and Y being either
  1667. \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
  1668. Y when leaving the state if and only if the *target* state does not
  1669. define X. You may omit any of the fast-selection key or X or /Y,
  1670. so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
  1671. For backward compatibility, this variable may also be just a list
  1672. of keywords. In this case the interpretation (sequence or type) will be
  1673. taken from the (otherwise obsolete) variable `org-todo-interpretation'."
  1674. :group 'org-todo
  1675. :group 'org-keywords
  1676. :type '(choice
  1677. (repeat :tag "Old syntax, just keywords"
  1678. (string :tag "Keyword"))
  1679. (repeat :tag "New syntax"
  1680. (cons
  1681. (choice
  1682. :tag "Interpretation"
  1683. ;;Quick and dirty way to see
  1684. ;;`org-todo-interpretation'. This takes the
  1685. ;;place of item arguments
  1686. :convert-widget
  1687. (lambda (widget)
  1688. (widget-put widget
  1689. :args (mapcar
  1690. (lambda (x)
  1691. (widget-convert
  1692. (cons 'const x)))
  1693. org-todo-interpretation-widgets))
  1694. widget))
  1695. (repeat
  1696. (string :tag "Keyword"))))))
  1697. (defvar-local org-todo-keywords-1 nil
  1698. "All TODO and DONE keywords active in a buffer.")
  1699. (defvar org-todo-keywords-for-agenda nil)
  1700. (defvar org-done-keywords-for-agenda nil)
  1701. (defvar org-todo-keyword-alist-for-agenda nil)
  1702. (defvar org-tag-alist-for-agenda nil
  1703. "Alist of all tags from all agenda files.")
  1704. (defvar org-tag-groups-alist-for-agenda nil
  1705. "Alist of all groups tags from all current agenda files.")
  1706. (defvar-local org-tag-groups-alist nil)
  1707. (defvar org-agenda-contributing-files nil)
  1708. (defvar-local org-current-tag-alist nil
  1709. "Alist of all tag groups in current buffer.
  1710. This variable takes into consideration `org-tag-alist',
  1711. `org-tag-persistent-alist' and TAGS keywords in the buffer.")
  1712. (defvar-local org-not-done-keywords nil)
  1713. (defvar-local org-done-keywords nil)
  1714. (defvar-local org-todo-heads nil)
  1715. (defvar-local org-todo-sets nil)
  1716. (defvar-local org-todo-log-states nil)
  1717. (defvar-local org-todo-kwd-alist nil)
  1718. (defvar-local org-todo-key-alist nil)
  1719. (defvar-local org-todo-key-trigger nil)
  1720. (defcustom org-todo-interpretation 'sequence
  1721. "Controls how TODO keywords are interpreted.
  1722. This variable is in principle obsolete and is only used for
  1723. backward compatibility, if the interpretation of todo keywords is
  1724. not given already in `org-todo-keywords'. See that variable for
  1725. more information."
  1726. :group 'org-todo
  1727. :group 'org-keywords
  1728. :type '(choice (const sequence)
  1729. (const type)))
  1730. (defcustom org-use-fast-todo-selection 'auto
  1731. "\\<org-mode-map>\
  1732. Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
  1733. This variable describes if and under what circumstances the cycling
  1734. mechanism for TODO keywords will be replaced by a single-key, direct
  1735. selection scheme, where the choices are displayed in a little window.
  1736. When nil, fast selection is never used. This means that the command
  1737. will always switch to the next state.
  1738. When it is the symbol `auto', fast selection is whenever selection
  1739. keys have been defined.
  1740. `expert' is like `auto', but no special window with the keyword
  1741. will be shown, choices will only be listed in the prompt.
  1742. In all cases, the special interface is only used if access keys have
  1743. actually been assigned by the user, i.e. if keywords in the configuration
  1744. are followed by a letter in parenthesis, like TODO(t)."
  1745. :group 'org-todo
  1746. :set (lambda (var val)
  1747. (cond
  1748. ((eq var t) (set var 'auto))
  1749. ((eq var 'prefix) (set var nil))
  1750. (t (set var val))))
  1751. :type '(choice
  1752. (const :tag "Never" nil)
  1753. (const :tag "Automatically, when key letter have been defined" auto)
  1754. (const :tag "Automatically, but don't show the selection window" expert)))
  1755. (defcustom org-provide-todo-statistics t
  1756. "Non-nil means update todo statistics after insert and toggle.
  1757. ALL-HEADLINES means update todo statistics by including headlines
  1758. with no TODO keyword as well, counting them as not done.
  1759. A list of TODO keywords means the same, but skip keywords that are
  1760. not in this list.
  1761. When set to a list of two lists, the first list contains keywords
  1762. to consider as TODO keywords, the second list contains keywords
  1763. to consider as DONE keywords.
  1764. When this is set, todo statistics is updated in the parent of the
  1765. current entry each time a todo state is changed."
  1766. :group 'org-todo
  1767. :type '(choice
  1768. (const :tag "Yes, only for TODO entries" t)
  1769. (const :tag "Yes, including all entries" all-headlines)
  1770. (repeat :tag "Yes, for TODOs in this list"
  1771. (string :tag "TODO keyword"))
  1772. (list :tag "Yes, for TODOs and DONEs in these lists"
  1773. (repeat (string :tag "TODO keyword"))
  1774. (repeat (string :tag "DONE keyword")))
  1775. (other :tag "No TODO statistics" nil)))
  1776. (defcustom org-hierarchical-todo-statistics t
  1777. "Non-nil means TODO statistics covers just direct children.
  1778. When nil, all entries in the subtree are considered.
  1779. This has only an effect if `org-provide-todo-statistics' is set.
  1780. To set this to nil for only a single subtree, use a COOKIE_DATA
  1781. property and include the word \"recursive\" into the value."
  1782. :group 'org-todo
  1783. :type 'boolean)
  1784. (defcustom org-after-todo-state-change-hook nil
  1785. "Hook which is run after the state of a TODO item was changed.
  1786. The new state (a string with a TODO keyword, or nil) is available in the
  1787. Lisp variable `org-state'."
  1788. :group 'org-todo
  1789. :type 'hook)
  1790. (defvar org-blocker-hook nil
  1791. "Hook for functions that are allowed to block a state change.
  1792. Functions in this hook should not modify the buffer.
  1793. Each function gets as its single argument a property list,
  1794. see `org-trigger-hook' for more information about this list.
  1795. If any of the functions in this hook returns nil, the state change
  1796. is blocked.")
  1797. (defvar org-trigger-hook nil
  1798. "Hook for functions that are triggered by a state change.
  1799. Each function gets as its single argument a property list with at
  1800. least the following elements:
  1801. (:type type-of-change :position pos-at-entry-start
  1802. :from old-state :to new-state)
  1803. Depending on the type, more properties may be present.
  1804. This mechanism is currently implemented for:
  1805. TODO state changes
  1806. ------------------
  1807. :type todo-state-change
  1808. :from previous state (keyword as a string), or nil, or a symbol
  1809. `todo' or `done', to indicate the general type of state.
  1810. :to new state, like in :from")
  1811. (defcustom org-enforce-todo-dependencies nil
  1812. "Non-nil means undone TODO entries will block switching the parent to DONE.
  1813. Also, if a parent has an :ORDERED: property, switching an entry to DONE will
  1814. be blocked if any prior sibling is not yet done.
  1815. Finally, if the parent is blocked because of ordered siblings of its own,
  1816. the child will also be blocked."
  1817. :set (lambda (var val)
  1818. (set var val)
  1819. (if val
  1820. (add-hook 'org-blocker-hook
  1821. 'org-block-todo-from-children-or-siblings-or-parent)
  1822. (remove-hook 'org-blocker-hook
  1823. 'org-block-todo-from-children-or-siblings-or-parent)))
  1824. :group 'org-todo
  1825. :type 'boolean)
  1826. (defcustom org-enforce-todo-checkbox-dependencies nil
  1827. "Non-nil means unchecked boxes will block switching the parent to DONE.
  1828. When this is nil, checkboxes have no influence on switching TODO states.
  1829. When non-nil, you first need to check off all check boxes before the TODO
  1830. entry can be switched to DONE.
  1831. This variable needs to be set before org.el is loaded, and you need to
  1832. restart Emacs after a change to make the change effective. The only way
  1833. to change it while Emacs is running is through the customize interface."
  1834. :set (lambda (var val)
  1835. (set var val)
  1836. (if val
  1837. (add-hook 'org-blocker-hook
  1838. 'org-block-todo-from-checkboxes)
  1839. (remove-hook 'org-blocker-hook
  1840. 'org-block-todo-from-checkboxes)))
  1841. :group 'org-todo
  1842. :type 'boolean)
  1843. (defcustom org-treat-insert-todo-heading-as-state-change nil
  1844. "Non-nil means inserting a TODO heading is treated as state change.
  1845. So when the command `\\[org-insert-todo-heading]' is used, state change
  1846. logging will apply if appropriate. When nil, the new TODO item will
  1847. be inserted directly, and no logging will take place."
  1848. :group 'org-todo
  1849. :type 'boolean)
  1850. (defcustom org-treat-S-cursor-todo-selection-as-state-change t
  1851. "Non-nil means switching TODO states with S-cursor counts as state change.
  1852. This is the default behavior. However, setting this to nil allows a
  1853. convenient way to select a TODO state and bypass any logging associated
  1854. with that."
  1855. :group 'org-todo
  1856. :type 'boolean)
  1857. (defcustom org-todo-state-tags-triggers nil
  1858. "Tag changes that should be triggered by TODO state changes.
  1859. This is a list. Each entry is
  1860. (state-change (tag . flag) .......)
  1861. State-change can be a string with a state, and empty string to indicate the
  1862. state that has no TODO keyword, or it can be one of the symbols `todo'
  1863. or `done', meaning any not-done or done state, respectively."
  1864. :group 'org-todo
  1865. :group 'org-tags
  1866. :type '(repeat
  1867. (cons (choice :tag "When changing to"
  1868. (const :tag "Not-done state" todo)
  1869. (const :tag "Done state" done)
  1870. (string :tag "State"))
  1871. (repeat
  1872. (cons :tag "Tag action"
  1873. (string :tag "Tag")
  1874. (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
  1875. (defcustom org-log-done nil
  1876. "Information to record when a task moves to the DONE state.
  1877. Possible values are:
  1878. nil Don't add anything, just change the keyword
  1879. time Add a time stamp to the task
  1880. note Prompt for a note and add it with template `org-log-note-headings'
  1881. This option can also be set with on a per-file-basis with
  1882. #+STARTUP: nologdone
  1883. #+STARTUP: logdone
  1884. #+STARTUP: lognotedone
  1885. You can have local logging settings for a subtree by setting the LOGGING
  1886. property to one or more of these keywords."
  1887. :group 'org-todo
  1888. :group 'org-progress
  1889. :type '(choice
  1890. (const :tag "No logging" nil)
  1891. (const :tag "Record CLOSED timestamp" time)
  1892. (const :tag "Record CLOSED timestamp with note." note)))
  1893. ;; Normalize old uses of org-log-done.
  1894. (cond
  1895. ((eq org-log-done t) (setq org-log-done 'time))
  1896. ((and (listp org-log-done) (memq 'done org-log-done))
  1897. (setq org-log-done 'note)))
  1898. (defcustom org-log-reschedule nil
  1899. "Information to record when the scheduling date of a task is modified.
  1900. Possible values are:
  1901. nil Don't add anything, just change the date
  1902. time Add a time stamp to the task
  1903. note Prompt for a note and add it with template `org-log-note-headings'
  1904. This option can also be set with on a per-file-basis with
  1905. #+STARTUP: nologreschedule
  1906. #+STARTUP: logreschedule
  1907. #+STARTUP: lognotereschedule
  1908. You can have local logging settings for a subtree by setting the LOGGING
  1909. property to one or more of these keywords.
  1910. This variable has an effect when calling `org-schedule' or
  1911. `org-agenda-schedule' only."
  1912. :group 'org-todo
  1913. :group 'org-progress
  1914. :type '(choice
  1915. (const :tag "No logging" nil)
  1916. (const :tag "Record timestamp" time)
  1917. (const :tag "Record timestamp with note" note)))
  1918. (defcustom org-log-redeadline nil
  1919. "Information to record when the deadline date of a task is modified.
  1920. Possible values are:
  1921. nil Don't add anything, just change the date
  1922. time Add a time stamp to the task
  1923. note Prompt for a note and add it with template `org-log-note-headings'
  1924. This option can also be set with on a per-file-basis with
  1925. #+STARTUP: nologredeadline
  1926. #+STARTUP: logredeadline
  1927. #+STARTUP: lognoteredeadline
  1928. You can have local logging settings for a subtree by setting the LOGGING
  1929. property to one or more of these keywords.
  1930. This variable has an effect when calling `org-deadline' or
  1931. `org-agenda-deadline' only."
  1932. :group 'org-todo
  1933. :group 'org-progress
  1934. :type '(choice
  1935. (const :tag "No logging" nil)
  1936. (const :tag "Record timestamp" time)
  1937. (const :tag "Record timestamp with note." note)))
  1938. (defcustom org-log-note-clock-out nil
  1939. "Non-nil means record a note when clocking out of an item.
  1940. This can also be configured on a per-file basis by adding one of
  1941. the following lines anywhere in the buffer:
  1942. #+STARTUP: lognoteclock-out
  1943. #+STARTUP: nolognoteclock-out"
  1944. :group 'org-todo
  1945. :group 'org-progress
  1946. :type 'boolean)
  1947. (defcustom org-log-done-with-time t
  1948. "Non-nil means the CLOSED time stamp will contain date and time.
  1949. When nil, only the date will be recorded."
  1950. :group 'org-progress
  1951. :type 'boolean)
  1952. (defcustom org-log-note-headings
  1953. '((done . "CLOSING NOTE %t")
  1954. (state . "State %-12s from %-12S %t")
  1955. (note . "Note taken on %t")
  1956. (reschedule . "Rescheduled from %S on %t")
  1957. (delschedule . "Not scheduled, was %S on %t")
  1958. (redeadline . "New deadline from %S on %t")
  1959. (deldeadline . "Removed deadline, was %S on %t")
  1960. (refile . "Refiled on %t")
  1961. (clock-out . ""))
  1962. "Headings for notes added to entries.
  1963. The value is an alist, with the car being a symbol indicating the
  1964. note context, and the cdr is the heading to be used. The heading
  1965. may also be the empty string. The following placeholders can be
  1966. used:
  1967. %t a time stamp.
  1968. %T an active time stamp instead the default inactive one
  1969. %d a short-format time stamp.
  1970. %D an active short-format time stamp.
  1971. %s the new TODO state or time stamp (inactive), in double quotes.
  1972. %S the old TODO state or time stamp (inactive), in double quotes.
  1973. %u the user name.
  1974. %U full user name.
  1975. In fact, it is not a good idea to change the `state' entry,
  1976. because Agenda Log mode depends on the format of these entries."
  1977. :group 'org-todo
  1978. :group 'org-progress
  1979. :type '(list :greedy t
  1980. (cons (const :tag "Heading when closing an item" done) string)
  1981. (cons (const :tag
  1982. "Heading when changing todo state (todo sequence only)"
  1983. state) string)
  1984. (cons (const :tag "Heading when just taking a note" note) string)
  1985. (cons (const :tag "Heading when rescheduling" reschedule) string)
  1986. (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
  1987. (cons (const :tag "Heading when changing deadline" redeadline) string)
  1988. (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
  1989. (cons (const :tag "Heading when refiling" refile) string)
  1990. (cons (const :tag "Heading when clocking out" clock-out) string)))
  1991. (unless (assq 'note org-log-note-headings)
  1992. (push '(note . "%t") org-log-note-headings))
  1993. (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
  1994. (defcustom org-log-into-drawer nil
  1995. "Non-nil means insert state change notes and time stamps into a drawer.
  1996. When nil, state changes notes will be inserted after the headline and
  1997. any scheduling and clock lines, but not inside a drawer.
  1998. The value of this variable should be the name of the drawer to use.
  1999. LOGBOOK is proposed as the default drawer for this purpose, you can
  2000. also set this to a string to define the drawer of your choice.
  2001. A value of t is also allowed, representing \"LOGBOOK\".
  2002. A value of t or nil can also be set with on a per-file-basis with
  2003. #+STARTUP: logdrawer
  2004. #+STARTUP: nologdrawer
  2005. If this variable is set, `org-log-state-notes-insert-after-drawers'
  2006. will be ignored.
  2007. You can set the property LOG_INTO_DRAWER to overrule this setting for
  2008. a subtree.
  2009. Do not check directly this variable in a Lisp program. Call
  2010. function `org-log-into-drawer' instead."
  2011. :group 'org-todo
  2012. :group 'org-progress
  2013. :type '(choice
  2014. (const :tag "Not into a drawer" nil)
  2015. (const :tag "LOGBOOK" t)
  2016. (string :tag "Other")))
  2017. (defun org-log-into-drawer ()
  2018. "Name of the log drawer, as a string, or nil.
  2019. This is the value of `org-log-into-drawer'. However, if the
  2020. current entry has or inherits a LOG_INTO_DRAWER property, it will
  2021. be used instead of the default value."
  2022. (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
  2023. (cond ((equal p "nil") nil)
  2024. ((equal p "t") "LOGBOOK")
  2025. ((stringp p) p)
  2026. (p "LOGBOOK")
  2027. ((stringp org-log-into-drawer) org-log-into-drawer)
  2028. (org-log-into-drawer "LOGBOOK"))))
  2029. (defcustom org-log-state-notes-insert-after-drawers nil
  2030. "Non-nil means insert state change notes after any drawers in entry.
  2031. Only the drawers that *immediately* follow the headline and the
  2032. deadline/scheduled line are skipped.
  2033. When nil, insert notes right after the heading and perhaps the line
  2034. with deadline/scheduling if present.
  2035. This variable will have no effect if `org-log-into-drawer' is
  2036. set."
  2037. :group 'org-todo
  2038. :group 'org-progress
  2039. :type 'boolean)
  2040. (defcustom org-log-states-order-reversed t
  2041. "Non-nil means the latest state note will be directly after heading.
  2042. When nil, the state change notes will be ordered according to time.
  2043. This option can also be set with on a per-file-basis with
  2044. #+STARTUP: logstatesreversed
  2045. #+STARTUP: nologstatesreversed"
  2046. :group 'org-todo
  2047. :group 'org-progress
  2048. :type 'boolean)
  2049. (defcustom org-todo-repeat-to-state nil
  2050. "The TODO state to which a repeater should return the repeating task.
  2051. By default this is the first task of a TODO sequence or the
  2052. previous state of a TYPE_TODO set. But you can specify to use
  2053. the previous state in a TODO sequence or a string.
  2054. Alternatively, you can set the :REPEAT_TO_STATE: property of the
  2055. entry, which has precedence over this option."
  2056. :group 'org-todo
  2057. :version "24.1"
  2058. :type '(choice (const :tag "Use the previous TODO state" t)
  2059. (const :tag "Use the head of the TODO sequence" nil)
  2060. (string :tag "Use a specific TODO state")))
  2061. (defcustom org-log-repeat 'time
  2062. "Non-nil means record moving through the DONE state when triggering repeat.
  2063. An auto-repeating task is immediately switched back to TODO when
  2064. marked DONE. If you are not logging state changes (by adding \"@\"
  2065. or \"!\" to the TODO keyword definition), or set `org-log-done' to
  2066. record a closing note, there will be no record of the task moving
  2067. through DONE. This variable forces taking a note anyway.
  2068. nil Don't force a record
  2069. time Record a time stamp
  2070. note Prompt for a note and add it with template `org-log-note-headings'
  2071. This option can also be set with on a per-file-basis with
  2072. #+STARTUP: nologrepeat
  2073. #+STARTUP: logrepeat
  2074. #+STARTUP: lognoterepeat
  2075. You can have local logging settings for a subtree by setting the LOGGING
  2076. property to one or more of these keywords."
  2077. :group 'org-todo
  2078. :group 'org-progress
  2079. :type '(choice
  2080. (const :tag "Don't force a record" nil)
  2081. (const :tag "Force recording the DONE state" time)
  2082. (const :tag "Force recording a note with the DONE state" note)))
  2083. (defcustom org-todo-repeat-hook nil
  2084. "Hook that is run after a task has been repeated."
  2085. :package-version '(Org . "9.2")
  2086. :group 'org-todo
  2087. :type 'hook)
  2088. (defgroup org-priorities nil
  2089. "Priorities in Org mode."
  2090. :tag "Org Priorities"
  2091. :group 'org-todo)
  2092. (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
  2093. (defcustom org-priority-enable-commands t
  2094. "Non-nil means priority commands are active.
  2095. When nil, these commands will be disabled, so that you never accidentally
  2096. set a priority."
  2097. :group 'org-priorities
  2098. :type 'boolean)
  2099. (defvaralias 'org-highest-priority 'org-priority-highest)
  2100. (defcustom org-priority-highest ?A
  2101. "The highest priority of TODO items.
  2102. A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
  2103. The default is the character ?A, which is 65 as a numeric value.
  2104. If you set `org-priority-highest' to a numeric value inferior to
  2105. 65, Org assumes you want to use digits for the priority cookie.
  2106. If you set it to >=65, Org assumes you want to use alphabetical
  2107. characters.
  2108. In both cases, the value of `org-priority-highest' must be
  2109. smaller than `org-priority-lowest': for example, if \"A\" is the
  2110. highest priority, it is smaller than the lowest \"C\" priority:
  2111. 65 < 67."
  2112. :group 'org-priorities
  2113. :type '(choice
  2114. (character :tag "Character")
  2115. (integer :tag "Integer (< 65)")))
  2116. (defvaralias 'org-lowest-priority 'org-priority-lowest)
  2117. (defcustom org-priority-lowest ?C
  2118. "The lowest priority of TODO items.
  2119. A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
  2120. The default is the character ?C, which is 67 as a numeric value.
  2121. If you set `org-priority-lowest' to a numeric value inferior to
  2122. 65, Org assumes you want to use digits for the priority cookie.
  2123. If you set it to >=65, Org assumes you want to use alphabetical
  2124. characters.
  2125. In both cases, the value of `org-priority-lowest' must be greater
  2126. than `org-priority-highest': for example, if \"C\" is the lowest
  2127. priority, it is greater than the highest \"A\" priority: 67 >
  2128. 65."
  2129. :group 'org-priorities
  2130. :type '(choice
  2131. (character :tag "Character")
  2132. (integer :tag "Integer (< 65)")))
  2133. (defvaralias 'org-default-priority 'org-priority-default)
  2134. (defcustom org-priority-default ?B
  2135. "The default priority of TODO items.
  2136. This is the priority an item gets if no explicit priority is given.
  2137. When starting to cycle on an empty priority the first step in the cycle
  2138. depends on `org-priority-start-cycle-with-default'. The resulting first
  2139. step priority must not exceed the range from `org-priority-highest' to
  2140. `org-priority-lowest' which means that `org-priority-default' has to be
  2141. in this range exclusive or inclusive to the range boundaries. Else the
  2142. first step refuses to set the default and the second will fall back on
  2143. \(depending on the command used) the highest or lowest priority."
  2144. :group 'org-priorities
  2145. :type '(choice
  2146. (character :tag "Character")
  2147. (integer :tag "Integer (< 65)")))
  2148. (defcustom org-priority-start-cycle-with-default t
  2149. "Non-nil means start with default priority when starting to cycle.
  2150. When this is nil, the first step in the cycle will be (depending on the
  2151. command used) one higher or lower than the default priority.
  2152. See also `org-priority-default'."
  2153. :group 'org-priorities
  2154. :type 'boolean)
  2155. (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
  2156. (defcustom org-priority-get-priority-function nil
  2157. "Function to extract the priority from a string.
  2158. The string is normally the headline. If this is nil, Org
  2159. computes the priority from the priority cookie like [#A] in the
  2160. headline. It returns an integer, increasing by 1000 for each
  2161. priority level.
  2162. The user can set a different function here, which should take a
  2163. string as an argument and return the numeric priority."
  2164. :group 'org-priorities
  2165. :version "24.1"
  2166. :type '(choice
  2167. (const nil)
  2168. (function)))
  2169. (defgroup org-time nil
  2170. "Options concerning time stamps and deadlines in Org mode."
  2171. :tag "Org Time"
  2172. :group 'org)
  2173. (defcustom org-time-stamp-rounding-minutes '(0 5)
  2174. "Number of minutes to round time stamps to.
  2175. \\<org-mode-map>\
  2176. These are two values, the first applies when first creating a time stamp.
  2177. The second applies when changing it with the commands `S-up' and `S-down'.
  2178. When changing the time stamp, this means that it will change in steps
  2179. of N minutes, as given by the second value.
  2180. When a setting is 0 or 1, insert the time unmodified. Useful rounding
  2181. numbers should be factors of 60, so for example 5, 10, 15.
  2182. When this is larger than 1, you can still force an exact time stamp by using
  2183. a double prefix argument to a time stamp command like \
  2184. `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
  2185. and by using a prefix arg to `S-up/down' to specify the exact number
  2186. of minutes to shift."
  2187. :group 'org-time
  2188. :get (lambda (var) ; Make sure both elements are there
  2189. (if (integerp (default-value var))
  2190. (list (default-value var) 5)
  2191. (default-value var)))
  2192. :type '(list
  2193. (integer :tag "when inserting times")
  2194. (integer :tag "when modifying times")))
  2195. ;; Normalize old customizations of this variable.
  2196. (when (integerp org-time-stamp-rounding-minutes)
  2197. (setq org-time-stamp-rounding-minutes
  2198. (list org-time-stamp-rounding-minutes
  2199. org-time-stamp-rounding-minutes)))
  2200. (defcustom org-display-custom-times nil
  2201. "Non-nil means overlay custom formats over all time stamps.
  2202. The formats are defined through the variable `org-time-stamp-custom-formats'.
  2203. To turn this on on a per-file basis, insert anywhere in the file:
  2204. #+STARTUP: customtime"
  2205. :group 'org-time
  2206. :set 'set-default
  2207. :type 'sexp)
  2208. (make-variable-buffer-local 'org-display-custom-times)
  2209. (defcustom org-time-stamp-custom-formats
  2210. '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
  2211. "Custom formats for time stamps. See `format-time-string' for the syntax.
  2212. These are overlaid over the default ISO format if the variable
  2213. `org-display-custom-times' is set. Time like %H:%M should be at the
  2214. end of the second format. The custom formats are also honored by export
  2215. commands, if custom time display is turned on at the time of export."
  2216. :group 'org-time
  2217. :type 'sexp)
  2218. (defun org-time-stamp-format (&optional long inactive)
  2219. "Get the right format for a time string."
  2220. (let ((f (if long (cdr org-time-stamp-formats)
  2221. (car org-time-stamp-formats))))
  2222. (if inactive
  2223. (concat "[" (substring f 1 -1) "]")
  2224. f)))
  2225. (defcustom org-deadline-warning-days 14
  2226. "Number of days before expiration during which a deadline becomes active.
  2227. This variable governs the display in sparse trees and in the agenda.
  2228. When 0 or negative, it means use this number (the absolute value of it)
  2229. even if a deadline has a different individual lead time specified.
  2230. Custom commands can set this variable in the options section."
  2231. :group 'org-time
  2232. :group 'org-agenda-daily/weekly
  2233. :type 'integer)
  2234. (defcustom org-scheduled-delay-days 0
  2235. "Number of days before a scheduled item becomes active.
  2236. This variable governs the display in sparse trees and in the agenda.
  2237. The default value (i.e. 0) means: don't delay scheduled item.
  2238. When negative, it means use this number (the absolute value of it)
  2239. even if a scheduled item has a different individual delay time
  2240. specified.
  2241. Custom commands can set this variable in the options section."
  2242. :group 'org-time
  2243. :group 'org-agenda-daily/weekly
  2244. :version "24.4"
  2245. :package-version '(Org . "8.0")
  2246. :type 'integer)
  2247. (defcustom org-read-date-prefer-future t
  2248. "Non-nil means assume future for incomplete date input from user.
  2249. This affects the following situations:
  2250. 1. The user gives a month but not a year.
  2251. For example, if it is April and you enter \"feb 2\", this will be read
  2252. as Feb 2, *next* year. \"May 5\", however, will be this year.
  2253. 2. The user gives a day, but no month.
  2254. For example, if today is the 15th, and you enter \"3\", Org will read
  2255. this as the third of *next* month. However, if you enter \"17\",
  2256. it will be considered as *this* month.
  2257. If you set this variable to the symbol `time', then also the following
  2258. will work:
  2259. 3. If the user gives a time.
  2260. If the time is before now, it will be interpreted as tomorrow.
  2261. Currently none of this works for ISO week specifications.
  2262. When this option is nil, the current day, month and year will always be
  2263. used as defaults.
  2264. See also `org-agenda-jump-prefer-future'."
  2265. :group 'org-time
  2266. :type '(choice
  2267. (const :tag "Never" nil)
  2268. (const :tag "Check month and day" t)
  2269. (const :tag "Check month, day, and time" time)))
  2270. (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
  2271. "Should the agenda jump command prefer the future for incomplete dates?
  2272. The default is to do the same as configured in `org-read-date-prefer-future'.
  2273. But you can also set a deviating value here.
  2274. This may t or nil, or the symbol `org-read-date-prefer-future'."
  2275. :group 'org-agenda
  2276. :group 'org-time
  2277. :version "24.1"
  2278. :type '(choice
  2279. (const :tag "Use org-read-date-prefer-future"
  2280. org-read-date-prefer-future)
  2281. (const :tag "Never" nil)
  2282. (const :tag "Always" t)))
  2283. (defcustom org-read-date-force-compatible-dates t
  2284. "Should date/time prompt force dates that are guaranteed to work in Emacs?
  2285. Depending on the system Emacs is running on, certain dates cannot
  2286. be represented with the type used internally to represent time.
  2287. Dates between 1970-1-1 and 2038-1-1 can always be represented
  2288. correctly. Some systems allow for earlier dates, some for later,
  2289. some for both. One way to find out is to insert any date into an
  2290. Org buffer, putting the cursor on the year and hitting S-up and
  2291. S-down to test the range.
  2292. When this variable is set to t, the date/time prompt will not let
  2293. you specify dates outside the 1970-2037 range, so it is certain that
  2294. these dates will work in whatever version of Emacs you are
  2295. running, and also that you can move a file from one Emacs implementation
  2296. to another. Whenever Org is forcing the year for you, it will display
  2297. a message and beep.
  2298. When this variable is nil, Org will check if the date is
  2299. representable in the specific Emacs implementation you are using.
  2300. If not, it will force a year, usually the current year, and beep
  2301. to remind you. Currently this setting is not recommended because
  2302. the likelihood that you will open your Org files in an Emacs that
  2303. has limited date range is not negligible.
  2304. A workaround for this problem is to use diary sexp dates for time
  2305. stamps outside of this range."
  2306. :group 'org-time
  2307. :version "24.1"
  2308. :type 'boolean)
  2309. (defcustom org-read-date-display-live t
  2310. "Non-nil means display current interpretation of date prompt live.
  2311. This display will be in an overlay, in the minibuffer. Note that
  2312. live display is only active when `org-read-date-popup-calendar'
  2313. is non-nil."
  2314. :group 'org-time
  2315. :type 'boolean)
  2316. (defvaralias 'org-popup-calendar-for-date-prompt
  2317. 'org-read-date-popup-calendar)
  2318. (defcustom org-read-date-popup-calendar t
  2319. "Non-nil means pop up a calendar when prompting for a date.
  2320. In the calendar, the date can be selected with mouse-1. However, the
  2321. minibuffer will also be active, and you can simply enter the date as well.
  2322. When nil, only the minibuffer will be available."
  2323. :group 'org-time
  2324. :type 'boolean)
  2325. (defcustom org-extend-today-until 0
  2326. "The hour when your day really ends. Must be an integer.
  2327. This has influence for the following applications:
  2328. - When switching the agenda to \"today\". If it is still earlier than
  2329. the time given here, the day recognized as TODAY is actually yesterday.
  2330. - When a date is read from the user and it is still before the time given
  2331. here, the current date and time will be assumed to be yesterday, 23:59.
  2332. Also, timestamps inserted in capture templates follow this rule.
  2333. IMPORTANT: This is a feature whose implementation is and likely will
  2334. remain incomplete. Really, it is only here because past midnight seems to
  2335. be the favorite working time of John Wiegley :-)"
  2336. :group 'org-time
  2337. :type 'integer)
  2338. (defcustom org-use-effective-time nil
  2339. "If non-nil, consider `org-extend-today-until' when creating timestamps.
  2340. For example, if `org-extend-today-until' is 8, and it's 4am, then the
  2341. \"effective time\" of any timestamps between midnight and 8am will be
  2342. 23:59 of the previous day."
  2343. :group 'org-time
  2344. :version "24.1"
  2345. :type 'boolean)
  2346. (defcustom org-use-last-clock-out-time-as-effective-time nil
  2347. "When non-nil, use the last clock out time for `org-todo'.
  2348. Note that this option has precedence over the combined use of
  2349. `org-use-effective-time' and `org-extend-today-until'."
  2350. :group 'org-time
  2351. :version "24.4"
  2352. :package-version '(Org . "8.0")
  2353. :type 'boolean)
  2354. (defcustom org-edit-timestamp-down-means-later nil
  2355. "Non-nil means S-down will increase the time in a time stamp.
  2356. When nil, S-up will increase."
  2357. :group 'org-time
  2358. :type 'boolean)
  2359. (defcustom org-calendar-follow-timestamp-change t
  2360. "Non-nil means make the calendar window follow timestamp changes.
  2361. When a timestamp is modified and the calendar window is visible, it will be
  2362. moved to the new date."
  2363. :group 'org-time
  2364. :type 'boolean)
  2365. (defgroup org-tags nil
  2366. "Options concerning tags in Org mode."
  2367. :tag "Org Tags"
  2368. :group 'org)
  2369. (defcustom org-tag-alist nil
  2370. "Default tags available in Org files.
  2371. The value of this variable is an alist. Associations either:
  2372. (TAG)
  2373. (TAG . SELECT)
  2374. (SPECIAL)
  2375. where TAG is a tag as a string, SELECT is character, used to
  2376. select that tag through the fast tag selection interface, and
  2377. SPECIAL is one of the following keywords: `:startgroup',
  2378. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2379. `:newline'. These keywords are used to define a hierarchy of
  2380. tags. See manual for details.
  2381. When this variable is nil, Org mode bases tag input on what is
  2382. already in the buffer. The value can be overridden locally by
  2383. using a TAGS keyword, e.g.,
  2384. #+TAGS: tag1 tag2
  2385. See also `org-tag-persistent-alist' to sidestep this behavior."
  2386. :group 'org-tags
  2387. :type '(repeat
  2388. (choice
  2389. (cons :tag "Tag with key"
  2390. (string :tag "Tag name")
  2391. (character :tag "Access char"))
  2392. (list :tag "Tag" (string :tag "Tag name"))
  2393. (const :tag "Start radio group" (:startgroup))
  2394. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2395. (const :tag "Group tags delimiter" (:grouptags))
  2396. (const :tag "End radio group" (:endgroup))
  2397. (const :tag "End tag group, non distinct" (:endgrouptag))
  2398. (const :tag "New line" (:newline)))))
  2399. (defcustom org-tag-persistent-alist nil
  2400. "Tags always available in Org files.
  2401. The value of this variable is an alist. Associations either:
  2402. (TAG)
  2403. (TAG . SELECT)
  2404. (SPECIAL)
  2405. where TAG is a tag as a string, SELECT is a character, used to
  2406. select that tag through the fast tag selection interface, and
  2407. SPECIAL is one of the following keywords: `:startgroup',
  2408. `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
  2409. `:newline'. These keywords are used to define a hierarchy of
  2410. tags. See manual for details.
  2411. Unlike to `org-tag-alist', tags defined in this variable do not
  2412. depend on a local TAGS keyword. Instead, to disable these tags
  2413. on a per-file basis, insert anywhere in the file:
  2414. #+STARTUP: noptag"
  2415. :group 'org-tags
  2416. :type '(repeat
  2417. (choice
  2418. (cons :tag "Tag with key"
  2419. (string :tag "Tag name")
  2420. (character :tag "Access char"))
  2421. (list :tag "Tag" (string :tag "Tag name"))
  2422. (const :tag "Start radio group" (:startgroup))
  2423. (const :tag "Start tag group, non distinct" (:startgrouptag))
  2424. (const :tag "Group tags delimiter" (:grouptags))
  2425. (const :tag "End radio group" (:endgroup))
  2426. (const :tag "End tag group, non distinct" (:endgrouptag))
  2427. (const :tag "New line" (:newline)))))
  2428. (defcustom org-complete-tags-always-offer-all-agenda-tags nil
  2429. "If non-nil, always offer completion for all tags of all agenda files.
  2430. Setting this variable locally allows for dynamic generation of tag
  2431. completions in capture buffers.
  2432. (add-hook \\='org-capture-mode-hook
  2433. (lambda ()
  2434. (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
  2435. :group 'org-tags
  2436. :version "24.1"
  2437. :type 'boolean)
  2438. (defvar org-file-tags nil
  2439. "List of tags that can be inherited by all entries in the file.
  2440. The tags will be inherited if the variable `org-use-tag-inheritance'
  2441. says they should be.
  2442. This variable is populated from #+FILETAGS lines.")
  2443. (defcustom org-use-fast-tag-selection 'auto
  2444. "Non-nil means use fast tag selection scheme.
  2445. This is a special interface to select and deselect tags with single keys.
  2446. When nil, fast selection is never used.
  2447. When the symbol `auto', fast selection is used if and only if selection
  2448. characters for tags have been configured, either through the variable
  2449. `org-tag-alist' or through a #+TAGS line in the buffer.
  2450. When t, fast selection is always used and selection keys are assigned
  2451. automatically if necessary."
  2452. :group 'org-tags
  2453. :type '(choice
  2454. (const :tag "Always" t)
  2455. (const :tag "Never" nil)
  2456. (const :tag "When selection characters are configured" auto)))
  2457. (defcustom org-fast-tag-selection-single-key nil
  2458. "Non-nil means fast tag selection exits after first change.
  2459. When nil, you have to press RET to exit it.
  2460. During fast tag selection, you can toggle this flag with `C-c'.
  2461. This variable can also have the value `expert'. In this case, the window
  2462. displaying the tags menu is not even shown, until you press `C-c' again."
  2463. :group 'org-tags
  2464. :type '(choice
  2465. (const :tag "No" nil)
  2466. (const :tag "Yes" t)
  2467. (const :tag "Expert" expert)))
  2468. (defvar org-fast-tag-selection-include-todo nil
  2469. "Non-nil means fast tags selection interface will also offer TODO states.
  2470. This is an undocumented feature, you should not rely on it.")
  2471. (defcustom org-tags-column -77
  2472. "The column to which tags should be indented in a headline.
  2473. If this number is positive, it specifies the column. If it is negative,
  2474. it means that the tags should be flushright to that column. For example,
  2475. -80 works well for a normal 80 character screen.
  2476. When 0, place tags directly after headline text, with only one space in
  2477. between."
  2478. :group 'org-tags
  2479. :type 'integer)
  2480. (defcustom org-auto-align-tags t
  2481. "Non-nil keeps tags aligned when modifying headlines.
  2482. Some operations (i.e. demoting) change the length of a headline and
  2483. therefore shift the tags around. With this option turned on, after
  2484. each such operation the tags are again aligned to `org-tags-column'."
  2485. :group 'org-tags
  2486. :type 'boolean)
  2487. (defcustom org-use-tag-inheritance t
  2488. "Non-nil means tags in levels apply also for sublevels.
  2489. When nil, only the tags directly given in a specific line apply there.
  2490. This may also be a list of tags that should be inherited, or a regexp that
  2491. matches tags that should be inherited. Additional control is possible
  2492. with the variable `org-tags-exclude-from-inheritance' which gives an
  2493. explicit list of tags to be excluded from inheritance, even if the value of
  2494. `org-use-tag-inheritance' would select it for inheritance.
  2495. If this option is t, a match early-on in a tree can lead to a large
  2496. number of matches in the subtree when constructing the agenda or creating
  2497. a sparse tree. If you only want to see the first match in a tree during
  2498. a search, check out the variable `org-tags-match-list-sublevels'."
  2499. :group 'org-tags
  2500. :type '(choice
  2501. (const :tag "Not" nil)
  2502. (const :tag "Always" t)
  2503. (repeat :tag "Specific tags" (string :tag "Tag"))
  2504. (regexp :tag "Tags matched by regexp")))
  2505. (defcustom org-tags-exclude-from-inheritance nil
  2506. "List of tags that should never be inherited.
  2507. This is a way to exclude a few tags from inheritance. For way to do
  2508. the opposite, to actively allow inheritance for selected tags,
  2509. see the variable `org-use-tag-inheritance'."
  2510. :group 'org-tags
  2511. :type '(repeat (string :tag "Tag")))
  2512. (defun org-tag-inherit-p (tag)
  2513. "Check if TAG is one that should be inherited."
  2514. (cond
  2515. ((member tag org-tags-exclude-from-inheritance) nil)
  2516. ((eq org-use-tag-inheritance t) t)
  2517. ((not org-use-tag-inheritance) nil)
  2518. ((stringp org-use-tag-inheritance)
  2519. (string-match org-use-tag-inheritance tag))
  2520. ((listp org-use-tag-inheritance)
  2521. (member tag org-use-tag-inheritance))
  2522. (t (error "Invalid setting of `org-use-tag-inheritance'"))))
  2523. (defcustom org-tags-match-list-sublevels t
  2524. "Non-nil means list also sublevels of headlines matching a search.
  2525. This variable applies to tags/property searches, and also to stuck
  2526. projects because this search is based on a tags match as well.
  2527. When set to the symbol `indented', sublevels are indented with
  2528. leading dots.
  2529. Because of tag inheritance (see variable `org-use-tag-inheritance'),
  2530. the sublevels of a headline matching a tag search often also match
  2531. the same search. Listing all of them can create very long lists.
  2532. Setting this variable to nil causes subtrees of a match to be skipped.
  2533. This variable is semi-obsolete and probably should always be true. It
  2534. is better to limit inheritance to certain tags using the variables
  2535. `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
  2536. :group 'org-tags
  2537. :type '(choice
  2538. (const :tag "No, don't list them" nil)
  2539. (const :tag "Yes, do list them" t)
  2540. (const :tag "List them, indented with leading dots" indented)))
  2541. (defcustom org-tags-sort-function nil
  2542. "When set, tags are sorted using this function as a comparator."
  2543. :group 'org-tags
  2544. :type '(choice
  2545. (const :tag "No sorting" nil)
  2546. (const :tag "Alphabetical" string-collate-lessp)
  2547. (const :tag "Reverse alphabetical" org-string-collate-greaterp)
  2548. (function :tag "Custom function" nil)))
  2549. (defvar org-tags-history nil
  2550. "History of minibuffer reads for tags.")
  2551. (defvar org-last-tags-completion-table nil
  2552. "The last used completion table for tags.")
  2553. (defvar org-after-tags-change-hook nil
  2554. "Hook that is run after the tags in a line have changed.")
  2555. (defgroup org-properties nil
  2556. "Options concerning properties in Org mode."
  2557. :tag "Org Properties"
  2558. :group 'org)
  2559. (defcustom org-property-format "%-10s %s"
  2560. "How property key/value pairs should be formatted by `indent-line'.
  2561. When `indent-line' hits a property definition, it will format the line
  2562. according to this format, mainly to make sure that the values are
  2563. lined-up with respect to each other."
  2564. :group 'org-properties
  2565. :type 'string)
  2566. (defcustom org-properties-postprocess-alist nil
  2567. "Alist of properties and functions to adjust inserted values.
  2568. Elements of this alist must be of the form
  2569. ([string] [function])
  2570. where [string] must be a property name and [function] must be a
  2571. lambda expression: this lambda expression must take one argument,
  2572. the value to adjust, and return the new value as a string.
  2573. For example, this element will allow the property \"Remaining\"
  2574. to be updated wrt the relation between the \"Effort\" property
  2575. and the clock summary:
  2576. ((\"Remaining\" (lambda(value)
  2577. (let ((clocksum (org-clock-sum-current-item))
  2578. (effort (org-duration-to-minutes
  2579. (org-entry-get (point) \"Effort\"))))
  2580. (org-minutes-to-clocksum-string (- effort clocksum))))))"
  2581. :group 'org-properties
  2582. :version "24.1"
  2583. :type '(alist :key-type (string :tag "Property")
  2584. :value-type (function :tag "Function")))
  2585. (defcustom org-use-property-inheritance nil
  2586. "Non-nil means properties apply also for sublevels.
  2587. This setting is chiefly used during property searches. Turning it on can
  2588. cause significant overhead when doing a search, which is why it is not
  2589. on by default.
  2590. When nil, only the properties directly given in the current entry count.
  2591. When t, every property is inherited. The value may also be a list of
  2592. properties that should have inheritance, or a regular expression matching
  2593. properties that should be inherited.
  2594. However, note that some special properties use inheritance under special
  2595. circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
  2596. and the properties ending in \"_ALL\" when they are used as descriptor
  2597. for valid values of a property.
  2598. Note for programmers:
  2599. When querying an entry with `org-entry-get', you can control if inheritance
  2600. should be used. By default, `org-entry-get' looks only at the local
  2601. properties. You can request inheritance by setting the inherit argument
  2602. to t (to force inheritance) or to `selective' (to respect the setting
  2603. in this variable)."
  2604. :group 'org-properties
  2605. :type '(choice
  2606. (const :tag "Not" nil)
  2607. (const :tag "Always" t)
  2608. (repeat :tag "Specific properties" (string :tag "Property"))
  2609. (regexp :tag "Properties matched by regexp")))
  2610. (defun org-property-inherit-p (property)
  2611. "Return a non-nil value if PROPERTY should be inherited."
  2612. (cond
  2613. ((eq org-use-property-inheritance t) t)
  2614. ((not org-use-property-inheritance) nil)
  2615. ((stringp org-use-property-inheritance)
  2616. (string-match org-use-property-inheritance property))
  2617. ((listp org-use-property-inheritance)
  2618. (member-ignore-case property org-use-property-inheritance))
  2619. (t (error "Invalid setting of `org-use-property-inheritance'"))))
  2620. (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
  2621. "The default column format, if no other format has been defined.
  2622. This variable can be set on the per-file basis by inserting a line
  2623. #+COLUMNS: %25ITEM ....."
  2624. :group 'org-properties
  2625. :type 'string)
  2626. (defcustom org-columns-default-format-for-agenda nil
  2627. "The default column format in an agenda buffer.
  2628. This will be used for column view in the agenda unless a format has
  2629. been set by adding `org-overriding-columns-format' to the local
  2630. settings list of a custom agenda view. When nil, the columns format
  2631. for the first item in the agenda list will be used, or as a fall-back,
  2632. `org-columns-default-format'."
  2633. :group 'org-properties
  2634. :type '(choice
  2635. (const :tag "No default" nil)
  2636. (string :tag "Format string")))
  2637. (defcustom org-columns-ellipses ".."
  2638. "The ellipses to be used when a field in column view is truncated.
  2639. When this is the empty string, as many characters as possible are shown,
  2640. but then there will be no visual indication that the field has been truncated.
  2641. When this is a string of length N, the last N characters of a truncated
  2642. field are replaced by this string. If the column is narrower than the
  2643. ellipses string, only part of the ellipses string will be shown."
  2644. :group 'org-properties
  2645. :type 'string)
  2646. (defconst org-global-properties-fixed
  2647. '(("VISIBILITY_ALL" . "folded children content all")
  2648. ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
  2649. "List of property/value pairs that can be inherited by any entry.
  2650. These are fixed values, for the preset properties. The user variable
  2651. that can be used to add to this list is `org-global-properties'.
  2652. The entries in this list are cons cells where the car is a property
  2653. name and cdr is a string with the value. If the value represents
  2654. multiple items like an \"_ALL\" property, separate the items by
  2655. spaces.")
  2656. (defcustom org-global-properties nil
  2657. "List of property/value pairs that can be inherited by any entry.
  2658. This list will be combined with the constant `org-global-properties-fixed'.
  2659. The entries in this list are cons cells where the car is a property
  2660. name and cdr is a string with the value.
  2661. Buffer local properties are added either by a document property drawer
  2662. :PROPERTIES:
  2663. :NAME: VALUE
  2664. :END:
  2665. or by adding lines like
  2666. #+PROPERTY: NAME VALUE"
  2667. :group 'org-properties
  2668. :type '(repeat
  2669. (cons (string :tag "Property")
  2670. (string :tag "Value"))))
  2671. (defvar-local org-keyword-properties nil
  2672. "List of property/value pairs inherited by any entry.
  2673. Valid for the current buffer. This variable is populated from
  2674. PROPERTY keywords.
  2675. Note that properties are defined also in property drawers.
  2676. Properties defined there take precedence over properties defined
  2677. as keywords.")
  2678. (defgroup org-agenda nil
  2679. "Options concerning agenda views in Org mode."
  2680. :tag "Org Agenda"
  2681. :group 'org)
  2682. (defvar-local org-category nil
  2683. "Variable used by Org files to set a category for agenda display.
  2684. There are multiple ways to set the category. One way is to set
  2685. it in the document property drawer. For example:
  2686. :PROPERTIES:
  2687. :CATEGORY: ELisp
  2688. :END:
  2689. Other ways to define it is as an Emacs file variable, for example
  2690. # -*- mode: org; org-category: \"ELisp\"
  2691. or for the file to contain a special line:
  2692. #+CATEGORY: ELisp
  2693. If the file does not specify a category, then file's base name
  2694. is used instead.")
  2695. (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
  2696. (defcustom org-agenda-files nil
  2697. "The files to be used for agenda display.
  2698. If an entry is a directory, all files in that directory that are matched
  2699. by `org-agenda-file-regexp' will be part of the file list.
  2700. If the value of the variable is not a list but a single file name, then
  2701. the list of agenda files is actually stored and maintained in that file,
  2702. one agenda file per line. In this file paths can be given relative to
  2703. `org-directory'. Tilde expansion and environment variable substitution
  2704. are also made.
  2705. Entries may be added to this list with `\\[org-agenda-file-to-front]'
  2706. and removed with `\\[org-remove-file]'."
  2707. :group 'org-agenda
  2708. :type '(choice
  2709. (repeat :tag "List of files and directories" file)
  2710. (file :tag "Store list in a file\n" :value "~/.agenda_files")))
  2711. (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
  2712. "Regular expression to match files for `org-agenda-files'.
  2713. If any element in the list in that variable contains a directory instead
  2714. of a normal file, all files in that directory that are matched by this
  2715. regular expression will be included."
  2716. :group 'org-agenda
  2717. :type 'regexp)
  2718. (defvaralias 'org-agenda-multi-occur-extra-files
  2719. 'org-agenda-text-search-extra-files)
  2720. (defcustom org-agenda-text-search-extra-files nil
  2721. "List of extra files to be searched by text search commands.
  2722. These files will be searched in addition to the agenda files by the
  2723. commands `org-search-view' (`\\[org-agenda] s') \
  2724. and `org-occur-in-agenda-files'.
  2725. Note that these files will only be searched for text search commands,
  2726. not for the other agenda views like todo lists, tag searches or the weekly
  2727. agenda. This variable is intended to list notes and possibly archive files
  2728. that should also be searched by these two commands.
  2729. In fact, if the first element in the list is the symbol `agenda-archives',
  2730. then all archive files of all agenda files will be added to the search
  2731. scope."
  2732. :group 'org-agenda
  2733. :type '(set :greedy t
  2734. (const :tag "Agenda Archives" agenda-archives)
  2735. (repeat :inline t (file))))
  2736. (defcustom org-agenda-skip-unavailable-files nil
  2737. "Non-nil means to just skip non-reachable files in `org-agenda-files'.
  2738. A nil value means to remove them, after a query, from the list."
  2739. :group 'org-agenda
  2740. :type 'boolean)
  2741. (defgroup org-latex nil
  2742. "Options for embedding LaTeX code into Org mode."
  2743. :tag "Org LaTeX"
  2744. :group 'org)
  2745. (defcustom org-format-latex-options
  2746. '(:foreground default :background default :scale 1.0
  2747. :html-foreground "Black" :html-background "Transparent"
  2748. :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
  2749. "Options for creating images from LaTeX fragments.
  2750. This is a property list with the following properties:
  2751. :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
  2752. `default' means use the foreground of the default face.
  2753. `auto' means use the foreground from the text face.
  2754. :background the background color, or \"Transparent\".
  2755. `default' means use the background of the default face.
  2756. `auto' means use the background from the text face.
  2757. :scale a scaling factor for the size of the images, to get more pixels
  2758. :html-foreground, :html-background, :html-scale
  2759. the same numbers for HTML export.
  2760. :matchers a list indicating which matchers should be used to
  2761. find LaTeX fragments. Valid members of this list are:
  2762. \"begin\" find environments
  2763. \"$1\" find single characters surrounded by $.$
  2764. \"$\" find math expressions surrounded by $...$
  2765. \"$$\" find math expressions surrounded by $$....$$
  2766. \"\\(\" find math expressions surrounded by \\(...\\)
  2767. \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
  2768. :group 'org-latex
  2769. :type 'plist)
  2770. (defcustom org-format-latex-signal-error t
  2771. "Non-nil means signal an error when image creation of LaTeX snippets fails.
  2772. When nil, just push out a message."
  2773. :group 'org-latex
  2774. :version "24.1"
  2775. :type 'boolean)
  2776. (defcustom org-latex-to-mathml-jar-file nil
  2777. "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
  2778. Use this to specify additional executable file say a jar file.
  2779. When using MathToWeb as the converter, specify the full-path to
  2780. your mathtoweb.jar file."
  2781. :group 'org-latex
  2782. :version "24.1"
  2783. :type '(choice
  2784. (const :tag "None" nil)
  2785. (file :tag "JAR file" :must-match t)))
  2786. (defcustom org-latex-to-mathml-convert-command nil
  2787. "Command to convert LaTeX fragments to MathML.
  2788. Replace format-specifiers in the command as noted below and use
  2789. `shell-command' to convert LaTeX to MathML.
  2790. %j: Executable file in fully expanded form as specified by
  2791. `org-latex-to-mathml-jar-file'.
  2792. %I: Input LaTeX file in fully expanded form.
  2793. %i: The latex fragment to be converted.
  2794. %o: Output MathML file.
  2795. This command is used by `org-create-math-formula'.
  2796. When using MathToWeb as the converter, set this option to
  2797. \"java -jar %j -unicode -force -df %o %I\".
  2798. When using LaTeXML set this option to
  2799. \"latexmlmath \"%i\" --presentationmathml=%o\"."
  2800. :group 'org-latex
  2801. :version "24.1"
  2802. :type '(choice
  2803. (const :tag "None" nil)
  2804. (string :tag "\nShell command")))
  2805. (defcustom org-latex-to-html-convert-command nil
  2806. "Command to convert LaTeX fragments to HTML.
  2807. This command is very open-ended: the output of the command will
  2808. directly replace the LaTeX fragment in the resulting HTML.
  2809. Replace format-specifiers in the command as noted below and use
  2810. `shell-command' to convert LaTeX to HTML.
  2811. %i: The LaTeX fragment to be converted.
  2812. For example, this could be used with LaTeXML as
  2813. \"latexmlc 'literal:%i' --profile=math --preload=siunitx.sty 2>/dev/null\"."
  2814. :group 'org-latex
  2815. :package-version '(Org . "9.4")
  2816. :type '(choice
  2817. (const :tag "None" nil)
  2818. (string :tag "Shell command")))
  2819. (defcustom org-preview-latex-default-process 'dvipng
  2820. "The default process to convert LaTeX fragments to image files.
  2821. All available processes and theirs documents can be found in
  2822. `org-preview-latex-process-alist', which see."
  2823. :group 'org-latex
  2824. :version "26.1"
  2825. :package-version '(Org . "9.0")
  2826. :type 'symbol)
  2827. (defcustom org-preview-latex-process-alist
  2828. '((dvipng
  2829. :programs ("latex" "dvipng")
  2830. :description "dvi > png"
  2831. :message "you need to install the programs: latex and dvipng."
  2832. :image-input-type "dvi"
  2833. :image-output-type "png"
  2834. :image-size-adjust (1.0 . 1.0)
  2835. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2836. :image-converter ("dvipng -D %D -T tight -o %O %f")
  2837. :transparent-image-converter
  2838. ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
  2839. (dvisvgm
  2840. :programs ("latex" "dvisvgm")
  2841. :description "dvi > svg"
  2842. :message "you need to install the programs: latex and dvisvgm."
  2843. :image-input-type "dvi"
  2844. :image-output-type "svg"
  2845. :image-size-adjust (1.7 . 1.5)
  2846. :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
  2847. :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
  2848. (imagemagick
  2849. :programs ("latex" "convert")
  2850. :description "pdf > png"
  2851. :message "you need to install the programs: latex and imagemagick."
  2852. :image-input-type "pdf"
  2853. :image-output-type "png"
  2854. :image-size-adjust (1.0 . 1.0)
  2855. :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
  2856. :image-converter
  2857. ("convert -density %D -trim -antialias %f -quality 100 %O")))
  2858. "Definitions of external processes for LaTeX previewing.
  2859. Org mode can use some external commands to generate TeX snippet's images for
  2860. previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
  2861. `org-create-formula-image' how to call them.
  2862. The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
  2863. PROPERTIES accepts the following attributes:
  2864. :programs list of strings, required programs.
  2865. :description string, describe the process.
  2866. :message string, message it when required programs cannot be found.
  2867. :image-input-type string, input file type of image converter (e.g., \"dvi\").
  2868. :image-output-type string, output file type of image converter (e.g., \"png\").
  2869. :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
  2870. image size showed in buffer and the cdr element is for
  2871. HTML file. This option is only useful for process
  2872. developers, users should use variable
  2873. `org-format-latex-options' instead.
  2874. :post-clean list of strings, files matched are to be cleaned up once
  2875. the image is generated. When nil, the files with \".dvi\",
  2876. \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
  2877. \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
  2878. be cleaned up.
  2879. :latex-header list of strings, the LaTeX header of the snippet file.
  2880. When nil, the fallback value is used instead, which is
  2881. controlled by `org-format-latex-header',
  2882. `org-latex-default-packages-alist' and
  2883. `org-latex-packages-alist', which see.
  2884. :latex-compiler list of LaTeX commands, as strings. Each of them is given
  2885. to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
  2886. replaced with values defined below.
  2887. :image-converter list of image converter commands strings. Each of them is
  2888. given to the shell and supports any of the following
  2889. place-holders defined below.
  2890. If set, :transparent-image-converter is used instead of :image-converter to
  2891. convert an image when the background color is nil or \"Transparent\".
  2892. Place-holders used by `:image-converter' and `:latex-compiler':
  2893. %f input file name
  2894. %b base name of input file
  2895. %o base directory of input file
  2896. %O absolute output file name
  2897. Place-holders only used by `:image-converter':
  2898. %D dpi, which is used to adjust image size by some processing commands.
  2899. %S the image size scale ratio, which is used to adjust image size by some
  2900. processing commands."
  2901. :group 'org-latex
  2902. :version "26.1"
  2903. :package-version '(Org . "9.0")
  2904. :type '(alist :tag "LaTeX to image backends"
  2905. :value-type (plist)))
  2906. (defcustom org-preview-latex-image-directory "ltximg/"
  2907. "Path to store latex preview images.
  2908. A relative path here creates many directories relative to the
  2909. processed Org files paths. An absolute path puts all preview
  2910. images at the same place."
  2911. :group 'org-latex
  2912. :version "26.1"
  2913. :package-version '(Org . "9.0")
  2914. :type 'string)
  2915. (defun org-format-latex-mathml-available-p ()
  2916. "Return t if `org-latex-to-mathml-convert-command' is usable."
  2917. (save-match-data
  2918. (when (and (boundp 'org-latex-to-mathml-convert-command)
  2919. org-latex-to-mathml-convert-command)
  2920. (let ((executable (car (split-string
  2921. org-latex-to-mathml-convert-command))))
  2922. (when (executable-find executable)
  2923. (if (string-match
  2924. "%j" org-latex-to-mathml-convert-command)
  2925. (file-readable-p org-latex-to-mathml-jar-file)
  2926. t))))))
  2927. (defcustom org-format-latex-header "\\documentclass{article}
  2928. \\usepackage[usenames]{color}
  2929. \[PACKAGES]
  2930. \[DEFAULT-PACKAGES]
  2931. \\pagestyle{empty} % do not remove
  2932. % The settings below are copied from fullpage.sty
  2933. \\setlength{\\textwidth}{\\paperwidth}
  2934. \\addtolength{\\textwidth}{-3cm}
  2935. \\setlength{\\oddsidemargin}{1.5cm}
  2936. \\addtolength{\\oddsidemargin}{-2.54cm}
  2937. \\setlength{\\evensidemargin}{\\oddsidemargin}
  2938. \\setlength{\\textheight}{\\paperheight}
  2939. \\addtolength{\\textheight}{-\\headheight}
  2940. \\addtolength{\\textheight}{-\\headsep}
  2941. \\addtolength{\\textheight}{-\\footskip}
  2942. \\addtolength{\\textheight}{-3cm}
  2943. \\setlength{\\topmargin}{1.5cm}
  2944. \\addtolength{\\topmargin}{-2.54cm}"
  2945. "The document header used for processing LaTeX fragments.
  2946. It is imperative that this header make sure that no page number
  2947. appears on the page. The package defined in the variables
  2948. `org-latex-default-packages-alist' and `org-latex-packages-alist'
  2949. will either replace the placeholder \"[PACKAGES]\" in this
  2950. header, or they will be appended."
  2951. :group 'org-latex
  2952. :type 'string)
  2953. (defun org-set-packages-alist (var val)
  2954. "Set the packages alist and make sure it has 3 elements per entry."
  2955. (set var (mapcar (lambda (x)
  2956. (if (and (consp x) (= (length x) 2))
  2957. (list (car x) (nth 1 x) t)
  2958. x))
  2959. val)))
  2960. (defun org-get-packages-alist (var)
  2961. "Get the packages alist and make sure it has 3 elements per entry."
  2962. (mapcar (lambda (x)
  2963. (if (and (consp x) (= (length x) 2))
  2964. (list (car x) (nth 1 x) t)
  2965. x))
  2966. (default-value var)))
  2967. (defcustom org-latex-default-packages-alist
  2968. '(("AUTO" "inputenc" t ("pdflatex"))
  2969. ("T1" "fontenc" t ("pdflatex"))
  2970. ("" "graphicx" t)
  2971. ("" "longtable" nil)
  2972. ("" "wrapfig" nil)
  2973. ("" "rotating" nil)
  2974. ("normalem" "ulem" t)
  2975. ("" "amsmath" t)
  2976. ("" "amssymb" t)
  2977. ("" "capt-of" nil)
  2978. ("" "hyperref" nil))
  2979. "Alist of default packages to be inserted in the header.
  2980. Change this only if one of the packages here causes an
  2981. incompatibility with another package you are using.
  2982. The packages in this list are needed by one part or another of
  2983. Org mode to function properly:
  2984. - inputenc, fontenc: for basic font and character selection
  2985. - graphicx: for including images
  2986. - longtable: For multipage tables
  2987. - wrapfig: for figure placement
  2988. - rotating: for sideways figures and tables
  2989. - ulem: for underline and strike-through
  2990. - amsmath: for subscript and superscript and math environments
  2991. - amssymb: for various symbols used for interpreting the entities
  2992. in `org-entities'. You can skip some of this package if you don't
  2993. use any of the symbols.
  2994. - capt-of: for captions outside of floats
  2995. - hyperref: for cross references
  2996. Therefore you should not modify this variable unless you know
  2997. what you are doing. The one reason to change it anyway is that
  2998. you might be loading some other package that conflicts with one
  2999. of the default packages. Each element is either a cell or
  3000. a string.
  3001. A cell is of the format
  3002. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3003. If SNIPPET-FLAG is non-nil, the package also needs to be included
  3004. when compiling LaTeX snippets into images for inclusion into
  3005. non-LaTeX output.
  3006. COMPILERS is a list of compilers that should include the package,
  3007. see `org-latex-compiler'. If the document compiler is not in the
  3008. list, and the list is non-nil, the package will not be inserted
  3009. in the final document.
  3010. A string will be inserted as-is in the header of the document."
  3011. :group 'org-latex
  3012. :group 'org-export-latex
  3013. :set 'org-set-packages-alist
  3014. :get 'org-get-packages-alist
  3015. :version "26.1"
  3016. :package-version '(Org . "8.3")
  3017. :type '(repeat
  3018. (choice
  3019. (list :tag "options/package pair"
  3020. (string :tag "options")
  3021. (string :tag "package")
  3022. (boolean :tag "Snippet")
  3023. (choice
  3024. (const :tag "For all compilers" nil)
  3025. (repeat :tag "Allowed compiler" string)))
  3026. (string :tag "A line of LaTeX"))))
  3027. (defcustom org-latex-packages-alist nil
  3028. "Alist of packages to be inserted in every LaTeX header.
  3029. These will be inserted after `org-latex-default-packages-alist'.
  3030. Each element is either a cell or a string.
  3031. A cell is of the format:
  3032. (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
  3033. SNIPPET-FLAG, when non-nil, indicates that this package is also
  3034. needed when turning LaTeX snippets into images for inclusion into
  3035. non-LaTeX output.
  3036. COMPILERS is a list of compilers that should include the package,
  3037. see `org-latex-compiler'. If the document compiler is not in the
  3038. list, and the list is non-nil, the package will not be inserted
  3039. in the final document.
  3040. A string will be inserted as-is in the header of the document.
  3041. Make sure that you only list packages here which:
  3042. - you want in every file;
  3043. - do not conflict with the setup in `org-format-latex-header';
  3044. - do not conflict with the default packages in
  3045. `org-latex-default-packages-alist'."
  3046. :group 'org-latex
  3047. :group 'org-export-latex
  3048. :set 'org-set-packages-alist
  3049. :get 'org-get-packages-alist
  3050. :type '(repeat
  3051. (choice
  3052. (list :tag "options/package pair"
  3053. (string :tag "options")
  3054. (string :tag "package")
  3055. (boolean :tag "Snippet"))
  3056. (string :tag "A line of LaTeX"))))
  3057. (defgroup org-appearance nil
  3058. "Settings for Org mode appearance."
  3059. :tag "Org Appearance"
  3060. :group 'org)
  3061. (defcustom org-level-color-stars-only nil
  3062. "Non-nil means fontify only the stars in each headline.
  3063. When nil, the entire headline is fontified.
  3064. Changing it requires restart of `font-lock-mode' to become effective
  3065. also in regions already fontified."
  3066. :group 'org-appearance
  3067. :type 'boolean)
  3068. (defcustom org-hide-leading-stars nil
  3069. "Non-nil means hide the first N-1 stars in a headline.
  3070. This works by using the face `org-hide' for these stars. This
  3071. face is white for a light background, and black for a dark
  3072. background. You may have to customize the face `org-hide' to
  3073. make this work.
  3074. Changing it requires restart of `font-lock-mode' to become effective
  3075. also in regions already fontified.
  3076. You may also set this on a per-file basis by adding one of the following
  3077. lines to the buffer:
  3078. #+STARTUP: hidestars
  3079. #+STARTUP: showstars"
  3080. :group 'org-appearance
  3081. :type 'boolean)
  3082. (defcustom org-hidden-keywords nil
  3083. "List of symbols corresponding to keywords to be hidden in the Org buffer.
  3084. For example, a value \\='(title) for this list makes the document's title
  3085. appear in the buffer without the initial \"#+TITLE:\" part."
  3086. :group 'org-appearance
  3087. :package-version '(Org . "9.5")
  3088. :type '(set (const :tag "#+AUTHOR" author)
  3089. (const :tag "#+DATE" date)
  3090. (const :tag "#+EMAIL" email)
  3091. (const :tag "#+SUBTITLE" subtitle)
  3092. (const :tag "#+TITLE" title)))
  3093. (defcustom org-custom-properties nil
  3094. "List of properties (as strings) with a special meaning.
  3095. The default use of these custom properties is to let the user
  3096. hide them with `org-toggle-custom-properties-visibility'."
  3097. :group 'org-properties
  3098. :group 'org-appearance
  3099. :version "24.3"
  3100. :type '(repeat (string :tag "Property Name")))
  3101. (defcustom org-fontify-todo-headline nil
  3102. "Non-nil means change the face of a headline if it is marked as TODO.
  3103. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3104. When this is non-nil, the headline after the keyword is set to the
  3105. `org-headline-todo' as an additional indication."
  3106. :group 'org-appearance
  3107. :package-version '(Org . "9.4")
  3108. :type 'boolean
  3109. :safe #'booleanp)
  3110. (defcustom org-fontify-done-headline t
  3111. "Non-nil means change the face of a headline if it is marked DONE.
  3112. Normally, only the TODO/DONE keyword indicates the state of a headline.
  3113. When this is non-nil, the headline after the keyword is set to the
  3114. `org-headline-done' as an additional indication."
  3115. :group 'org-appearance
  3116. :package-version '(Org . "9.4")
  3117. :type 'boolean)
  3118. (defcustom org-fontify-emphasized-text t
  3119. "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
  3120. Changing this variable requires a restart of Emacs to take effect."
  3121. :group 'org-appearance
  3122. :type 'boolean)
  3123. (defcustom org-fontify-whole-heading-line nil
  3124. "Non-nil means fontify the whole line for headings.
  3125. This is useful when setting a background color for the
  3126. org-level-* faces."
  3127. :group 'org-appearance
  3128. :type 'boolean)
  3129. (defcustom org-fontify-whole-block-delimiter-line t
  3130. "Non-nil means fontify the whole line for begin/end lines of blocks.
  3131. This is useful when setting a background color for the
  3132. org-block-begin-line and org-block-end-line faces."
  3133. :group 'org-appearance
  3134. :type 'boolean)
  3135. (defcustom org-highlight-latex-and-related nil
  3136. "Non-nil means highlight LaTeX related syntax in the buffer.
  3137. When non-nil, the value should be a list containing any of the
  3138. following symbols:
  3139. `native' Highlight LaTeX snippets and environments natively.
  3140. `latex' Highlight LaTeX snippets and environments.
  3141. `script' Highlight subscript and superscript.
  3142. `entities' Highlight entities."
  3143. :group 'org-appearance
  3144. :version "24.4"
  3145. :package-version '(Org . "8.0")
  3146. :type '(choice
  3147. (const :tag "No highlighting" nil)
  3148. (set :greedy t :tag "Highlight"
  3149. (const :tag "LaTeX snippets and environments (native)" native)
  3150. (const :tag "LaTeX snippets and environments" latex)
  3151. (const :tag "Subscript and superscript" script)
  3152. (const :tag "Entities" entities))))
  3153. (defcustom org-hide-emphasis-markers nil
  3154. "Non-nil mean font-lock should hide the emphasis marker characters."
  3155. :group 'org-appearance
  3156. :type 'boolean
  3157. :safe #'booleanp)
  3158. (defcustom org-hide-macro-markers nil
  3159. "Non-nil mean font-lock should hide the brackets marking macro calls."
  3160. :group 'org-appearance
  3161. :type 'boolean)
  3162. (defcustom org-pretty-entities nil
  3163. "Non-nil means show entities as UTF8 characters.
  3164. When nil, the \\name form remains in the buffer."
  3165. :group 'org-appearance
  3166. :version "24.1"
  3167. :type 'boolean)
  3168. (defcustom org-pretty-entities-include-sub-superscripts t
  3169. "Non-nil means, pretty entity display includes formatting sub/superscripts."
  3170. :group 'org-appearance
  3171. :version "24.1"
  3172. :type 'boolean)
  3173. (defvar org-emph-re nil
  3174. "Regular expression for matching emphasis.
  3175. After a match, the match groups contain these elements:
  3176. 0 The match of the full regular expression, including the characters
  3177. before and after the proper match
  3178. 1 The character before the proper match, or empty at beginning of line
  3179. 2 The proper match, including the leading and trailing markers
  3180. 3 The leading marker like * or /, indicating the type of highlighting
  3181. 4 The text between the emphasis markers, not including the markers
  3182. 5 The character after the match, empty at the end of a line")
  3183. (defvar org-verbatim-re nil
  3184. "Regular expression for matching verbatim text.")
  3185. (defvar org-emphasis-regexp-components) ; defined just below
  3186. (defvar org-emphasis-alist) ; defined just below
  3187. (defun org-set-emph-re (var val)
  3188. "Set variable and compute the emphasis regular expression."
  3189. (set var val)
  3190. (when (and (boundp 'org-emphasis-alist)
  3191. (boundp 'org-emphasis-regexp-components)
  3192. org-emphasis-alist org-emphasis-regexp-components)
  3193. (pcase-let*
  3194. ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
  3195. (body (if (<= nl 0) body
  3196. (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
  3197. (template
  3198. (format (concat "\\([%s]\\|^\\)" ;before markers
  3199. "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
  3200. "\\([%s]\\|$\\)") ;after markers
  3201. pre border border body border post)))
  3202. (setq org-emph-re (format template "*/_+"))
  3203. (setq org-verbatim-re (format template "=~")))))
  3204. ;; This used to be a defcustom (Org <8.0) but allowing the users to
  3205. ;; set this option proved cumbersome. See this message/thread:
  3206. ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
  3207. (defvar org-emphasis-regexp-components
  3208. '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
  3209. "Components used to build the regular expression for emphasis.
  3210. This is a list with five entries. Terminology: In an emphasis string
  3211. like \" *strong word* \", we call the initial space PREMATCH, the final
  3212. space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
  3213. and \"trong wor\" is the body. The different components in this variable
  3214. specify what is allowed/forbidden in each part:
  3215. pre Chars allowed as prematch. Beginning of line will be allowed too.
  3216. post Chars allowed as postmatch. End of line will be allowed too.
  3217. border The chars *forbidden* as border characters.
  3218. body-regexp A regexp like \".\" to match a body character. Don't use
  3219. non-shy groups here, and don't allow newline here.
  3220. newline The maximum number of newlines allowed in an emphasis exp.
  3221. You need to reload Org or to restart Emacs after setting this.")
  3222. (defcustom org-emphasis-alist
  3223. '(("*" bold)
  3224. ("/" italic)
  3225. ("_" underline)
  3226. ("=" org-verbatim verbatim)
  3227. ("~" org-code verbatim)
  3228. ("+" (:strike-through t)))
  3229. "Alist of characters and faces to emphasize text.
  3230. Text starting and ending with a special character will be emphasized,
  3231. for example *bold*, _underlined_ and /italic/. This variable sets the
  3232. marker characters and the face to be used by font-lock for highlighting
  3233. in Org buffers.
  3234. You need to reload Org or to restart Emacs after customizing this."
  3235. :group 'org-appearance
  3236. :set 'org-set-emph-re
  3237. :version "24.4"
  3238. :package-version '(Org . "8.0")
  3239. :type '(repeat
  3240. (list
  3241. (string :tag "Marker character")
  3242. (choice
  3243. (face :tag "Font-lock-face")
  3244. (plist :tag "Face property list"))
  3245. (option (const verbatim)))))
  3246. (defvar org-protecting-blocks '("src" "example" "export")
  3247. "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
  3248. This is needed for font-lock setup.")
  3249. ;;; Functions and variables from their packages
  3250. ;; Declared here to avoid compiler warnings
  3251. (defvar mark-active)
  3252. ;; Various packages
  3253. (declare-function calc-eval "calc" (str &optional separator &rest args))
  3254. (declare-function calendar-forward-day "cal-move" (arg))
  3255. (declare-function calendar-goto-date "cal-move" (date))
  3256. (declare-function calendar-goto-today "cal-move" ())
  3257. (declare-function calendar-iso-from-absolute "cal-iso" (date))
  3258. (declare-function calendar-iso-to-absolute "cal-iso" (date))
  3259. (declare-function cdlatex-compute-tables "ext:cdlatex" ())
  3260. (declare-function cdlatex-tab "ext:cdlatex" ())
  3261. (declare-function dired-get-filename
  3262. "dired"
  3263. (&optional localp no-error-if-not-filep))
  3264. (declare-function iswitchb-read-buffer
  3265. "iswitchb"
  3266. (prompt &optional
  3267. default require-match _predicate start matches-set))
  3268. (declare-function org-agenda-change-all-lines
  3269. "org-agenda"
  3270. (newhead hdmarker &optional fixface just-this))
  3271. (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
  3272. "org-agenda"
  3273. (&optional end))
  3274. (declare-function org-agenda-copy-local-variable "org-agenda" (var))
  3275. (declare-function org-agenda-format-item
  3276. "org-agenda"
  3277. (extra txt &optional level category tags dotime
  3278. remove-re habitp))
  3279. (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
  3280. (declare-function org-agenda-save-markers-for-cut-and-paste
  3281. "org-agenda"
  3282. (beg end))
  3283. (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
  3284. (declare-function org-agenda-skip "org-agenda" ())
  3285. (declare-function org-attach-expand "org-attach" (file))
  3286. (declare-function org-attach-reveal "org-attach" ())
  3287. (declare-function org-attach-reveal-in-emacs "org-attach" ())
  3288. (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
  3289. (declare-function org-indent-mode "org-indent" (&optional arg))
  3290. (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
  3291. (declare-function org-inlinetask-goto-end "org-inlinetask" ())
  3292. (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
  3293. (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
  3294. (declare-function parse-time-string "parse-time" (string))
  3295. (defvar align-mode-rules-list)
  3296. (defvar calc-embedded-close-formula)
  3297. (defvar calc-embedded-open-formula)
  3298. (defvar calc-embedded-open-mode)
  3299. (defvar font-lock-unfontify-region-function)
  3300. (defvar iswitchb-temp-buflist)
  3301. (defvar org-agenda-tags-todo-honor-ignore-options)
  3302. (defvar remember-data-file)
  3303. (defvar texmathp-why)
  3304. (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
  3305. (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
  3306. (declare-function org-resolve-clocks "org-clock"
  3307. (&optional also-non-dangling-p prompt last-valid))
  3308. (defvar org-clock-start-time)
  3309. (defvar org-clock-marker (make-marker)
  3310. "Marker recording the last clock-in.")
  3311. (defvar org-clock-hd-marker (make-marker)
  3312. "Marker recording the last clock-in, but the headline position.")
  3313. (defvar org-clock-heading ""
  3314. "The heading of the current clock entry.")
  3315. (defun org-clocking-buffer ()
  3316. "Return the buffer where the clock is currently running.
  3317. Return nil if no clock is running."
  3318. (marker-buffer org-clock-marker))
  3319. (defalias 'org-clock-is-active #'org-clocking-buffer)
  3320. (defun org-check-running-clock ()
  3321. "Check if the current buffer contains the running clock.
  3322. If yes, offer to stop it and to save the buffer with the changes."
  3323. (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
  3324. (y-or-n-p (format "Clock-out in buffer %s before killing it? "
  3325. (buffer-name))))
  3326. (org-clock-out)
  3327. (when (y-or-n-p "Save changed buffer?")
  3328. (save-buffer))))
  3329. (defun org-clocktable-try-shift (dir n)
  3330. "Check if this line starts a clock table, if yes, shift the time block."
  3331. (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
  3332. (org-clocktable-shift dir n)))
  3333. ;;;###autoload
  3334. (defun org-clock-persistence-insinuate ()
  3335. "Set up hooks for clock persistence."
  3336. (require 'org-clock)
  3337. (add-hook 'org-mode-hook 'org-clock-load)
  3338. (add-hook 'kill-emacs-hook 'org-clock-save))
  3339. (defun org-clock-auto-clockout-insinuate ()
  3340. "Set up hook for auto clocking out when Emacs is idle.
  3341. See `org-clock-auto-clockout-timer'.
  3342. This function is meant to be added to the user configuration."
  3343. (require 'org-clock)
  3344. (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
  3345. (defgroup org-archive nil
  3346. "Options concerning archiving in Org mode."
  3347. :tag "Org Archive"
  3348. :group 'org-structure)
  3349. (defcustom org-archive-location "%s_archive::"
  3350. "The location where subtrees should be archived.
  3351. The value of this variable is a string, consisting of two parts,
  3352. separated by a double-colon. The first part is a filename and
  3353. the second part is a headline.
  3354. When the filename is omitted, archiving happens in the same file.
  3355. %s in the filename will be replaced by the current file
  3356. name (without the directory part). Archiving to a different file
  3357. is useful to keep archived entries from contributing to the
  3358. Org Agenda.
  3359. The archived entries will be filed as subtrees of the specified
  3360. headline. When the headline is omitted, the subtrees are simply
  3361. filed away at the end of the file, as top-level entries. Also in
  3362. the heading you can use %s to represent the file name, this can be
  3363. useful when using the same archive for a number of different files.
  3364. Here are a few examples:
  3365. \"%s_archive::\"
  3366. If the current file is Projects.org, archive in file
  3367. Projects.org_archive, as top-level trees. This is the default.
  3368. \"::* Archived Tasks\"
  3369. Archive in the current file, under the top-level headline
  3370. \"* Archived Tasks\".
  3371. \"~/org/archive.org::\"
  3372. Archive in file ~/org/archive.org (absolute path), as top-level trees.
  3373. \"~/org/archive.org::* From %s\"
  3374. Archive in file ~/org/archive.org (absolute path), under headlines
  3375. \"From FILENAME\" where file name is the current file name.
  3376. \"~/org/datetree.org::datetree/* Finished Tasks\"
  3377. The \"datetree/\" string is special, signifying to archive
  3378. items to the datetree. Items are placed in either the CLOSED
  3379. date of the item, or the current date if there is no CLOSED date.
  3380. The heading will be a subentry to the current date. There doesn't
  3381. need to be a heading, but there always needs to be a slash after
  3382. datetree. For example, to store archived items directly in the
  3383. datetree, use \"~/org/datetree.org::datetree/\".
  3384. \"basement::** Finished Tasks\"
  3385. Archive in file ./basement (relative path), as level 3 trees
  3386. below the level 2 heading \"** Finished Tasks\".
  3387. You may define it locally by setting an ARCHIVE property. If
  3388. such a property is found in the file or in an entry, and anywhere
  3389. up the hierarchy, it will be used.
  3390. You can also set it for the whole file using the keyword-syntax:
  3391. #+ARCHIVE: basement::** Finished Tasks"
  3392. :group 'org-archive
  3393. :type 'string)
  3394. (defcustom org-agenda-skip-archived-trees t
  3395. "Non-nil means the agenda will skip any items located in archived trees.
  3396. An archived tree is a tree marked with the tag ARCHIVE. The use of this
  3397. variable is no longer recommended, you should leave it at the value t.
  3398. Instead, use the key `v' to cycle the archives-mode in the agenda."
  3399. :group 'org-archive
  3400. :group 'org-agenda-skip
  3401. :type 'boolean)
  3402. (defcustom org-columns-skip-archived-trees t
  3403. "Non-nil means ignore archived trees when creating column view."
  3404. :group 'org-archive
  3405. :group 'org-properties
  3406. :type 'boolean)
  3407. (defcustom org-cycle-open-archived-trees nil
  3408. "Non-nil means `org-cycle' will open archived trees.
  3409. An archived tree is a tree marked with the tag ARCHIVE.
  3410. When nil, archived trees will stay folded. You can still open them with
  3411. normal outline commands like `show-all', but not with the cycling commands."
  3412. :group 'org-archive
  3413. :group 'org-cycle
  3414. :type 'boolean)
  3415. (defcustom org-sparse-tree-open-archived-trees nil
  3416. "Non-nil means sparse tree construction shows matches in archived trees.
  3417. When nil, matches in these trees are highlighted, but the trees are kept in
  3418. collapsed state."
  3419. :group 'org-archive
  3420. :group 'org-sparse-trees
  3421. :type 'boolean)
  3422. (defcustom org-sparse-tree-default-date-type nil
  3423. "The default date type when building a sparse tree.
  3424. When this is nil, a date is a scheduled or a deadline timestamp.
  3425. Otherwise, these types are allowed:
  3426. all: all timestamps
  3427. active: only active timestamps (<...>)
  3428. inactive: only inactive timestamps ([...])
  3429. scheduled: only scheduled timestamps
  3430. deadline: only deadline timestamps"
  3431. :type '(choice (const :tag "Scheduled or deadline" nil)
  3432. (const :tag "All timestamps" all)
  3433. (const :tag "Only active timestamps" active)
  3434. (const :tag "Only inactive timestamps" inactive)
  3435. (const :tag "Only scheduled timestamps" scheduled)
  3436. (const :tag "Only deadline timestamps" deadline)
  3437. (const :tag "Only closed timestamps" closed))
  3438. :version "26.1"
  3439. :package-version '(Org . "8.3")
  3440. :group 'org-sparse-trees)
  3441. (defun org-cycle-hide-archived-subtrees (state)
  3442. "Re-hide all archived subtrees after a visibility state change.
  3443. STATE should be one of the symbols listed in the docstring of
  3444. `org-cycle-hook'."
  3445. (when (and (not org-cycle-open-archived-trees)
  3446. (not (memq state '(overview folded))))
  3447. (save-excursion
  3448. (let* ((globalp (memq state '(contents all)))
  3449. (beg (if globalp (point-min) (point)))
  3450. (end (if globalp (point-max) (org-end-of-subtree t))))
  3451. (org-hide-archived-subtrees beg end)
  3452. (goto-char beg)
  3453. (when (looking-at-p (concat ".*:" org-archive-tag ":"))
  3454. (message "%s" (substitute-command-keys
  3455. "Subtree is archived and stays closed. Use \
  3456. `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
  3457. (defun org-force-cycle-archived ()
  3458. "Cycle subtree even if it is archived."
  3459. (interactive)
  3460. (setq this-command 'org-cycle)
  3461. (let ((org-cycle-open-archived-trees t))
  3462. (call-interactively 'org-cycle)))
  3463. (defun org-hide-archived-subtrees (beg end)
  3464. "Re-hide all archived subtrees after a visibility state change."
  3465. (org-with-wide-buffer
  3466. (let ((case-fold-search nil)
  3467. (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
  3468. (goto-char beg)
  3469. ;; Include headline point is currently on.
  3470. (beginning-of-line)
  3471. (while (and (< (point) end) (re-search-forward re end t))
  3472. (when (member org-archive-tag (org-get-tags nil t))
  3473. (org-flag-subtree t)
  3474. (org-end-of-subtree t))))))
  3475. (defun org-flag-subtree (flag)
  3476. (save-excursion
  3477. (org-back-to-heading t)
  3478. (org-flag-region (line-end-position)
  3479. (progn (org-end-of-subtree t) (point))
  3480. flag
  3481. 'outline)))
  3482. (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
  3483. ;; Declare Column View Code
  3484. (declare-function org-columns-get-format-and-top-level "org-colview" ())
  3485. (declare-function org-columns-compute "org-colview" (property))
  3486. ;; Declare ID code
  3487. (declare-function org-id-store-link "org-id")
  3488. (declare-function org-id-locations-load "org-id")
  3489. (declare-function org-id-locations-save "org-id")
  3490. (defvar org-id-track-globally)
  3491. ;;; Variables for pre-computed regular expressions, all buffer local
  3492. (defvar-local org-todo-regexp nil
  3493. "Matches any of the TODO state keywords.
  3494. Since TODO keywords are case-sensitive, `case-fold-search' is
  3495. expected to be bound to nil when matching against this regexp.")
  3496. (defvar-local org-not-done-regexp nil
  3497. "Matches any of the TODO state keywords except the last one.
  3498. Since TODO keywords are case-sensitive, `case-fold-search' is
  3499. expected to be bound to nil when matching against this regexp.")
  3500. (defvar-local org-not-done-heading-regexp nil
  3501. "Matches a TODO headline that is not done.
  3502. Since TODO keywords are case-sensitive, `case-fold-search' is
  3503. expected to be bound to nil when matching against this regexp.")
  3504. (defvar-local org-todo-line-regexp nil
  3505. "Matches a headline and puts TODO state into group 2 if present.
  3506. Since TODO keywords are case-sensitive, `case-fold-search' is
  3507. expected to be bound to nil when matching against this regexp.")
  3508. (defvar-local org-complex-heading-regexp nil
  3509. "Matches a headline and puts everything into groups:
  3510. group 1: Stars
  3511. group 2: The TODO keyword, maybe
  3512. group 3: Priority cookie
  3513. group 4: True headline
  3514. group 5: Tags
  3515. Since TODO keywords are case-sensitive, `case-fold-search' is
  3516. expected to be bound to nil when matching against this regexp.")
  3517. (defvar-local org-complex-heading-regexp-format nil
  3518. "Printf format to make regexp to match an exact headline.
  3519. This regexp will match the headline of any node which has the
  3520. exact headline text that is put into the format, but may have any
  3521. TODO state, priority and tags.")
  3522. (defvar-local org-todo-line-tags-regexp nil
  3523. "Matches a headline and puts TODO state into group 2 if present.
  3524. Also put tags into group 4 if tags are present.")
  3525. (defconst org-plain-time-of-day-regexp
  3526. (concat
  3527. "\\(\\<[012]?[0-9]"
  3528. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3529. "\\(--?"
  3530. "\\(\\<[012]?[0-9]"
  3531. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3532. "\\)?")
  3533. "Regular expression to match a plain time or time range.
  3534. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3535. groups carry important information:
  3536. 0 the full match
  3537. 1 the first time, range or not
  3538. 8 the second time, if it is a range.")
  3539. (defconst org-plain-time-extension-regexp
  3540. (concat
  3541. "\\(\\<[012]?[0-9]"
  3542. "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
  3543. "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
  3544. "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
  3545. Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
  3546. groups carry important information:
  3547. 0 the full match
  3548. 7 hours of duration
  3549. 9 minutes of duration")
  3550. (defconst org-stamp-time-of-day-regexp
  3551. (concat
  3552. "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
  3553. "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
  3554. "\\(--?"
  3555. "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
  3556. "Regular expression to match a timestamp time or time range.
  3557. After a match, the following groups carry important information:
  3558. 0 the full match
  3559. 1 date plus weekday, for back referencing to make sure
  3560. both times are on the same day
  3561. 2 the first time, range or not
  3562. 4 the second time, if it is a range.")
  3563. (defconst org-startup-options
  3564. '(("fold" org-startup-folded t)
  3565. ("overview" org-startup-folded t)
  3566. ("nofold" org-startup-folded nil)
  3567. ("showall" org-startup-folded nil)
  3568. ("show2levels" org-startup-folded show2levels)
  3569. ("show3levels" org-startup-folded show3levels)
  3570. ("show4levels" org-startup-folded show4levels)
  3571. ("show5levels" org-startup-folded show5levels)
  3572. ("showeverything" org-startup-folded showeverything)
  3573. ("content" org-startup-folded content)
  3574. ("indent" org-startup-indented t)
  3575. ("noindent" org-startup-indented nil)
  3576. ("num" org-startup-numerated t)
  3577. ("nonum" org-startup-numerated nil)
  3578. ("hidestars" org-hide-leading-stars t)
  3579. ("showstars" org-hide-leading-stars nil)
  3580. ("odd" org-odd-levels-only t)
  3581. ("oddeven" org-odd-levels-only nil)
  3582. ("align" org-startup-align-all-tables t)
  3583. ("noalign" org-startup-align-all-tables nil)
  3584. ("shrink" org-startup-shrink-all-tables t)
  3585. ("inlineimages" org-startup-with-inline-images t)
  3586. ("noinlineimages" org-startup-with-inline-images nil)
  3587. ("latexpreview" org-startup-with-latex-preview t)
  3588. ("nolatexpreview" org-startup-with-latex-preview nil)
  3589. ("customtime" org-display-custom-times t)
  3590. ("logdone" org-log-done time)
  3591. ("lognotedone" org-log-done note)
  3592. ("nologdone" org-log-done nil)
  3593. ("lognoteclock-out" org-log-note-clock-out t)
  3594. ("nolognoteclock-out" org-log-note-clock-out nil)
  3595. ("logrepeat" org-log-repeat state)
  3596. ("lognoterepeat" org-log-repeat note)
  3597. ("logdrawer" org-log-into-drawer t)
  3598. ("nologdrawer" org-log-into-drawer nil)
  3599. ("logstatesreversed" org-log-states-order-reversed t)
  3600. ("nologstatesreversed" org-log-states-order-reversed nil)
  3601. ("nologrepeat" org-log-repeat nil)
  3602. ("logreschedule" org-log-reschedule time)
  3603. ("lognotereschedule" org-log-reschedule note)
  3604. ("nologreschedule" org-log-reschedule nil)
  3605. ("logredeadline" org-log-redeadline time)
  3606. ("lognoteredeadline" org-log-redeadline note)
  3607. ("nologredeadline" org-log-redeadline nil)
  3608. ("logrefile" org-log-refile time)
  3609. ("lognoterefile" org-log-refile note)
  3610. ("nologrefile" org-log-refile nil)
  3611. ("fninline" org-footnote-define-inline t)
  3612. ("nofninline" org-footnote-define-inline nil)
  3613. ("fnlocal" org-footnote-section nil)
  3614. ("fnauto" org-footnote-auto-label t)
  3615. ("fnprompt" org-footnote-auto-label nil)
  3616. ("fnconfirm" org-footnote-auto-label confirm)
  3617. ("fnplain" org-footnote-auto-label plain)
  3618. ("fnadjust" org-footnote-auto-adjust t)
  3619. ("nofnadjust" org-footnote-auto-adjust nil)
  3620. ("constcgs" constants-unit-system cgs)
  3621. ("constSI" constants-unit-system SI)
  3622. ("noptag" org-tag-persistent-alist nil)
  3623. ("hideblocks" org-hide-block-startup t)
  3624. ("nohideblocks" org-hide-block-startup nil)
  3625. ("beamer" org-startup-with-beamer-mode t)
  3626. ("entitiespretty" org-pretty-entities t)
  3627. ("entitiesplain" org-pretty-entities nil))
  3628. "Variable associated with STARTUP options for Org.
  3629. Each element is a list of three items: the startup options (as written
  3630. in the #+STARTUP line), the corresponding variable, and the value to set
  3631. this variable to if the option is found. An optional fourth element PUSH
  3632. means to push this value onto the list in the variable.")
  3633. (defcustom org-group-tags t
  3634. "When non-nil (the default), use group tags.
  3635. This can be turned on/off through `org-toggle-tags-groups'."
  3636. :group 'org-tags
  3637. :group 'org-startup
  3638. :type 'boolean)
  3639. (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
  3640. (defun org-toggle-tags-groups ()
  3641. "Toggle support for group tags.
  3642. Support for group tags is controlled by the option
  3643. `org-group-tags', which is non-nil by default."
  3644. (interactive)
  3645. (setq org-group-tags (not org-group-tags))
  3646. (cond ((and (derived-mode-p 'org-agenda-mode)
  3647. org-group-tags)
  3648. (org-agenda-redo))
  3649. ((derived-mode-p 'org-mode)
  3650. (let ((org-inhibit-startup t)) (org-mode))))
  3651. (message "Groups tags support has been turned %s"
  3652. (if org-group-tags "on" "off")))
  3653. (defun org--tag-add-to-alist (alist1 alist2)
  3654. "Merge tags from ALIST1 into ALIST2.
  3655. Duplicates tags outside a group are removed. Keywords and order
  3656. are preserved.
  3657. The function assumes ALIST1 and ALIST2 are proper tag alists.
  3658. See `org-tag-alist' for their structure."
  3659. (cond
  3660. ((null alist2) alist1)
  3661. ((null alist1) alist2)
  3662. (t
  3663. (let ((to-add nil)
  3664. (group-flag nil))
  3665. (dolist (tag-pair alist1)
  3666. (pcase tag-pair
  3667. (`(,(or :startgrouptag :startgroup))
  3668. (setq group-flag t)
  3669. (push tag-pair to-add))
  3670. (`(,(or :endgrouptag :endgroup))
  3671. (setq group-flag nil)
  3672. (push tag-pair to-add))
  3673. (`(,(or :grouptags :newline))
  3674. (push tag-pair to-add))
  3675. (`(,tag . ,_)
  3676. ;; Remove duplicates from ALIST1, unless they are in
  3677. ;; a group. Indeed, it makes sense to have a tag appear in
  3678. ;; multiple groups.
  3679. (when (or group-flag (not (assoc tag alist2)))
  3680. (push tag-pair to-add)))
  3681. (_ (error "Invalid association in tag alist: %S" tag-pair))))
  3682. ;; Preserve order of ALIST1.
  3683. (append (nreverse to-add) alist2)))))
  3684. (defun org-priority-to-value (s)
  3685. "Convert priority string S to its numeric value."
  3686. (or (save-match-data
  3687. (and (string-match "\\([0-9]+\\)" s)
  3688. (string-to-number (match-string 1 s))))
  3689. (string-to-char s)))
  3690. (defun org-set-regexps-and-options (&optional tags-only)
  3691. "Precompute regular expressions used in the current buffer.
  3692. When optional argument TAGS-ONLY is non-nil, only compute tags
  3693. related expressions."
  3694. (when (derived-mode-p 'org-mode)
  3695. (let ((alist (org-collect-keywords
  3696. (append '("FILETAGS" "TAGS")
  3697. (and (not tags-only)
  3698. '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
  3699. "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
  3700. "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
  3701. '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
  3702. ;; Startup options. Get this early since it does change
  3703. ;; behavior for other options (e.g., tags).
  3704. (let ((startup (cl-mapcan (lambda (value) (split-string value))
  3705. (cdr (assoc "STARTUP" alist)))))
  3706. (dolist (option startup)
  3707. (pcase (assoc-string option org-startup-options t)
  3708. (`(,_ ,variable ,value t)
  3709. (unless (listp (symbol-value variable))
  3710. (set (make-local-variable variable) nil))
  3711. (add-to-list variable value))
  3712. (`(,_ ,variable ,value . ,_)
  3713. (set (make-local-variable variable) value))
  3714. (_ nil))))
  3715. (setq-local org-file-tags
  3716. (mapcar #'org-add-prop-inherited
  3717. (cl-mapcan (lambda (value)
  3718. (cl-mapcan
  3719. (lambda (k) (org-split-string k ":"))
  3720. (split-string value)))
  3721. (cdr (assoc "FILETAGS" alist)))))
  3722. (setq org-current-tag-alist
  3723. (org--tag-add-to-alist
  3724. org-tag-persistent-alist
  3725. (let ((tags (cdr (assoc "TAGS" alist))))
  3726. (if tags
  3727. (org-tag-string-to-alist
  3728. (mapconcat #'identity tags "\n"))
  3729. org-tag-alist))))
  3730. (setq org-tag-groups-alist
  3731. (org-tag-alist-to-groups org-current-tag-alist))
  3732. (unless tags-only
  3733. ;; Properties.
  3734. (let ((properties nil))
  3735. (dolist (value (cdr (assoc "PROPERTY" alist)))
  3736. (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
  3737. (setq properties (org--update-property-plist
  3738. (match-string-no-properties 1 value)
  3739. (match-string-no-properties 2 value)
  3740. properties))))
  3741. (setq-local org-keyword-properties properties))
  3742. ;; Archive location.
  3743. (let ((archive (cdr (assoc "ARCHIVE" alist))))
  3744. (when archive (setq-local org-archive-location archive)))
  3745. ;; Category.
  3746. (let ((category (cdr (assoc "CATEGORY" alist))))
  3747. (when category
  3748. (setq-local org-category (intern category))
  3749. (setq-local org-keyword-properties
  3750. (org--update-property-plist
  3751. "CATEGORY" category org-keyword-properties))))
  3752. ;; Columns.
  3753. (let ((column (cdr (assoc "COLUMNS" alist))))
  3754. (when column (setq-local org-columns-default-format column)))
  3755. ;; Constants.
  3756. (let ((store nil))
  3757. (dolist (pair (cl-mapcan #'split-string
  3758. (cdr (assoc "CONSTANTS" alist))))
  3759. (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
  3760. (let* ((name (match-string 1 pair))
  3761. (value (match-string 2 pair))
  3762. (old (assoc name store)))
  3763. (if old (setcdr old value)
  3764. (push (cons name value) store)))))
  3765. (setq org-table-formula-constants-local store))
  3766. ;; Link abbreviations.
  3767. (let ((links
  3768. (delq nil
  3769. (mapcar
  3770. (lambda (value)
  3771. (and (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
  3772. (cons (match-string-no-properties 1 value)
  3773. (match-string-no-properties 2 value))))
  3774. (cdr (assoc "LINK" alist))))))
  3775. (when links (setq org-link-abbrev-alist-local (nreverse links))))
  3776. ;; Priorities.
  3777. (let ((value (cdr (assoc "PRIORITIES" alist))))
  3778. (pcase (and value (split-string value))
  3779. (`(,high ,low ,default . ,_)
  3780. (setq-local org-priority-highest (org-priority-to-value high))
  3781. (setq-local org-priority-lowest (org-priority-to-value low))
  3782. (setq-local org-priority-default (org-priority-to-value default)))))
  3783. ;; Scripts.
  3784. (let ((value (cdr (assoc "OPTIONS" alist))))
  3785. (dolist (option value)
  3786. (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
  3787. (setq-local org-use-sub-superscripts
  3788. (read (match-string 1 option))))))
  3789. ;; TODO keywords.
  3790. (setq-local org-todo-kwd-alist nil)
  3791. (setq-local org-todo-key-alist nil)
  3792. (setq-local org-todo-key-trigger nil)
  3793. (setq-local org-todo-keywords-1 nil)
  3794. (setq-local org-done-keywords nil)
  3795. (setq-local org-todo-heads nil)
  3796. (setq-local org-todo-sets nil)
  3797. (setq-local org-todo-log-states nil)
  3798. (let ((todo-sequences
  3799. (or (append (mapcar (lambda (value)
  3800. (cons 'type (split-string value)))
  3801. (cdr (assoc "TYP_TODO" alist)))
  3802. (mapcar (lambda (value)
  3803. (cons 'sequence (split-string value)))
  3804. (append (cdr (assoc "TODO" alist))
  3805. (cdr (assoc "SEQ_TODO" alist)))))
  3806. (let ((d (default-value 'org-todo-keywords)))
  3807. (if (not (stringp (car d))) d
  3808. ;; XXX: Backward compatibility code.
  3809. (list (cons org-todo-interpretation d)))))))
  3810. (dolist (sequence todo-sequences)
  3811. (let* ((sequence (or (run-hook-with-args-until-success
  3812. 'org-todo-setup-filter-hook sequence)
  3813. sequence))
  3814. (sequence-type (car sequence))
  3815. (keywords (cdr sequence))
  3816. (sep (member "|" keywords))
  3817. names alist)
  3818. (dolist (k (remove "|" keywords))
  3819. (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
  3820. k)
  3821. (error "Invalid TODO keyword %s" k))
  3822. (let ((name (match-string 1 k))
  3823. (key (match-string 2 k))
  3824. (log (org-extract-log-state-settings k)))
  3825. (push name names)
  3826. (push (cons name (and key (string-to-char key))) alist)
  3827. (when log (push log org-todo-log-states))))
  3828. (let* ((names (nreverse names))
  3829. (done (if sep (org-remove-keyword-keys (cdr sep))
  3830. (last names)))
  3831. (head (car names))
  3832. (tail (list sequence-type head (car done) (org-last done))))
  3833. (add-to-list 'org-todo-heads head 'append)
  3834. (push names org-todo-sets)
  3835. (setq org-done-keywords (append org-done-keywords done nil))
  3836. (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
  3837. (setq org-todo-key-alist
  3838. (append org-todo-key-alist
  3839. (and alist
  3840. (append '((:startgroup))
  3841. (nreverse alist)
  3842. '((:endgroup))))))
  3843. (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
  3844. (setq org-todo-sets (nreverse org-todo-sets)
  3845. org-todo-kwd-alist (nreverse org-todo-kwd-alist)
  3846. org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
  3847. org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
  3848. ;; Compute the regular expressions and other local variables.
  3849. ;; Using `org-outline-regexp-bol' would complicate them much,
  3850. ;; because of the fixed white space at the end of that string.
  3851. (unless org-done-keywords
  3852. (setq org-done-keywords
  3853. (and org-todo-keywords-1 (last org-todo-keywords-1))))
  3854. (setq org-not-done-keywords
  3855. (org-delete-all org-done-keywords
  3856. (copy-sequence org-todo-keywords-1))
  3857. org-todo-regexp (regexp-opt org-todo-keywords-1 t)
  3858. org-not-done-regexp (regexp-opt org-not-done-keywords t)
  3859. org-not-done-heading-regexp
  3860. (format org-heading-keyword-regexp-format org-not-done-regexp)
  3861. org-todo-line-regexp
  3862. (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
  3863. org-complex-heading-regexp
  3864. (concat "^\\(\\*+\\)"
  3865. "\\(?: +" org-todo-regexp "\\)?"
  3866. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3867. "\\(?: +\\(.*?\\)\\)??"
  3868. "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
  3869. "[ \t]*$")
  3870. org-complex-heading-regexp-format
  3871. (concat "^\\(\\*+\\)"
  3872. "\\(?: +" org-todo-regexp "\\)?"
  3873. "\\(?: +\\(\\[#.\\]\\)\\)?"
  3874. "\\(?: +"
  3875. ;; Stats cookies can be stuck to body.
  3876. "\\(?:\\[[0-9%%/]+\\] *\\)*"
  3877. "\\(%s\\)"
  3878. "\\(?: *\\[[0-9%%/]+\\]\\)*"
  3879. "\\)"
  3880. "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
  3881. "[ \t]*$")
  3882. org-todo-line-tags-regexp
  3883. (concat "^\\(\\*+\\)"
  3884. "\\(?: +" org-todo-regexp "\\)?"
  3885. "\\(?: +\\(.*?\\)\\)??"
  3886. "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
  3887. "[ \t]*$"))
  3888. (org-compute-latex-and-related-regexp)))))
  3889. (defun org-collect-keywords (keywords &optional unique directory)
  3890. "Return values for KEYWORDS in current buffer, as an alist.
  3891. KEYWORDS is a list of strings. Return value is a list of
  3892. elements with the pattern:
  3893. (NAME . LIST-OF-VALUES)
  3894. where NAME is the upcase name of the keyword, and LIST-OF-VALUES
  3895. is a list of non-empty values, as strings, in order of appearance
  3896. in the buffer.
  3897. When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
  3898. value, empty or not, appearing in the buffer, as a string.
  3899. When KEYWORD appears in DIRECTORIES, each value is a cons cell:
  3900. (VALUE . DIRECTORY)
  3901. where VALUE is the regular value, and DIRECTORY is the variable
  3902. `default-directory' for the buffer containing the keyword. This
  3903. is important for values containing relative file names, since the
  3904. function follows SETUPFILE keywords, and may change its working
  3905. directory."
  3906. (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
  3907. (unique (mapcar #'upcase unique))
  3908. (alist (org--collect-keywords-1
  3909. keywords unique directory
  3910. (and buffer-file-name (list buffer-file-name))
  3911. nil)))
  3912. ;; Re-order results.
  3913. (dolist (entry alist)
  3914. (pcase entry
  3915. (`(,_ . ,(and value (pred consp)))
  3916. (setcdr entry (nreverse value)))))
  3917. (nreverse alist)))
  3918. (defun org--collect-keywords-1 (keywords unique directory files alist)
  3919. (org-with-point-at 1
  3920. (let ((case-fold-search t)
  3921. (regexp (org-make-options-regexp keywords)))
  3922. (while (and keywords (re-search-forward regexp nil t))
  3923. (let ((element (org-element-at-point)))
  3924. (when (eq 'keyword (org-element-type element))
  3925. (let ((value (org-element-property :value element)))
  3926. (pcase (org-element-property :key element)
  3927. ("SETUPFILE"
  3928. (when (and (org-string-nw-p value)
  3929. (not buffer-read-only)) ;FIXME: bug in Gnus?
  3930. (let* ((uri (org-strip-quotes value))
  3931. (uri-is-url (org-url-p uri))
  3932. (uri (if uri-is-url
  3933. uri
  3934. (expand-file-name uri))))
  3935. (unless (member uri files)
  3936. (with-temp-buffer
  3937. (unless uri-is-url
  3938. (setq default-directory (file-name-directory uri)))
  3939. (let ((contents (org-file-contents uri :noerror)))
  3940. (when contents
  3941. (insert contents)
  3942. ;; Fake Org mode: `org-element-at-point'
  3943. ;; doesn't need full set-up.
  3944. (let ((major-mode 'org-mode))
  3945. (setq alist
  3946. (org--collect-keywords-1
  3947. keywords unique directory
  3948. (cons uri files)
  3949. alist))))))))))
  3950. (keyword
  3951. (let ((entry (assoc keyword alist))
  3952. (final
  3953. (cond ((not (member keyword directory)) value)
  3954. (buffer-file-name
  3955. (cons value
  3956. (file-name-directory buffer-file-name)))
  3957. (t (cons value default-directory)))))
  3958. (cond ((member keyword unique)
  3959. (push (cons keyword final) alist)
  3960. (setq keywords (remove keyword keywords))
  3961. (setq regexp (org-make-options-regexp keywords)))
  3962. ((null entry) (push (list keyword final) alist))
  3963. (t (push final (cdr entry)))))))))))
  3964. alist)))
  3965. (defun org-tag-string-to-alist (s)
  3966. "Return tag alist associated to string S.
  3967. S is a value for TAGS keyword or produced with
  3968. `org-tag-alist-to-string'. Return value is an alist suitable for
  3969. `org-tag-alist' or `org-tag-persistent-alist'."
  3970. (let ((lines (mapcar #'split-string (split-string s "\n" t)))
  3971. (tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
  3972. "\\(?:(\\(.\\))\\)?\\'"))
  3973. alist group-flag)
  3974. (dolist (tokens lines (cdr (nreverse alist)))
  3975. (push '(:newline) alist)
  3976. (while tokens
  3977. (let ((token (pop tokens)))
  3978. (pcase token
  3979. ("{"
  3980. (push '(:startgroup) alist)
  3981. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3982. ("}"
  3983. (push '(:endgroup) alist)
  3984. (setq group-flag nil))
  3985. ("["
  3986. (push '(:startgrouptag) alist)
  3987. (when (equal (nth 1 tokens) ":") (setq group-flag t)))
  3988. ("]"
  3989. (push '(:endgrouptag) alist)
  3990. (setq group-flag nil))
  3991. (":"
  3992. (push '(:grouptags) alist))
  3993. ((guard (string-match tag-re token))
  3994. (let ((tag (match-string 1 token))
  3995. (key (and (match-beginning 2)
  3996. (string-to-char (match-string 2 token)))))
  3997. ;; Push all tags in groups, no matter if they already
  3998. ;; appear somewhere else in the list.
  3999. (when (or group-flag (not (assoc tag alist)))
  4000. (push (cons tag key) alist))))))))))
  4001. (defun org-tag-alist-to-string (alist &optional skip-key)
  4002. "Return tag string associated to ALIST.
  4003. ALIST is an alist, as defined in `org-tag-alist' or
  4004. `org-tag-persistent-alist', or produced with
  4005. `org-tag-string-to-alist'.
  4006. Return value is a string suitable as a value for \"TAGS\"
  4007. keyword.
  4008. When optional argument SKIP-KEY is non-nil, skip selection keys
  4009. next to tags."
  4010. (mapconcat (lambda (token)
  4011. (pcase token
  4012. (`(:startgroup) "{")
  4013. (`(:endgroup) "}")
  4014. (`(:startgrouptag) "[")
  4015. (`(:endgrouptag) "]")
  4016. (`(:grouptags) ":")
  4017. (`(:newline) "\\n")
  4018. ((and
  4019. (guard (not skip-key))
  4020. `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
  4021. (format "%s(%c)" tag key))
  4022. (`(,(and tag (pred stringp)) . ,_) tag)
  4023. (_ (user-error "Invalid tag token: %S" token))))
  4024. alist
  4025. " "))
  4026. (defun org-tag-alist-to-groups (alist)
  4027. "Return group alist from tag ALIST.
  4028. ALIST is an alist, as defined in `org-tag-alist' or
  4029. `org-tag-persistent-alist', or produced with
  4030. `org-tag-string-to-alist'. Return value is an alist following
  4031. the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
  4032. a string, summarizing TAGS, as a list of strings."
  4033. (let (groups group-status current-group)
  4034. (dolist (token alist (nreverse groups))
  4035. (pcase token
  4036. (`(,(or :startgroup :startgrouptag)) (setq group-status t))
  4037. (`(,(or :endgroup :endgrouptag))
  4038. (when (eq group-status 'append)
  4039. (push (nreverse current-group) groups))
  4040. (setq group-status nil current-group nil))
  4041. (`(:grouptags) (setq group-status 'append))
  4042. ((and `(,tag . ,_) (guard group-status))
  4043. (if (eq group-status 'append) (push tag current-group)
  4044. (setq current-group (list tag))))
  4045. (_ nil)))))
  4046. (defvar org--file-cache (make-hash-table :test #'equal)
  4047. "Hash table to store contents of files referenced via a URL.
  4048. This is the cache of file URLs read using `org-file-contents'.")
  4049. (defun org-reset-file-cache ()
  4050. "Reset the cache of files downloaded by `org-file-contents'."
  4051. (clrhash org--file-cache))
  4052. (defun org-file-contents (file &optional noerror nocache)
  4053. "Return the contents of FILE, as a string.
  4054. FILE can be a file name or URL.
  4055. If FILE is a URL, download the contents. If the URL contents are
  4056. already cached in the `org--file-cache' hash table, the download step
  4057. is skipped.
  4058. If NOERROR is non-nil, ignore the error when unable to read the FILE
  4059. from file or URL, and return nil.
  4060. If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
  4061. is available. This option applies only if FILE is a URL."
  4062. (let* ((is-url (org-url-p file))
  4063. (cache (and is-url
  4064. (not nocache)
  4065. (gethash file org--file-cache))))
  4066. (cond
  4067. (cache)
  4068. (is-url
  4069. (with-current-buffer (url-retrieve-synchronously file)
  4070. (goto-char (point-min))
  4071. ;; Move point to after the url-retrieve header.
  4072. (search-forward "\n\n" nil :move)
  4073. ;; Search for the success code only in the url-retrieve header.
  4074. (if (save-excursion
  4075. (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
  4076. ;; Update the cache `org--file-cache' and return contents.
  4077. (puthash file
  4078. (buffer-substring-no-properties (point) (point-max))
  4079. org--file-cache)
  4080. (funcall (if noerror #'message #'user-error)
  4081. "Unable to fetch file from %S"
  4082. file)
  4083. nil)))
  4084. (t
  4085. (with-temp-buffer
  4086. (condition-case nil
  4087. (progn
  4088. (insert-file-contents file)
  4089. (buffer-string))
  4090. (file-error
  4091. (funcall (if noerror #'message #'user-error)
  4092. "Unable to read file %S"
  4093. file)
  4094. nil)))))))
  4095. (defun org-extract-log-state-settings (x)
  4096. "Extract the log state setting from a TODO keyword string.
  4097. This will extract info from a string like \"WAIT(w@/!)\"."
  4098. (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
  4099. (let ((kw (match-string 1 x))
  4100. (log1 (and (match-end 3) (match-string 3 x)))
  4101. (log2 (and (match-end 4) (match-string 4 x))))
  4102. (and (or log1 log2)
  4103. (list kw
  4104. (and log1 (if (equal log1 "!") 'time 'note))
  4105. (and log2 (if (equal log2 "!") 'time 'note)))))))
  4106. (defun org-remove-keyword-keys (list)
  4107. "Remove a pair of parenthesis at the end of each string in LIST."
  4108. (mapcar (lambda (x)
  4109. (if (string-match "(.*)$" x)
  4110. (substring x 0 (match-beginning 0))
  4111. x))
  4112. list))
  4113. (defun org-assign-fast-keys (alist)
  4114. "Assign fast keys to a keyword-key alist.
  4115. Respect keys that are already there."
  4116. (let (new e (alt ?0))
  4117. (while (setq e (pop alist))
  4118. (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
  4119. (cdr e)) ;; Key already assigned.
  4120. (push e new)
  4121. (let ((clist (string-to-list (downcase (car e))))
  4122. (used (append new alist)))
  4123. (when (= (car clist) ?@)
  4124. (pop clist))
  4125. (while (and clist (rassoc (car clist) used))
  4126. (pop clist))
  4127. (unless clist
  4128. (while (rassoc alt used)
  4129. (cl-incf alt)))
  4130. (push (cons (car e) (or (car clist) alt)) new))))
  4131. (nreverse new)))
  4132. ;;; Some variables used in various places
  4133. (defvar org-window-configuration nil
  4134. "Used in various places to store a window configuration.")
  4135. (defvar org-selected-window nil
  4136. "Used in various places to store a window configuration.")
  4137. (defvar org-finish-function nil
  4138. "Function to be called when `C-c C-c' is used.
  4139. This is for getting out of special buffers like capture.")
  4140. (defvar org-last-state)
  4141. ;; Defined somewhere in this file, but used before definition.
  4142. (defvar org-entities) ;; defined in org-entities.el
  4143. (defvar org-struct-menu)
  4144. (defvar org-org-menu)
  4145. (defvar org-tbl-menu)
  4146. ;;;; Define the Org mode
  4147. (defun org-before-change-function (_beg _end)
  4148. "Every change indicates that a table might need an update."
  4149. (setq org-table-may-need-update t))
  4150. (defvar org-mode-map)
  4151. (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
  4152. (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
  4153. (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
  4154. (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
  4155. (defvar bidi-paragraph-direction)
  4156. (defvar buffer-face-mode-face)
  4157. (require 'outline)
  4158. ;; Other stuff we need.
  4159. (require 'time-date)
  4160. (when (< emacs-major-version 28) ; preloaded in Emacs 28
  4161. (require 'easymenu))
  4162. (require 'org-entities)
  4163. (require 'org-faces)
  4164. (require 'org-list)
  4165. (require 'org-pcomplete)
  4166. (require 'org-src)
  4167. (require 'org-footnote)
  4168. (require 'org-macro)
  4169. ;; babel
  4170. (require 'ob)
  4171. ;;;###autoload
  4172. (define-derived-mode org-mode outline-mode "Org"
  4173. "Outline-based notes management and organizer, alias
  4174. \"Carsten's outline-mode for keeping track of everything.\"
  4175. Org mode develops organizational tasks around a NOTES file which
  4176. contains information about projects as plain text. Org mode is
  4177. implemented on top of Outline mode, which is ideal to keep the content
  4178. of large files well structured. It supports ToDo items, deadlines and
  4179. time stamps, which magically appear in the diary listing of the Emacs
  4180. calendar. Tables are easily created with a built-in table editor.
  4181. Plain text URL-like links connect to websites, emails (VM), Usenet
  4182. messages (Gnus), BBDB entries, and any files related to the project.
  4183. For printing and sharing of notes, an Org file (or a part of it)
  4184. can be exported as a structured ASCII or HTML file.
  4185. The following commands are available:
  4186. \\{org-mode-map}"
  4187. (org-load-modules-maybe)
  4188. (org-install-agenda-files-menu)
  4189. (when org-link-descriptive (add-to-invisibility-spec '(org-link)))
  4190. (make-local-variable 'org-link-descriptive)
  4191. (add-to-invisibility-spec '(org-hide-block . t))
  4192. (setq-local outline-regexp org-outline-regexp)
  4193. (setq-local outline-level 'org-outline-level)
  4194. (setq bidi-paragraph-direction 'left-to-right)
  4195. (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
  4196. (unless org-display-table
  4197. (setq org-display-table (make-display-table)))
  4198. (set-display-table-slot
  4199. org-display-table 4
  4200. (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
  4201. org-ellipsis)))
  4202. (setq buffer-display-table org-display-table))
  4203. (org-set-regexps-and-options)
  4204. (org-set-font-lock-defaults)
  4205. (when (and org-tag-faces (not org-tags-special-faces-re))
  4206. ;; tag faces set outside customize.... force initialization.
  4207. (org-set-tag-faces 'org-tag-faces org-tag-faces))
  4208. ;; Calc embedded
  4209. (setq-local calc-embedded-open-mode "# ")
  4210. ;; Modify a few syntax entries
  4211. (modify-syntax-entry ?\" "\"")
  4212. (modify-syntax-entry ?\\ "_")
  4213. (modify-syntax-entry ?~ "_")
  4214. (modify-syntax-entry ?< "(>")
  4215. (modify-syntax-entry ?> ")<")
  4216. (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
  4217. ;; Activate before-change-function
  4218. (setq-local org-table-may-need-update t)
  4219. (add-hook 'before-change-functions 'org-before-change-function nil 'local)
  4220. ;; Check for running clock before killing a buffer
  4221. (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
  4222. ;; Initialize macros templates.
  4223. (org-macro-initialize-templates)
  4224. ;; Initialize radio targets.
  4225. (org-update-radio-target-regexp)
  4226. ;; Indentation.
  4227. (setq-local indent-line-function 'org-indent-line)
  4228. (setq-local indent-region-function 'org-indent-region)
  4229. ;; Filling and auto-filling.
  4230. (org-setup-filling)
  4231. ;; Comments.
  4232. (org-setup-comments-handling)
  4233. ;; Initialize cache.
  4234. (org-element-cache-reset)
  4235. ;; Beginning/end of defun
  4236. (setq-local beginning-of-defun-function 'org-backward-element)
  4237. (setq-local end-of-defun-function
  4238. (lambda ()
  4239. (if (not (org-at-heading-p))
  4240. (org-forward-element)
  4241. (org-forward-element)
  4242. (forward-char -1))))
  4243. ;; Next error for sparse trees
  4244. (setq-local next-error-function 'org-occur-next-match)
  4245. ;; Make commit log messages from Org documents easier.
  4246. (setq-local add-log-current-defun-function #'org-add-log-current-headline)
  4247. ;; Make sure dependence stuff works reliably, even for users who set it
  4248. ;; too late :-(
  4249. (if org-enforce-todo-dependencies
  4250. (add-hook 'org-blocker-hook
  4251. 'org-block-todo-from-children-or-siblings-or-parent)
  4252. (remove-hook 'org-blocker-hook
  4253. 'org-block-todo-from-children-or-siblings-or-parent))
  4254. (if org-enforce-todo-checkbox-dependencies
  4255. (add-hook 'org-blocker-hook
  4256. 'org-block-todo-from-checkboxes)
  4257. (remove-hook 'org-blocker-hook
  4258. 'org-block-todo-from-checkboxes))
  4259. ;; Align options lines
  4260. (setq-local
  4261. align-mode-rules-list
  4262. '((org-in-buffer-settings
  4263. (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
  4264. (modes . '(org-mode)))))
  4265. ;; Setup the pcomplete hooks
  4266. (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
  4267. (setq-local pcomplete-command-name-function #'org-command-at-point)
  4268. (setq-local pcomplete-default-completion-function #'ignore)
  4269. (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
  4270. (setq-local pcomplete-termination-string "")
  4271. (add-hook 'completion-at-point-functions
  4272. #'pcomplete-completions-at-point nil t)
  4273. (setq-local buffer-face-mode-face 'org-default)
  4274. ;; If empty file that did not turn on Org mode automatically, make
  4275. ;; it to.
  4276. (when (and org-insert-mode-line-in-empty-file
  4277. (called-interactively-p 'any)
  4278. (= (point-min) (point-max)))
  4279. (insert "# -*- mode: org -*-\n\n"))
  4280. (unless org-inhibit-startup
  4281. (org-unmodified
  4282. (when org-startup-with-beamer-mode (org-beamer-mode))
  4283. (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
  4284. (org-table-map-tables
  4285. (cond ((and org-startup-align-all-tables
  4286. org-startup-shrink-all-tables)
  4287. (lambda () (org-table-align) (org-table-shrink)))
  4288. (org-startup-align-all-tables #'org-table-align)
  4289. (t #'org-table-shrink))
  4290. t))
  4291. (when org-startup-with-inline-images (org-display-inline-images))
  4292. (when org-startup-with-latex-preview (org-latex-preview '(16)))
  4293. (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
  4294. (when org-startup-truncated (setq truncate-lines t))
  4295. (when org-startup-numerated (require 'org-num) (org-num-mode 1))
  4296. (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
  4297. ;; Add a custom keymap for `visual-line-mode' so that activating
  4298. ;; this minor mode does not override Org's keybindings.
  4299. ;; FIXME: Probably `visual-line-mode' should take care of this.
  4300. (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
  4301. (newmap (make-sparse-keymap)))
  4302. (set-keymap-parent newmap oldmap)
  4303. (define-key newmap [remap move-beginning-of-line] nil)
  4304. (define-key newmap [remap move-end-of-line] nil)
  4305. (define-key newmap [remap kill-line] nil)
  4306. (make-local-variable 'minor-mode-overriding-map-alist)
  4307. (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
  4308. ;; Activate `org-table-header-line-mode'
  4309. (when org-table-header-line-p
  4310. (org-table-header-line-mode 1))
  4311. ;; Try to set `org-hide' face correctly.
  4312. (let ((foreground (org-find-invisible-foreground)))
  4313. (when foreground
  4314. (set-face-foreground 'org-hide foreground)))
  4315. ;; Set face extension as requested.
  4316. (org--set-faces-extend '(org-block-begin-line org-block-end-line)
  4317. org-fontify-whole-block-delimiter-line)
  4318. (org--set-faces-extend org-level-faces org-fontify-whole-heading-line))
  4319. ;; Update `customize-package-emacs-version-alist'
  4320. (add-to-list 'customize-package-emacs-version-alist
  4321. '(Org ("8.0" . "24.4")
  4322. ("8.1" . "24.4")
  4323. ("8.2" . "24.4")
  4324. ("8.2.7" . "24.4")
  4325. ("8.3" . "26.1")
  4326. ("9.0" . "26.1")
  4327. ("9.1" . "26.1")
  4328. ("9.2" . "27.1")
  4329. ("9.3" . "27.1")
  4330. ("9.4" . "27.2")
  4331. ("9.5" . "28.1")))
  4332. (defvar org-mode-transpose-word-syntax-table
  4333. (let ((st (make-syntax-table text-mode-syntax-table)))
  4334. (dolist (c org-emphasis-alist st)
  4335. (modify-syntax-entry (string-to-char (car c)) "w p" st))))
  4336. (when (fboundp 'abbrev-table-put)
  4337. (abbrev-table-put org-mode-abbrev-table
  4338. :parents (list text-mode-abbrev-table)))
  4339. (defun org-find-invisible-foreground ()
  4340. (let ((candidates (remove
  4341. "unspecified-bg"
  4342. (nconc
  4343. (list (face-background 'default)
  4344. (face-background 'org-default))
  4345. (mapcar
  4346. (lambda (alist)
  4347. (when (boundp alist)
  4348. (cdr (assq 'background-color (symbol-value alist)))))
  4349. '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
  4350. (list (face-foreground 'org-hide))))))
  4351. (car (remove nil candidates))))
  4352. (defun org-current-time (&optional rounding-minutes past)
  4353. "Current time, possibly rounded to ROUNDING-MINUTES.
  4354. When ROUNDING-MINUTES is not an integer, fall back on the car of
  4355. `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
  4356. the rounding returns a past time."
  4357. (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
  4358. (car org-time-stamp-rounding-minutes)))
  4359. (now (current-time)))
  4360. (if (< r 1)
  4361. now
  4362. (let* ((time (decode-time now))
  4363. (res (apply #'encode-time 0 (* r (round (nth 1 time) r))
  4364. (nthcdr 2 time))))
  4365. (if (or (not past) (time-less-p res now))
  4366. res
  4367. (time-subtract res (* r 60)))))))
  4368. (defun org-today ()
  4369. "Return today date, considering `org-extend-today-until'."
  4370. (time-to-days
  4371. (time-since (* 3600 org-extend-today-until))))
  4372. ;;;; Font-Lock stuff, including the activators
  4373. (defconst org-match-sexp-depth 3
  4374. "Number of stacked braces for sub/superscript matching.")
  4375. (defun org-create-multibrace-regexp (left right n)
  4376. "Create a regular expression which will match a balanced sexp.
  4377. Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
  4378. as single character strings.
  4379. The regexp returned will match the entire expression including the
  4380. delimiters. It will also define a single group which contains the
  4381. match except for the outermost delimiters. The maximum depth of
  4382. stacked delimiters is N. Escaping delimiters is not possible."
  4383. (let* ((nothing (concat "[^" left right "]*?"))
  4384. (or "\\|")
  4385. (re nothing)
  4386. (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
  4387. (while (> n 1)
  4388. (setq n (1- n)
  4389. re (concat re or next)
  4390. next (concat "\\(?:" nothing left next right "\\)+" nothing)))
  4391. (concat left "\\(" re "\\)" right)))
  4392. (defconst org-match-substring-regexp
  4393. (concat
  4394. "\\(\\S-\\)\\([_^]\\)\\("
  4395. "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
  4396. "\\|"
  4397. "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
  4398. "\\|"
  4399. "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
  4400. "The regular expression matching a sub- or superscript.")
  4401. (defconst org-match-substring-with-braces-regexp
  4402. (concat
  4403. "\\(\\S-\\)\\([_^]\\)"
  4404. "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
  4405. "The regular expression matching a sub- or superscript, forcing braces.")
  4406. (defvar org-emph-face nil)
  4407. (defun org-do-emphasis-faces (limit)
  4408. "Run through the buffer and emphasize strings."
  4409. (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
  4410. (car org-emphasis-regexp-components))))
  4411. (catch :exit
  4412. (while (re-search-forward quick-re limit t)
  4413. (let* ((marker (match-string 2))
  4414. (verbatim? (member marker '("~" "="))))
  4415. (when (save-excursion
  4416. (goto-char (match-beginning 0))
  4417. (and
  4418. ;; Do not match table hlines.
  4419. (not (and (equal marker "+")
  4420. (org-match-line
  4421. "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
  4422. ;; Do not match headline stars. Do not consider
  4423. ;; stars of a headline as closing marker for bold
  4424. ;; markup either.
  4425. (not (and (equal marker "*")
  4426. (save-excursion
  4427. (forward-char)
  4428. (skip-chars-backward "*")
  4429. (looking-at-p org-outline-regexp-bol))))
  4430. ;; Match full emphasis markup regexp.
  4431. (looking-at (if verbatim? org-verbatim-re org-emph-re))
  4432. ;; Do not span over paragraph boundaries.
  4433. (not (string-match-p org-element-paragraph-separate
  4434. (match-string 2)))
  4435. ;; Do not span over cells in table rows.
  4436. (not (and (save-match-data (org-match-line "[ \t]*|"))
  4437. (string-match-p "|" (match-string 4))))))
  4438. (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
  4439. (m (if org-hide-emphasis-markers 4 2)))
  4440. (font-lock-prepend-text-property
  4441. (match-beginning m) (match-end m) 'face face)
  4442. (when verbatim?
  4443. (org-remove-flyspell-overlays-in
  4444. (match-beginning 0) (match-end 0))
  4445. (remove-text-properties (match-beginning 2) (match-end 2)
  4446. '(display t invisible t intangible t)))
  4447. (add-text-properties (match-beginning 2) (match-end 2)
  4448. '(font-lock-multiline t org-emphasis t))
  4449. (when (and org-hide-emphasis-markers
  4450. (not (org-at-comment-p)))
  4451. (add-text-properties (match-end 4) (match-beginning 5)
  4452. '(invisible t))
  4453. (add-text-properties (match-beginning 3) (match-end 3)
  4454. '(invisible t)))
  4455. (goto-char (match-end 0))
  4456. (throw :exit t))))))))
  4457. (defun org-emphasize (&optional char)
  4458. "Insert or change an emphasis, i.e. a font like bold or italic.
  4459. If there is an active region, change that region to a new emphasis.
  4460. If there is no region, just insert the marker characters and position
  4461. the cursor between them.
  4462. CHAR should be the marker character. If it is a space, it means to
  4463. remove the emphasis of the selected region.
  4464. If CHAR is not given (for example in an interactive call) it will be
  4465. prompted for."
  4466. (interactive)
  4467. (let ((erc org-emphasis-regexp-components)
  4468. (string "") beg end move s)
  4469. (if (org-region-active-p)
  4470. (setq beg (region-beginning)
  4471. end (region-end)
  4472. string (buffer-substring beg end))
  4473. (setq move t))
  4474. (unless char
  4475. (message "Emphasis marker or tag: [%s]"
  4476. (mapconcat #'car org-emphasis-alist ""))
  4477. (setq char (read-char-exclusive)))
  4478. (if (equal char ?\s)
  4479. (setq s ""
  4480. move nil)
  4481. (unless (assoc (char-to-string char) org-emphasis-alist)
  4482. (user-error "No such emphasis marker: \"%c\"" char))
  4483. (setq s (char-to-string char)))
  4484. (while (and (> (length string) 1)
  4485. (equal (substring string 0 1) (substring string -1))
  4486. (assoc (substring string 0 1) org-emphasis-alist))
  4487. (setq string (substring string 1 -1)))
  4488. (setq string (concat s string s))
  4489. (when beg (delete-region beg end))
  4490. (unless (or (bolp)
  4491. (string-match (concat "[" (nth 0 erc) "\n]")
  4492. (char-to-string (char-before (point)))))
  4493. (insert " "))
  4494. (unless (or (eobp)
  4495. (string-match (concat "[" (nth 1 erc) "\n]")
  4496. (char-to-string (char-after (point)))))
  4497. (insert " ") (backward-char 1))
  4498. (insert string)
  4499. (and move (backward-char 1))))
  4500. (defconst org-nonsticky-props
  4501. '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
  4502. (defsubst org-rear-nonsticky-at (pos)
  4503. (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
  4504. (defun org-activate-links (limit)
  4505. "Add link properties to links.
  4506. This includes angle, plain, and bracket links."
  4507. (catch :exit
  4508. (while (re-search-forward org-link-any-re limit t)
  4509. (let* ((start (match-beginning 0))
  4510. (end (match-end 0))
  4511. (visible-start (or (match-beginning 3) (match-beginning 2)))
  4512. (visible-end (or (match-end 3) (match-end 2)))
  4513. (style (cond ((eq ?< (char-after start)) 'angle)
  4514. ((eq ?\[ (char-after (1+ start))) 'bracket)
  4515. (t 'plain))))
  4516. (when (and (memq style org-highlight-links)
  4517. ;; Do not span over paragraph boundaries.
  4518. (not (string-match-p org-element-paragraph-separate
  4519. (match-string 0)))
  4520. ;; Do not confuse plain links with tags.
  4521. (not (and (eq style 'plain)
  4522. (let ((face (get-text-property
  4523. (max (1- start) (point-min)) 'face)))
  4524. (if (consp face) (memq 'org-tag face)
  4525. (eq 'org-tag face))))))
  4526. (let* ((link-object (save-excursion
  4527. (goto-char start)
  4528. (save-match-data (org-element-link-parser))))
  4529. (link (org-element-property :raw-link link-object))
  4530. (type (org-element-property :type link-object))
  4531. (path (org-element-property :path link-object))
  4532. (face-property (pcase (org-link-get-parameter type :face)
  4533. ((and (pred functionp) face) (funcall face path))
  4534. ((and (pred facep) face) face)
  4535. ((and (pred consp) face) face) ;anonymous
  4536. (_ 'org-link)))
  4537. (properties ;for link's visible part
  4538. (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
  4539. 'highlight)
  4540. 'keymap (or (org-link-get-parameter type :keymap)
  4541. org-mouse-map)
  4542. 'help-echo (pcase (org-link-get-parameter type :help-echo)
  4543. ((and (pred stringp) echo) echo)
  4544. ((and (pred functionp) echo) echo)
  4545. (_ (concat "LINK: " link)))
  4546. 'htmlize-link (pcase (org-link-get-parameter type
  4547. :htmlize-link)
  4548. ((and (pred functionp) f) (funcall f))
  4549. (_ `(:uri ,link)))
  4550. 'font-lock-multiline t)))
  4551. (org-remove-flyspell-overlays-in start end)
  4552. (org-rear-nonsticky-at end)
  4553. (if (not (eq 'bracket style))
  4554. (progn
  4555. (add-face-text-property start end face-property)
  4556. (add-text-properties start end properties))
  4557. ;; Handle invisible parts in bracket links.
  4558. (remove-text-properties start end '(invisible nil))
  4559. (let ((hidden
  4560. (append `(invisible
  4561. ,(or (org-link-get-parameter type :display)
  4562. 'org-link))
  4563. properties)))
  4564. (add-text-properties start visible-start hidden)
  4565. (add-face-text-property start end face-property)
  4566. (add-text-properties visible-start visible-end properties)
  4567. (add-text-properties visible-end end hidden)
  4568. (org-rear-nonsticky-at visible-start)
  4569. (org-rear-nonsticky-at visible-end)))
  4570. (let ((f (org-link-get-parameter type :activate-func)))
  4571. (when (functionp f)
  4572. (funcall f start end path (eq style 'bracket))))
  4573. (throw :exit t))))) ;signal success
  4574. nil))
  4575. (defun org-activate-code (limit)
  4576. (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
  4577. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4578. (remove-text-properties (match-beginning 0) (match-end 0)
  4579. '(display t invisible t intangible t))
  4580. t))
  4581. (defcustom org-src-fontify-natively t
  4582. "When non-nil, fontify code in code blocks.
  4583. See also the `org-block' face."
  4584. :type 'boolean
  4585. :version "26.1"
  4586. :package-version '(Org . "8.3")
  4587. :group 'org-appearance
  4588. :group 'org-babel)
  4589. (defcustom org-allow-promoting-top-level-subtree nil
  4590. "When non-nil, allow promoting a top level subtree.
  4591. The leading star of the top level headline will be replaced
  4592. by a #."
  4593. :type 'boolean
  4594. :version "24.1"
  4595. :group 'org-appearance)
  4596. (defun org-fontify-meta-lines-and-blocks (limit)
  4597. (condition-case nil
  4598. (org-fontify-meta-lines-and-blocks-1 limit)
  4599. (error (message "Org mode fontification error in %S at %d"
  4600. (current-buffer)
  4601. (line-number-at-pos)))))
  4602. (defun org-fontify-meta-lines-and-blocks-1 (limit)
  4603. "Fontify #+ lines and blocks."
  4604. (let ((case-fold-search t))
  4605. (when (re-search-forward
  4606. (rx bol (group (zero-or-more (any " \t")) "#"
  4607. (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
  4608. (any " \t")
  4609. eol))
  4610. (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
  4611. (zero-or-more (any " \t"))
  4612. (group (group (zero-or-more (not (any " \t\n"))))
  4613. (zero-or-more (any " \t"))
  4614. (group (zero-or-more any)))))
  4615. limit t)
  4616. (let ((beg (match-beginning 0))
  4617. (end-of-beginline (match-end 0))
  4618. ;; Including \n at end of #+begin line will include \n
  4619. ;; after the end of block content.
  4620. (block-start (match-end 0))
  4621. (block-end nil)
  4622. (lang (match-string 7)) ; The language, if it is a source block.
  4623. (bol-after-beginline (line-beginning-position 2))
  4624. (dc1 (downcase (match-string 2)))
  4625. (dc3 (downcase (match-string 3)))
  4626. (whole-blockline org-fontify-whole-block-delimiter-line)
  4627. beg-of-endline end-of-endline nl-before-endline quoting block-type)
  4628. (cond
  4629. ((and (match-end 4) (equal dc3 "+begin"))
  4630. ;; Truly a block
  4631. (setq block-type (downcase (match-string 5))
  4632. ;; Src, example, export, maybe more.
  4633. quoting (member block-type org-protecting-blocks))
  4634. (when (re-search-forward
  4635. (rx-to-string `(group bol (or (seq (one-or-more "*") space)
  4636. (seq (zero-or-more (any " \t"))
  4637. "#+end"
  4638. ,(match-string 4)
  4639. word-end
  4640. (zero-or-more any)))))
  4641. ;; We look further than LIMIT on purpose.
  4642. nil t)
  4643. ;; We do have a matching #+end line.
  4644. (setq beg-of-endline (match-beginning 0)
  4645. end-of-endline (match-end 0)
  4646. nl-before-endline (1- (match-beginning 0)))
  4647. (setq block-end (match-beginning 0)) ; Include the final newline.
  4648. (when quoting
  4649. (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
  4650. (remove-text-properties beg end-of-endline
  4651. '(display t invisible t intangible t)))
  4652. (add-text-properties
  4653. beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
  4654. (org-remove-flyspell-overlays-in beg bol-after-beginline)
  4655. (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
  4656. (cond
  4657. ((and lang (not (string= lang "")) org-src-fontify-natively)
  4658. (save-match-data
  4659. (org-src-font-lock-fontify-block lang block-start block-end))
  4660. (add-text-properties bol-after-beginline block-end '(src-block t)))
  4661. (quoting
  4662. (add-text-properties
  4663. bol-after-beginline beg-of-endline
  4664. (list 'face
  4665. (list :inherit
  4666. (let ((face-name
  4667. (intern (format "org-block-%s" lang))))
  4668. (append (and (facep face-name) (list face-name))
  4669. '(org-block)))))))
  4670. ((not org-fontify-quote-and-verse-blocks))
  4671. ((string= block-type "quote")
  4672. (add-face-text-property
  4673. bol-after-beginline beg-of-endline 'org-quote t))
  4674. ((string= block-type "verse")
  4675. (add-face-text-property
  4676. bol-after-beginline beg-of-endline 'org-verse t)))
  4677. ;; Fontify the #+begin and #+end lines of the blocks
  4678. (add-text-properties
  4679. beg (if whole-blockline bol-after-beginline end-of-beginline)
  4680. '(face org-block-begin-line))
  4681. (unless (eq (char-after beg-of-endline) ?*)
  4682. (add-text-properties
  4683. beg-of-endline
  4684. (if whole-blockline
  4685. (let ((beg-of-next-line (1+ end-of-endline)))
  4686. (min (point-max) beg-of-next-line))
  4687. (min (point-max) end-of-endline))
  4688. '(face org-block-end-line)))
  4689. t))
  4690. ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
  4691. (org-remove-flyspell-overlays-in
  4692. (match-beginning 0)
  4693. (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
  4694. (add-text-properties
  4695. beg (match-end 3)
  4696. (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
  4697. '(font-lock-fontified t invisible t)
  4698. '(font-lock-fontified t face org-document-info-keyword)))
  4699. (add-text-properties
  4700. (match-beginning 6) (min (point-max) (1+ (match-end 6)))
  4701. (if (string-equal dc1 "+title:")
  4702. '(font-lock-fontified t face org-document-title)
  4703. '(font-lock-fontified t face org-document-info))))
  4704. ((string-prefix-p "+caption" dc1)
  4705. (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
  4706. (remove-text-properties (match-beginning 0) (match-end 0)
  4707. '(display t invisible t intangible t))
  4708. ;; Handle short captions
  4709. (save-excursion
  4710. (beginning-of-line)
  4711. (looking-at (rx (group (zero-or-more (any " \t"))
  4712. "#+caption"
  4713. (optional "[" (zero-or-more any) "]")
  4714. ":")
  4715. (zero-or-more (any " \t")))))
  4716. (add-text-properties (line-beginning-position) (match-end 1)
  4717. '(font-lock-fontified t face org-meta-line))
  4718. (add-text-properties (match-end 0) (line-end-position)
  4719. '(font-lock-fontified t face org-block))
  4720. t)
  4721. ((member dc3 '(" " ""))
  4722. ;; Just a comment, the plus was not there
  4723. (org-remove-flyspell-overlays-in beg (match-end 0))
  4724. (add-text-properties
  4725. beg (match-end 0)
  4726. '(font-lock-fontified t face font-lock-comment-face)))
  4727. (t ;; Just any other in-buffer setting, but not indented
  4728. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4729. (remove-text-properties (match-beginning 0) (match-end 0)
  4730. '(display t invisible t intangible t))
  4731. (add-text-properties beg (match-end 0)
  4732. '(font-lock-fontified t face org-meta-line))
  4733. t))))))
  4734. (defun org-fontify-drawers (limit)
  4735. "Fontify drawers."
  4736. (when (re-search-forward org-drawer-regexp limit t)
  4737. (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
  4738. '(font-lock-fontified t face org-drawer))
  4739. (org-remove-flyspell-overlays-in
  4740. (line-beginning-position) (line-beginning-position 2))
  4741. t))
  4742. (defun org-fontify-macros (limit)
  4743. "Fontify macros."
  4744. (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
  4745. (let ((begin (match-beginning 0))
  4746. (opening-end (match-beginning 1)))
  4747. (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
  4748. (match-string 1))
  4749. (let ((end (match-end 1))
  4750. (closing-start (match-beginning 1)))
  4751. (add-text-properties
  4752. begin end
  4753. '(font-lock-multiline t font-lock-fontified t face org-macro))
  4754. (org-remove-flyspell-overlays-in begin end)
  4755. (when org-hide-macro-markers
  4756. (add-text-properties begin opening-end '(invisible t))
  4757. (add-text-properties closing-start end '(invisible t)))
  4758. t)))))
  4759. (defun org-fontify-extend-region (beg end _old-len)
  4760. (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
  4761. (1+ end) end))
  4762. (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
  4763. (end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
  4764. (extend
  4765. (lambda (r1 r2 dir)
  4766. (let ((re (replace-regexp-in-string
  4767. "\\(begin\\|end\\)" r1
  4768. (replace-regexp-in-string
  4769. "[][]" r2
  4770. (match-string-no-properties 0)))))
  4771. (re-search-forward (regexp-quote re) nil t dir)))))
  4772. (goto-char beg)
  4773. (back-to-indentation)
  4774. (save-match-data
  4775. (cond ((looking-at end-re)
  4776. (cons (or (funcall extend "begin" "[" -1) beg) end))
  4777. ((looking-at begin-re)
  4778. (cons beg (or (funcall extend "end" "]" 1) end)))
  4779. (t (cons beg end))))))
  4780. (defun org-activate-footnote-links (limit)
  4781. "Add text properties for footnotes."
  4782. (let ((fn (org-footnote-next-reference-or-definition limit)))
  4783. (when fn
  4784. (let* ((beg (nth 1 fn))
  4785. (end (nth 2 fn))
  4786. (label (car fn))
  4787. (referencep (/= (line-beginning-position) beg)))
  4788. (when (and referencep (nth 3 fn))
  4789. (save-excursion
  4790. (goto-char beg)
  4791. (search-forward (or label "fn:"))
  4792. (org-remove-flyspell-overlays-in beg (match-end 0))))
  4793. (add-text-properties beg end
  4794. (list 'mouse-face 'highlight
  4795. 'keymap org-mouse-map
  4796. 'help-echo
  4797. (if referencep "Footnote reference"
  4798. "Footnote definition")
  4799. 'font-lock-fontified t
  4800. 'font-lock-multiline t
  4801. 'face 'org-footnote))))))
  4802. (defun org-activate-dates (limit)
  4803. "Add text properties for dates."
  4804. (when (and (re-search-forward org-tsr-regexp-both limit t)
  4805. (not (equal (char-before (match-beginning 0)) 91)))
  4806. (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
  4807. (add-text-properties (match-beginning 0) (match-end 0)
  4808. (list 'mouse-face 'highlight
  4809. 'keymap org-mouse-map))
  4810. (org-rear-nonsticky-at (match-end 0))
  4811. (when org-display-custom-times
  4812. ;; If it's a date range, activate custom time for second date.
  4813. (when (match-end 3)
  4814. (org-display-custom-time (match-beginning 3) (match-end 3)))
  4815. (org-display-custom-time (match-beginning 1) (match-end 1)))
  4816. t))
  4817. (defun org-activate-target-links (limit)
  4818. "Add text properties for target matches."
  4819. (when org-target-link-regexp
  4820. (let ((case-fold-search t))
  4821. ;; `org-target-link-regexp' matches one character before the
  4822. ;; actual target.
  4823. (unless (bolp) (forward-char -1))
  4824. (when (re-search-forward org-target-link-regexp 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. 'help-echo "Radio target link"
  4830. 'org-linked-text t))
  4831. (org-rear-nonsticky-at (match-end 1))
  4832. t))))
  4833. (defvar org-latex-and-related-regexp nil
  4834. "Regular expression for highlighting LaTeX, entities and sub/superscript.")
  4835. (defun org-compute-latex-and-related-regexp ()
  4836. "Compute regular expression for LaTeX, entities and sub/superscript.
  4837. Result depends on variable `org-highlight-latex-and-related'."
  4838. (let ((re-sub
  4839. (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
  4840. ((eq org-use-sub-superscripts '{})
  4841. (list org-match-substring-with-braces-regexp))
  4842. (org-use-sub-superscripts (list org-match-substring-regexp))))
  4843. (re-latex
  4844. (when (or (memq 'latex org-highlight-latex-and-related)
  4845. (memq 'native org-highlight-latex-and-related))
  4846. (let ((matchers (plist-get org-format-latex-options :matchers)))
  4847. (delq nil
  4848. (mapcar (lambda (x)
  4849. (and (member (car x) matchers) (nth 1 x)))
  4850. org-latex-regexps)))))
  4851. (re-entities
  4852. (when (memq 'entities org-highlight-latex-and-related)
  4853. (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
  4854. \\($\\|{}\\|[^[:alpha:]]\\)"))))
  4855. (setq-local org-latex-and-related-regexp
  4856. (mapconcat #'identity
  4857. (append re-latex re-entities re-sub)
  4858. "\\|"))))
  4859. (defun org-do-latex-and-related (limit)
  4860. "Highlight LaTeX snippets and environments, entities and sub/superscript.
  4861. Stop at first highlighted object, if any. Return t if some
  4862. highlighting was done, nil otherwise."
  4863. (when (org-string-nw-p org-latex-and-related-regexp)
  4864. (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
  4865. (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
  4866. (catch 'found
  4867. (while (and (< (point) limit)
  4868. (re-search-forward org-latex-and-related-regexp nil t))
  4869. (cond
  4870. ((>= (match-beginning 0) limit)
  4871. (throw 'found nil))
  4872. ((cl-some (lambda (f)
  4873. (memq f '(org-code org-verbatim underline
  4874. org-special-keyword)))
  4875. (save-excursion
  4876. (goto-char (1+ (match-beginning 0)))
  4877. (face-at-point nil t))))
  4878. ;; Try to limit false positives. In this case, ignore
  4879. ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
  4880. ;; contain an empty line.
  4881. ((save-excursion
  4882. (goto-char (match-beginning 0))
  4883. (and (looking-at-p latex-prefix-re)
  4884. (save-match-data
  4885. (re-search-forward blank-line-re (1- (match-end 0)) t)))))
  4886. (t
  4887. (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
  4888. '(?_ ?^))
  4889. 1
  4890. 0))
  4891. (start (+ offset (match-beginning 0)))
  4892. (end (match-end 0)))
  4893. (if (memq 'native org-highlight-latex-and-related)
  4894. (org-src-font-lock-fontify-block "latex" start end)
  4895. (font-lock-prepend-text-property start end
  4896. 'face 'org-latex-and-related))
  4897. (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
  4898. '(font-lock-multiline t))
  4899. (throw 'found t)))))
  4900. nil))))
  4901. (defun org-restart-font-lock ()
  4902. "Restart `font-lock-mode', to force refontification."
  4903. (when font-lock-mode
  4904. (font-lock-mode -1)
  4905. (font-lock-mode 1)))
  4906. (defun org-activate-tags (limit)
  4907. (when (re-search-forward org-tag-line-re limit t)
  4908. (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
  4909. (add-text-properties (match-beginning 1) (match-end 1)
  4910. (list 'mouse-face 'highlight
  4911. 'keymap org-mouse-map))
  4912. (org-rear-nonsticky-at (match-end 1))
  4913. t))
  4914. (defun org-outline-level ()
  4915. "Compute the outline level of the heading at point.
  4916. If this is called at a normal headline, the level is the number
  4917. of stars. Use `org-reduced-level' to remove the effect of
  4918. `org-odd-levels'. Unlike to `org-current-level', this function
  4919. takes into consideration inlinetasks."
  4920. (org-with-wide-buffer
  4921. (end-of-line)
  4922. (if (re-search-backward org-outline-regexp-bol nil t)
  4923. (1- (- (match-end 0) (match-beginning 0)))
  4924. 0)))
  4925. (defvar org-font-lock-keywords nil)
  4926. (defsubst org-re-property (property &optional literal allow-null value)
  4927. "Return a regexp matching a PROPERTY line.
  4928. When optional argument LITERAL is non-nil, do not quote PROPERTY.
  4929. This is useful when PROPERTY is a regexp. When ALLOW-NULL is
  4930. non-nil, match properties even without a value.
  4931. Match group 3 is set to the value when it exists. If there is no
  4932. value and ALLOW-NULL is non-nil, it is set to the empty string.
  4933. With optional argument VALUE, match only property lines with
  4934. that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
  4935. unless LITERAL is non-nil."
  4936. (concat
  4937. "^\\(?4:[ \t]*\\)"
  4938. (format "\\(?1::\\(?2:%s\\):\\)"
  4939. (if literal property (regexp-quote property)))
  4940. (cond (value
  4941. (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
  4942. (if literal value (regexp-quote value))))
  4943. (allow-null
  4944. "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
  4945. (t
  4946. "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
  4947. (defconst org-property-re
  4948. (org-re-property "\\S-+" 'literal t)
  4949. "Regular expression matching a property line.
  4950. There are four matching groups:
  4951. 1: :PROPKEY: including the leading and trailing colon,
  4952. 2: PROPKEY without the leading and trailing colon,
  4953. 3: PROPVAL without leading or trailing spaces,
  4954. 4: the indentation of the current line,
  4955. 5: trailing whitespace.")
  4956. (defvar org-font-lock-hook nil
  4957. "Functions to be called for special font lock stuff.")
  4958. (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
  4959. (defvar org-font-lock-set-keywords-hook nil
  4960. "Functions that can manipulate `org-font-lock-extra-keywords'.
  4961. This is called after `org-font-lock-extra-keywords' is defined, but before
  4962. it is installed to be used by font lock. This can be useful if something
  4963. needs to be inserted at a specific position in the font-lock sequence.")
  4964. (defun org-font-lock-hook (limit)
  4965. "Run `org-font-lock-hook' within LIMIT."
  4966. (run-hook-with-args 'org-font-lock-hook limit))
  4967. (defun org-set-font-lock-defaults ()
  4968. "Set font lock defaults for the current buffer."
  4969. (let ((org-font-lock-extra-keywords
  4970. (list
  4971. ;; Call the hook
  4972. '(org-font-lock-hook)
  4973. ;; Headlines
  4974. `(,(if org-fontify-whole-heading-line
  4975. "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
  4976. "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
  4977. (1 (org-get-level-face 1))
  4978. (2 (org-get-level-face 2))
  4979. (3 (org-get-level-face 3)))
  4980. ;; Table lines
  4981. '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
  4982. (1 'org-table t))
  4983. ;; Table internals
  4984. '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
  4985. '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
  4986. '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
  4987. '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
  4988. ;; Properties
  4989. (list org-property-re
  4990. '(1 'org-special-keyword t)
  4991. '(3 'org-property-value t))
  4992. ;; Drawers
  4993. '(org-fontify-drawers)
  4994. ;; Link related fontification.
  4995. '(org-activate-links)
  4996. (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
  4997. (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
  4998. (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
  4999. (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
  5000. ;; Targets.
  5001. (list org-radio-target-regexp '(0 'org-target t))
  5002. (list org-target-regexp '(0 'org-target t))
  5003. ;; Diary sexps.
  5004. '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
  5005. ;; Macro
  5006. '(org-fontify-macros)
  5007. ;; TODO keyword
  5008. (list (format org-heading-keyword-regexp-format
  5009. org-todo-regexp)
  5010. '(2 (org-get-todo-face 2) prepend))
  5011. ;; TODO
  5012. (when org-fontify-todo-headline
  5013. (list (format org-heading-keyword-regexp-format
  5014. (concat
  5015. "\\(?:"
  5016. (mapconcat 'regexp-quote org-not-done-keywords "\\|")
  5017. "\\)"))
  5018. '(2 'org-headline-todo prepend)))
  5019. ;; DONE
  5020. (when org-fontify-done-headline
  5021. (list (format org-heading-keyword-regexp-format
  5022. (concat
  5023. "\\(?:"
  5024. (mapconcat 'regexp-quote org-done-keywords "\\|")
  5025. "\\)"))
  5026. '(2 'org-headline-done prepend)))
  5027. ;; Priorities
  5028. '(org-font-lock-add-priority-faces)
  5029. ;; Tags
  5030. '(org-font-lock-add-tag-faces)
  5031. ;; Tags groups
  5032. (when (and org-group-tags org-tag-groups-alist)
  5033. (list (concat org-outline-regexp-bol ".+\\(:"
  5034. (regexp-opt (mapcar 'car org-tag-groups-alist))
  5035. ":\\).*$")
  5036. '(1 'org-tag-group prepend)))
  5037. ;; Special keywords
  5038. (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
  5039. (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
  5040. (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
  5041. (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
  5042. ;; Emphasis
  5043. (when org-fontify-emphasized-text '(org-do-emphasis-faces))
  5044. ;; Checkboxes
  5045. '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
  5046. 1 'org-checkbox prepend)
  5047. (when (cdr (assq 'checkbox org-list-automatic-rules))
  5048. '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
  5049. (0 (org-get-checkbox-statistics-face) prepend)))
  5050. ;; Description list items
  5051. '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
  5052. 1 'org-list-dt prepend)
  5053. ;; Inline export snippets
  5054. '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
  5055. (1 'font-lock-comment-face t)
  5056. (2 'org-tag t)
  5057. (3 'font-lock-comment-face t))
  5058. ;; ARCHIVEd headings
  5059. (list (concat
  5060. org-outline-regexp-bol
  5061. "\\(.*:" org-archive-tag ":.*\\)")
  5062. '(1 'org-archived prepend))
  5063. ;; Specials
  5064. '(org-do-latex-and-related)
  5065. '(org-fontify-entities)
  5066. '(org-raise-scripts)
  5067. ;; Code
  5068. '(org-activate-code (1 'org-code t))
  5069. ;; COMMENT
  5070. (list (format
  5071. "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
  5072. org-todo-regexp
  5073. org-comment-string)
  5074. '(9 'org-special-keyword t))
  5075. ;; Blocks and meta lines
  5076. '(org-fontify-meta-lines-and-blocks)
  5077. ;; Citations
  5078. '(org-cite-activate))))
  5079. (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
  5080. (run-hooks 'org-font-lock-set-keywords-hook)
  5081. ;; Now set the full font-lock-keywords
  5082. (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
  5083. (setq-local font-lock-defaults
  5084. '(org-font-lock-keywords t nil nil backward-paragraph))
  5085. (setq-local font-lock-extend-after-change-region-function
  5086. #'org-fontify-extend-region)
  5087. (kill-local-variable 'font-lock-keywords)
  5088. nil))
  5089. (defun org-toggle-pretty-entities ()
  5090. "Toggle the composition display of entities as UTF8 characters."
  5091. (interactive)
  5092. (setq-local org-pretty-entities (not org-pretty-entities))
  5093. (org-restart-font-lock)
  5094. (if org-pretty-entities
  5095. (message "Entities are now displayed as UTF8 characters")
  5096. (save-restriction
  5097. (widen)
  5098. (decompose-region (point-min) (point-max))
  5099. (message "Entities are now displayed as plain text"))))
  5100. (defvar-local org-custom-properties-overlays nil
  5101. "List of overlays used for custom properties.")
  5102. (defun org-toggle-custom-properties-visibility ()
  5103. "Display or hide properties in `org-custom-properties'."
  5104. (interactive)
  5105. (if org-custom-properties-overlays
  5106. (progn (mapc #'delete-overlay org-custom-properties-overlays)
  5107. (setq org-custom-properties-overlays nil))
  5108. (when org-custom-properties
  5109. (org-with-wide-buffer
  5110. (goto-char (point-min))
  5111. (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
  5112. (while (re-search-forward regexp nil t)
  5113. (let ((end (cdr (save-match-data (org-get-property-block)))))
  5114. (when (and end (< (point) end))
  5115. ;; Hide first custom property in current drawer.
  5116. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5117. (overlay-put o 'invisible t)
  5118. (overlay-put o 'org-custom-property t)
  5119. (push o org-custom-properties-overlays))
  5120. ;; Hide additional custom properties in the same drawer.
  5121. (while (re-search-forward regexp end t)
  5122. (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
  5123. (overlay-put o 'invisible t)
  5124. (overlay-put o 'org-custom-property t)
  5125. (push o org-custom-properties-overlays)))))
  5126. ;; Each entry is limited to a single property drawer.
  5127. (outline-next-heading)))))))
  5128. (defun org-fontify-entities (limit)
  5129. "Find an entity to fontify."
  5130. (let (ee)
  5131. (when org-pretty-entities
  5132. (catch 'match
  5133. ;; "\_ "-family is left out on purpose. Only the first one,
  5134. ;; i.e., "\_ ", could be fontified anyway, and it would be
  5135. ;; confusing when adding a second white space character.
  5136. (while (re-search-forward
  5137. "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
  5138. limit t)
  5139. (when (and (not (org-at-comment-p))
  5140. (setq ee (org-entity-get (match-string 1)))
  5141. (= (length (nth 6 ee)) 1))
  5142. (let* ((end (if (equal (match-string 2) "{}")
  5143. (match-end 2)
  5144. (match-end 1))))
  5145. (add-text-properties
  5146. (match-beginning 0) end
  5147. (list 'font-lock-fontified t))
  5148. (compose-region (match-beginning 0) end
  5149. (nth 6 ee) nil)
  5150. (backward-char 1)
  5151. (throw 'match t))))
  5152. nil))))
  5153. (defun org-fontify-like-in-org-mode (s &optional odd-levels)
  5154. "Fontify string S like in Org mode."
  5155. (with-temp-buffer
  5156. (insert s)
  5157. (let ((org-odd-levels-only odd-levels))
  5158. (org-mode)
  5159. (org-font-lock-ensure)
  5160. (buffer-string))))
  5161. (defun org-get-level-face (n)
  5162. "Get the right face for match N in font-lock matching of headlines."
  5163. (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
  5164. (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
  5165. (org-f (if org-cycle-level-faces
  5166. (nth (% (1- org-l) org-n-level-faces) org-level-faces)
  5167. (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
  5168. (cond
  5169. ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
  5170. ((eq n 2) org-f)
  5171. (t (unless org-level-color-stars-only org-f)))))
  5172. (defun org-face-from-face-or-color (context inherit face-or-color)
  5173. "Create a face list that inherits INHERIT, but sets the foreground color.
  5174. When FACE-OR-COLOR is not a string, just return it."
  5175. (if (stringp face-or-color)
  5176. (list :inherit inherit
  5177. (cdr (assoc context org-faces-easy-properties))
  5178. face-or-color)
  5179. face-or-color))
  5180. (defun org-get-todo-face (kwd)
  5181. "Get the right face for a TODO keyword KWD.
  5182. If KWD is a number, get the corresponding match group."
  5183. (when (numberp kwd) (setq kwd (match-string kwd)))
  5184. (or (org-face-from-face-or-color
  5185. 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
  5186. (and (member kwd org-done-keywords) 'org-done)
  5187. 'org-todo))
  5188. (defun org-get-priority-face (priority)
  5189. "Get the right face for PRIORITY.
  5190. PRIORITY is a character."
  5191. (or (org-face-from-face-or-color
  5192. 'priority 'org-priority (cdr (assq priority org-priority-faces)))
  5193. 'org-priority))
  5194. (defun org-get-tag-face (tag)
  5195. "Get the right face for TAG.
  5196. If TAG is a number, get the corresponding match group."
  5197. (let ((tag (if (wholenump tag) (match-string tag) tag)))
  5198. (or (org-face-from-face-or-color
  5199. 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
  5200. 'org-tag)))
  5201. (defvar org-priority-regexp) ; defined later in the file
  5202. (defun org-font-lock-add-priority-faces (limit)
  5203. "Add the special priority faces."
  5204. (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
  5205. (let ((beg (match-beginning 1))
  5206. (end (1+ (match-end 2))))
  5207. (add-face-text-property
  5208. beg end
  5209. (org-get-priority-face (string-to-char (match-string 2))))
  5210. (add-text-properties
  5211. beg end
  5212. (list 'font-lock-fontified t)))))
  5213. (defun org-font-lock-add-tag-faces (limit)
  5214. "Add the special tag faces."
  5215. (when (and org-tag-faces org-tags-special-faces-re)
  5216. (while (re-search-forward org-tags-special-faces-re limit t)
  5217. (add-face-text-property
  5218. (match-beginning 1)
  5219. (match-end 1)
  5220. (org-get-tag-face 1))
  5221. (add-text-properties (match-beginning 1) (match-end 1)
  5222. (list 'font-lock-fontified t))
  5223. (backward-char 1))))
  5224. (defun org-unfontify-region (beg end &optional _maybe_loudly)
  5225. "Remove fontification and activation overlays from links."
  5226. (font-lock-default-unfontify-region beg end)
  5227. (let* ((buffer-undo-list t)
  5228. (inhibit-read-only t) (inhibit-point-motion-hooks t)
  5229. (inhibit-modification-hooks t)
  5230. deactivate-mark buffer-file-name buffer-file-truename)
  5231. (decompose-region beg end)
  5232. (remove-text-properties beg end
  5233. '(mouse-face t keymap t org-linked-text t
  5234. invisible t intangible t
  5235. org-emphasis t))
  5236. (org-remove-font-lock-display-properties beg end)))
  5237. (defconst org-script-display '(((raise -0.3) (height 0.7))
  5238. ((raise 0.3) (height 0.7))
  5239. ((raise -0.5))
  5240. ((raise 0.5)))
  5241. "Display properties for showing superscripts and subscripts.")
  5242. (defun org-remove-font-lock-display-properties (beg end)
  5243. "Remove specific display properties that have been added by font lock.
  5244. The will remove the raise properties that are used to show superscripts
  5245. and subscripts."
  5246. (let (next prop)
  5247. (while (< beg end)
  5248. (setq next (next-single-property-change beg 'display nil end)
  5249. prop (get-text-property beg 'display))
  5250. (when (member prop org-script-display)
  5251. (put-text-property beg next 'display nil))
  5252. (setq beg next))))
  5253. (defun org-raise-scripts (limit)
  5254. "Add raise properties to sub/superscripts."
  5255. (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
  5256. (re-search-forward
  5257. (if (eq org-use-sub-superscripts t)
  5258. org-match-substring-regexp
  5259. org-match-substring-with-braces-regexp)
  5260. limit t))
  5261. (let* ((pos (point)) table-p comment-p
  5262. (mpos (match-beginning 3))
  5263. (emph-p (get-text-property mpos 'org-emphasis))
  5264. (link-p (get-text-property mpos 'mouse-face))
  5265. (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
  5266. (goto-char (point-at-bol))
  5267. (setq table-p (looking-at-p org-table-dataline-regexp)
  5268. comment-p (looking-at-p "^[ \t]*#[ +]"))
  5269. (goto-char pos)
  5270. ;; Handle a_b^c
  5271. (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
  5272. (unless (or comment-p emph-p link-p keyw-p)
  5273. (put-text-property (match-beginning 3) (match-end 0)
  5274. 'display
  5275. (if (equal (char-after (match-beginning 2)) ?^)
  5276. (nth (if table-p 3 1) org-script-display)
  5277. (nth (if table-p 2 0) org-script-display)))
  5278. (add-text-properties (match-beginning 2) (match-end 2)
  5279. (list 'invisible t))
  5280. (when (and (eq (char-after (match-beginning 3)) ?{)
  5281. (eq (char-before (match-end 3)) ?}))
  5282. (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
  5283. (list 'invisible t))
  5284. (add-text-properties (1- (match-end 3)) (match-end 3)
  5285. (list 'invisible t))))
  5286. t)))
  5287. (defun org-remove-empty-overlays-at (pos)
  5288. "Remove outline overlays that do not contain non-white stuff."
  5289. (dolist (o (overlays-at pos))
  5290. (and (eq 'outline (overlay-get o 'invisible))
  5291. (not (string-match-p
  5292. "\\S-" (buffer-substring (overlay-start o)
  5293. (overlay-end o))))
  5294. (delete-overlay o))))
  5295. (defun org-show-empty-lines-in-parent ()
  5296. "Move to the parent and re-show empty lines before visible headlines."
  5297. (save-excursion
  5298. (let ((context (if (org-up-heading-safe) 'children 'overview)))
  5299. (org-cycle-show-empty-lines context))))
  5300. (defun org-files-list ()
  5301. "Return `org-agenda-files' list, plus all open Org files.
  5302. This is useful for operations that need to scan all of a user's
  5303. open and agenda-wise Org files."
  5304. (let ((files (mapcar #'expand-file-name (org-agenda-files))))
  5305. (dolist (buf (buffer-list))
  5306. (with-current-buffer buf
  5307. (when (and (derived-mode-p 'org-mode) (buffer-file-name))
  5308. (cl-pushnew (expand-file-name (buffer-file-name)) files
  5309. :test #'equal))))
  5310. files))
  5311. (defsubst org-entry-beginning-position ()
  5312. "Return the beginning position of the current entry."
  5313. (save-excursion (org-back-to-heading t) (point)))
  5314. (defsubst org-entry-end-position ()
  5315. "Return the end position of the current entry."
  5316. (save-excursion (outline-next-heading) (point)))
  5317. (defun org-subtree-end-visible-p ()
  5318. "Is the end of the current subtree visible?"
  5319. (pos-visible-in-window-p
  5320. (save-excursion (org-end-of-subtree t) (point))))
  5321. (defun org-first-headline-recenter ()
  5322. "Move cursor to the first headline and recenter the headline."
  5323. (let ((window (get-buffer-window)))
  5324. (when window
  5325. (goto-char (point-min))
  5326. (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
  5327. (set-window-start window (line-beginning-position))))))
  5328. ;;; Visibility (headlines, blocks, drawers)
  5329. ;;;; Headlines visibility
  5330. (defun org-show-entry ()
  5331. "Show the body directly following its heading.
  5332. Show the heading too, if it is currently invisible."
  5333. (interactive)
  5334. (save-excursion
  5335. (org-back-to-heading-or-point-min t)
  5336. (org-flag-region
  5337. (line-end-position 0)
  5338. (save-excursion
  5339. (if (re-search-forward
  5340. (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
  5341. (match-beginning 1)
  5342. (point-max)))
  5343. nil
  5344. 'outline)
  5345. (org-cycle-hide-drawers 'children)))
  5346. (defun org-hide-entry ()
  5347. "Hide the body directly following its heading."
  5348. (interactive)
  5349. (save-excursion
  5350. (org-back-to-heading-or-point-min t)
  5351. (when (org-at-heading-p) (forward-line))
  5352. (org-flag-region
  5353. (line-end-position 0)
  5354. (save-excursion
  5355. (if (re-search-forward
  5356. (concat "[\r\n]" org-outline-regexp) nil t)
  5357. (line-end-position 0)
  5358. (point-max)))
  5359. t
  5360. 'outline)))
  5361. (defun org-show-children (&optional level)
  5362. "Show all direct subheadings of this heading.
  5363. Prefix arg LEVEL is how many levels below the current level
  5364. should be shown. Default is enough to cause the following
  5365. heading to appear."
  5366. (interactive "p")
  5367. (unless (org-before-first-heading-p)
  5368. (save-excursion
  5369. (org-with-limited-levels (org-back-to-heading t))
  5370. (let* ((current-level (funcall outline-level))
  5371. (max-level (org-get-valid-level
  5372. current-level
  5373. (if level (prefix-numeric-value level) 1)))
  5374. (end (save-excursion (org-end-of-subtree t t)))
  5375. (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
  5376. (past-first-child nil)
  5377. ;; Make sure to skip inlinetasks.
  5378. (re (format regexp-fmt
  5379. current-level
  5380. (cond
  5381. ((not (featurep 'org-inlinetask)) "")
  5382. (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
  5383. 3))
  5384. (t (1- org-inlinetask-min-level))))))
  5385. ;; Display parent heading.
  5386. (org-flag-heading nil)
  5387. (forward-line)
  5388. ;; Display children. First child may be deeper than expected
  5389. ;; MAX-LEVEL. Since we want to display it anyway, adjust
  5390. ;; MAX-LEVEL accordingly.
  5391. (while (re-search-forward re end t)
  5392. (unless past-first-child
  5393. (setq re (format regexp-fmt
  5394. current-level
  5395. (max (funcall outline-level) max-level)))
  5396. (setq past-first-child t))
  5397. (org-flag-heading nil))))))
  5398. (defun org-show-subtree ()
  5399. "Show everything after this heading at deeper levels."
  5400. (interactive)
  5401. (org-flag-region
  5402. (point) (save-excursion (org-end-of-subtree t t)) nil 'outline))
  5403. ;;;; Blocks and drawers visibility
  5404. (defun org--hide-wrapper-toggle (element category force no-error)
  5405. "Toggle visibility for ELEMENT.
  5406. ELEMENT is a block or drawer type parsed element. CATEGORY is
  5407. either `block' or `drawer'. When FORCE is `off', show the block
  5408. or drawer. If it is non-nil, hide it unconditionally. Throw an
  5409. error when not at a block or drawer, unless NO-ERROR is non-nil.
  5410. Return a non-nil value when toggling is successful."
  5411. (let ((type (org-element-type element)))
  5412. (cond
  5413. ((memq type
  5414. (pcase category
  5415. (`drawer '(drawer property-drawer))
  5416. (`block '(center-block
  5417. comment-block dynamic-block example-block export-block
  5418. quote-block special-block src-block verse-block))
  5419. (_ (error "Unknown category: %S" category))))
  5420. (let* ((post (org-element-property :post-affiliated element))
  5421. (start (save-excursion
  5422. (goto-char post)
  5423. (line-end-position)))
  5424. (end (save-excursion
  5425. (goto-char (org-element-property :end element))
  5426. (skip-chars-backward " \t\n")
  5427. (line-end-position))))
  5428. ;; Do nothing when not before or at the block opening line or
  5429. ;; at the block closing line.
  5430. (unless (let ((eol (line-end-position)))
  5431. (and (> eol start) (/= eol end)))
  5432. (let* ((spec (if (eq category 'block) 'org-hide-block 'outline))
  5433. (flag
  5434. (cond ((eq force 'off) nil)
  5435. (force t)
  5436. ((eq spec (get-char-property start 'invisible)) nil)
  5437. (t t))))
  5438. (org-flag-region start end flag spec))
  5439. ;; When the block is hidden away, make sure point is left in
  5440. ;; a visible part of the buffer.
  5441. (when (invisible-p (max (1- (point)) (point-min)))
  5442. (goto-char post))
  5443. ;; Signal success.
  5444. t)))
  5445. (no-error nil)
  5446. (t
  5447. (user-error (if (eq category 'drawer)
  5448. "Not at a drawer"
  5449. "Not at a block"))))))
  5450. (defun org-hide-block-toggle (&optional force no-error element)
  5451. "Toggle the visibility of the current block.
  5452. When optional argument FORCE is `off', make block visible. If it
  5453. is non-nil, hide it unconditionally. Throw an error when not at
  5454. a block, unless NO-ERROR is non-nil. When optional argument
  5455. ELEMENT is provided, consider it instead of the current block.
  5456. Return a non-nil value when toggling is successful."
  5457. (interactive)
  5458. (org--hide-wrapper-toggle
  5459. (or element (org-element-at-point)) 'block force no-error))
  5460. (defun org-hide-drawer-toggle (&optional force no-error element)
  5461. "Toggle the visibility of the current drawer.
  5462. When optional argument FORCE is `off', make drawer visible. If
  5463. it is non-nil, hide it unconditionally. Throw an error when not
  5464. at a drawer, unless NO-ERROR is non-nil. When optional argument
  5465. ELEMENT is provided, consider it instead of the current drawer.
  5466. Return a non-nil value when toggling is successful."
  5467. (interactive)
  5468. (org--hide-wrapper-toggle
  5469. (or element (org-element-at-point)) 'drawer force no-error))
  5470. (defun org-hide-block-all ()
  5471. "Fold all blocks in the current buffer."
  5472. (interactive)
  5473. (org-show-all '(blocks))
  5474. (org-block-map 'org-hide-block-toggle))
  5475. (defun org-hide-drawer-all ()
  5476. "Fold all drawers in the current buffer."
  5477. (let ((begin (point-min))
  5478. (end (point-max)))
  5479. (org--hide-drawers begin end)))
  5480. (defun org-cycle-hide-drawers (state)
  5481. "Re-hide all drawers after a visibility state change.
  5482. STATE should be one of the symbols listed in the docstring of
  5483. `org-cycle-hook'."
  5484. (when (derived-mode-p 'org-mode)
  5485. (cond ((not (memq state '(overview folded contents)))
  5486. (let* ((global? (eq state 'all))
  5487. (beg (if global? (point-min) (line-beginning-position)))
  5488. (end (cond (global? (point-max))
  5489. ((eq state 'children) (org-entry-end-position))
  5490. (t (save-excursion (org-end-of-subtree t t))))))
  5491. (org--hide-drawers beg end)))
  5492. ((memq state '(overview contents))
  5493. ;; Hide drawers before first heading.
  5494. (let ((beg (point-min))
  5495. (end (save-excursion
  5496. (goto-char (point-min))
  5497. (if (org-before-first-heading-p)
  5498. (org-entry-end-position)
  5499. (point-min)))))
  5500. (when (< beg end)
  5501. (org--hide-drawers beg end)))))))
  5502. (defun org--hide-drawers (begin end)
  5503. "Hide all drawers between BEGIN and END."
  5504. (save-excursion
  5505. (goto-char begin)
  5506. (while (re-search-forward org-drawer-regexp end t)
  5507. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5508. 'invisible))
  5509. (o (cdr-safe pair)))
  5510. (if (overlayp o) (goto-char (overlay-end o)) ;invisible drawer
  5511. (pcase (get-char-property-and-overlay (point) 'invisible)
  5512. (`(outline . ,o) (goto-char (overlay-end o))) ;already folded
  5513. (_
  5514. (let* ((drawer (org-element-at-point))
  5515. (type (org-element-type drawer)))
  5516. (when (memq type '(drawer property-drawer))
  5517. (org-hide-drawer-toggle t nil drawer)
  5518. ;; Make sure to skip drawer entirely or we might flag it
  5519. ;; another time when matching its ending line with
  5520. ;; `org-drawer-regexp'.
  5521. (goto-char (org-element-property :end drawer)))))))))))
  5522. ;;;; Visibility cycling
  5523. (defvar-local org-cycle-global-status nil)
  5524. (put 'org-cycle-global-status 'org-state t)
  5525. (defvar-local org-cycle-subtree-status nil)
  5526. (put 'org-cycle-subtree-status 'org-state t)
  5527. (defun org-show-all (&optional types)
  5528. "Show all contents in the visible part of the buffer.
  5529. By default, the function expands headings, blocks and drawers.
  5530. When optional argument TYPE is a list of symbols among `blocks',
  5531. `drawers' and `headings', to only expand one specific type."
  5532. (interactive)
  5533. (let ((types (or types '(blocks drawers headings))))
  5534. (when (memq 'blocks types)
  5535. (org-flag-region (point-min) (point-max) nil 'org-hide-block))
  5536. (cond
  5537. ;; Fast path. Since headings and drawers share the same
  5538. ;; invisible spec, clear everything in one go.
  5539. ((and (memq 'headings types)
  5540. (memq 'drawers types))
  5541. (org-flag-region (point-min) (point-max) nil 'outline))
  5542. ((memq 'headings types)
  5543. (org-flag-region (point-min) (point-max) nil 'outline)
  5544. (org-cycle-hide-drawers 'all))
  5545. ((memq 'drawers types)
  5546. (save-excursion
  5547. (goto-char (point-min))
  5548. (while (re-search-forward org-drawer-regexp nil t)
  5549. (let* ((pair (get-char-property-and-overlay (line-beginning-position)
  5550. 'invisible))
  5551. (o (cdr-safe pair)))
  5552. (if (overlayp o) (goto-char (overlay-end o))
  5553. (pcase (get-char-property-and-overlay (point) 'invisible)
  5554. (`(outline . ,o)
  5555. (goto-char (overlay-end o))
  5556. (delete-overlay o))
  5557. (_ nil))))))))))
  5558. ;;;###autoload
  5559. (defun org-cycle (&optional arg)
  5560. "TAB-action and visibility cycling for Org mode.
  5561. This is the command invoked in Org mode by the `TAB' key. Its main
  5562. purpose is outline visibility cycling, but it also invokes other actions
  5563. in special contexts.
  5564. When this function is called with a `\\[universal-argument]' prefix, rotate \
  5565. the entire
  5566. buffer through 3 states (global cycling)
  5567. 1. OVERVIEW: Show only top-level headlines.
  5568. 2. CONTENTS: Show all headlines of all levels, but no body text.
  5569. 3. SHOW ALL: Show everything.
  5570. With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
  5571. switch to the startup visibility,
  5572. determined by the variable `org-startup-folded', and by any VISIBILITY
  5573. properties in the buffer.
  5574. With a `\\[universal-argument] \\[universal-argument] \
  5575. \\[universal-argument]' prefix argument, show the entire buffer, including
  5576. any drawers.
  5577. When inside a table, re-align the table and move to the next field.
  5578. When point is at the beginning of a headline, rotate the subtree started
  5579. by this line through 3 different states (local cycling)
  5580. 1. FOLDED: Only the main headline is shown.
  5581. 2. CHILDREN: The main headline and the direct children are shown.
  5582. From this state, you can move to one of the children
  5583. and zoom in further.
  5584. 3. SUBTREE: Show the entire subtree, including body text.
  5585. If there is no subtree, switch directly from CHILDREN to FOLDED.
  5586. When point is at the beginning of an empty headline and the variable
  5587. `org-cycle-level-after-item/entry-creation' is set, cycle the level
  5588. of the headline by demoting and promoting it to likely levels. This
  5589. speeds up creation document structure by pressing `TAB' once or several
  5590. times right after creating a new headline.
  5591. When there is a numeric prefix, go up to a heading with level ARG, do
  5592. a `show-subtree' and return to the previous cursor position. If ARG
  5593. is negative, go up that many levels.
  5594. When point is not at the beginning of a headline, execute the global
  5595. binding for `TAB', which is re-indenting the line. See the option
  5596. `org-cycle-emulate-tab' for details.
  5597. As a special case, if point is at the very beginning of the buffer, if
  5598. there is no headline there, and if the variable `org-cycle-global-at-bob'
  5599. is non-nil, this function acts as if called with prefix argument \
  5600. \(`\\[universal-argument] TAB',
  5601. same as `S-TAB') also when called without prefix argument."
  5602. (interactive "P")
  5603. (org-load-modules-maybe)
  5604. (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
  5605. (and org-cycle-level-after-item/entry-creation
  5606. (or (org-cycle-level)
  5607. (org-cycle-item-indentation))))
  5608. (let* ((limit-level
  5609. (or org-cycle-max-level
  5610. (and (boundp 'org-inlinetask-min-level)
  5611. org-inlinetask-min-level
  5612. (1- org-inlinetask-min-level))))
  5613. (nstars
  5614. (and limit-level
  5615. (if org-odd-levels-only
  5616. (1- (* 2 limit-level))
  5617. limit-level)))
  5618. (org-outline-regexp
  5619. (format "\\*%s " (if nstars (format "\\{1,%d\\}" nstars) "+"))))
  5620. (cond
  5621. ((equal arg '(16))
  5622. (setq last-command 'dummy)
  5623. (org-set-startup-visibility)
  5624. (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
  5625. ((equal arg '(64))
  5626. (org-show-all)
  5627. (org-unlogged-message "Entire buffer visible, including drawers"))
  5628. ((equal arg '(4)) (org-cycle-internal-global))
  5629. ;; Show-subtree, ARG levels up from here.
  5630. ((integerp arg)
  5631. (save-excursion
  5632. (org-back-to-heading)
  5633. (outline-up-heading (if (< arg 0) (- arg)
  5634. (- (funcall outline-level) arg)))
  5635. (org-show-subtree)))
  5636. ;; Global cycling at BOB: delegate to `org-cycle-internal-global'.
  5637. ((and org-cycle-global-at-bob
  5638. (bobp)
  5639. (not (looking-at org-outline-regexp)))
  5640. (let ((org-cycle-hook
  5641. (remq 'org-optimize-window-after-visibility-change
  5642. org-cycle-hook)))
  5643. (org-cycle-internal-global)))
  5644. ;; Try CDLaTeX TAB completion.
  5645. ((org-try-cdlatex-tab))
  5646. ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
  5647. ((and (featurep 'org-inlinetask)
  5648. (org-inlinetask-at-task-p)
  5649. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5650. (org-inlinetask-toggle-visibility))
  5651. (t
  5652. (let ((pos (point))
  5653. (element (org-element-at-point)))
  5654. (cond
  5655. ;; Try toggling visibility for block at point.
  5656. ((org-hide-block-toggle nil t element))
  5657. ;; Try toggling visibility for drawer at point.
  5658. ((org-hide-drawer-toggle nil t element))
  5659. ;; Table: enter it or move to the next field.
  5660. ((and (org-match-line "[ \t]*[|+]")
  5661. (org-element-lineage element '(table) t))
  5662. (if (and (eq 'table (org-element-type element))
  5663. (eq 'table.el (org-element-property :type element)))
  5664. (message (substitute-command-keys "\\<org-mode-map>\
  5665. Use `\\[org-edit-special]' to edit table.el tables"))
  5666. (org-table-justify-field-maybe)
  5667. (call-interactively #'org-table-next-field)))
  5668. ((run-hook-with-args-until-success
  5669. 'org-tab-after-check-for-table-hook))
  5670. ;; At an item/headline: delegate to `org-cycle-internal-local'.
  5671. ((and (or (and org-cycle-include-plain-lists
  5672. (let ((item (org-element-lineage element
  5673. '(item plain-list)
  5674. t)))
  5675. (and item
  5676. (= (line-beginning-position)
  5677. (org-element-property :post-affiliated
  5678. item)))))
  5679. (org-match-line org-outline-regexp))
  5680. (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
  5681. (org-cycle-internal-local))
  5682. ;; From there: TAB emulation and template completion.
  5683. (buffer-read-only (org-back-to-heading))
  5684. ((run-hook-with-args-until-success
  5685. 'org-tab-after-check-for-cycling-hook))
  5686. ((run-hook-with-args-until-success
  5687. 'org-tab-before-tab-emulation-hook))
  5688. ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
  5689. (or (not (bolp))
  5690. (not (looking-at org-outline-regexp))))
  5691. (call-interactively (global-key-binding (kbd "TAB"))))
  5692. ((or (eq org-cycle-emulate-tab t)
  5693. (and (memq org-cycle-emulate-tab '(white whitestart))
  5694. (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
  5695. (or (and (eq org-cycle-emulate-tab 'white)
  5696. (= (match-end 0) (point-at-eol)))
  5697. (and (eq org-cycle-emulate-tab 'whitestart)
  5698. (>= (match-end 0) pos)))))
  5699. (call-interactively (global-key-binding (kbd "TAB"))))
  5700. (t
  5701. (save-excursion
  5702. (org-back-to-heading)
  5703. (org-cycle))))))))))
  5704. (defun org-cycle-internal-global ()
  5705. "Do the global cycling action."
  5706. ;; Hack to avoid display of messages for .org attachments in Gnus
  5707. (let ((ga (string-match-p "\\*fontification" (buffer-name))))
  5708. (cond
  5709. ((and (eq last-command this-command)
  5710. (eq org-cycle-global-status 'overview))
  5711. ;; We just created the overview - now do table of contents
  5712. ;; This can be slow in very large buffers, so indicate action
  5713. (run-hook-with-args 'org-pre-cycle-hook 'contents)
  5714. (unless ga (org-unlogged-message "CONTENTS..."))
  5715. (org-content)
  5716. (unless ga (org-unlogged-message "CONTENTS...done"))
  5717. (setq org-cycle-global-status 'contents)
  5718. (run-hook-with-args 'org-cycle-hook 'contents))
  5719. ((and (eq last-command this-command)
  5720. (eq org-cycle-global-status 'contents))
  5721. ;; We just showed the table of contents - now show everything
  5722. (run-hook-with-args 'org-pre-cycle-hook 'all)
  5723. (org-show-all '(headings blocks))
  5724. (unless ga (org-unlogged-message "SHOW ALL"))
  5725. (setq org-cycle-global-status 'all)
  5726. (run-hook-with-args 'org-cycle-hook 'all))
  5727. (t
  5728. ;; Default action: go to overview
  5729. (run-hook-with-args 'org-pre-cycle-hook 'overview)
  5730. (org-overview)
  5731. (unless ga (org-unlogged-message "OVERVIEW"))
  5732. (setq org-cycle-global-status 'overview)
  5733. (run-hook-with-args 'org-cycle-hook 'overview)))))
  5734. (defvar org-called-with-limited-levels nil
  5735. "Non-nil when `org-with-limited-levels' is currently active.")
  5736. (defun org-cycle-internal-local ()
  5737. "Do the local cycling action."
  5738. (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
  5739. ;; First, determine end of headline (EOH), end of subtree or item
  5740. ;; (EOS), and if item or heading has children (HAS-CHILDREN).
  5741. (save-excursion
  5742. (if (org-at-item-p)
  5743. (progn
  5744. (beginning-of-line)
  5745. (setq struct (org-list-struct))
  5746. (setq eoh (point-at-eol))
  5747. (setq eos (org-list-get-item-end-before-blank (point) struct))
  5748. (setq has-children (org-list-has-child-p (point) struct)))
  5749. (org-back-to-heading)
  5750. (setq eoh (save-excursion (outline-end-of-heading) (point)))
  5751. (setq eos (save-excursion
  5752. (org-end-of-subtree t t)
  5753. (unless (eobp) (forward-char -1))
  5754. (point)))
  5755. (setq has-children
  5756. (or
  5757. (save-excursion
  5758. (let ((level (funcall outline-level)))
  5759. (outline-next-heading)
  5760. (and (org-at-heading-p t)
  5761. (> (funcall outline-level) level))))
  5762. (and (eq org-cycle-include-plain-lists 'integrate)
  5763. (save-excursion
  5764. (org-list-search-forward (org-item-beginning-re) eos t))))))
  5765. ;; Determine end invisible part of buffer (EOL)
  5766. (beginning-of-line 2)
  5767. (while (and (not (eobp)) ;this is like `next-line'
  5768. (get-char-property (1- (point)) 'invisible))
  5769. (goto-char (next-single-char-property-change (point) 'invisible))
  5770. (and (eolp) (beginning-of-line 2)))
  5771. (setq eol (point)))
  5772. ;; Find out what to do next and set `this-command'
  5773. (cond
  5774. ((= eos eoh)
  5775. ;; Nothing is hidden behind this heading
  5776. (unless (org-before-first-heading-p)
  5777. (run-hook-with-args 'org-pre-cycle-hook 'empty))
  5778. (org-unlogged-message "EMPTY ENTRY")
  5779. (setq org-cycle-subtree-status nil)
  5780. (save-excursion
  5781. (goto-char eos)
  5782. (outline-next-heading)
  5783. (when (org-invisible-p) (org-flag-heading nil))))
  5784. ((and (or (>= eol eos)
  5785. (not (string-match "\\S-" (buffer-substring eol eos))))
  5786. (or has-children
  5787. (not (setq children-skipped
  5788. org-cycle-skip-children-state-if-no-children))))
  5789. ;; Entire subtree is hidden in one line: children view
  5790. (unless (org-before-first-heading-p)
  5791. (run-hook-with-args 'org-pre-cycle-hook 'children))
  5792. (if (org-at-item-p)
  5793. (org-list-set-item-visibility (point-at-bol) struct 'children)
  5794. (org-show-entry)
  5795. (org-with-limited-levels (org-show-children))
  5796. (org-show-set-visibility 'tree)
  5797. ;; Fold every list in subtree to top-level items.
  5798. (when (eq org-cycle-include-plain-lists 'integrate)
  5799. (save-excursion
  5800. (org-back-to-heading)
  5801. (while (org-list-search-forward (org-item-beginning-re) eos t)
  5802. (beginning-of-line 1)
  5803. (let* ((struct (org-list-struct))
  5804. (prevs (org-list-prevs-alist struct))
  5805. (end (org-list-get-bottom-point struct)))
  5806. (dolist (e (org-list-get-all-items (point) struct prevs))
  5807. (org-list-set-item-visibility e struct 'folded))
  5808. (goto-char (if (< end eos) end eos)))))))
  5809. (org-unlogged-message "CHILDREN")
  5810. (save-excursion
  5811. (goto-char eos)
  5812. (outline-next-heading)
  5813. (when (org-invisible-p) (org-flag-heading nil)))
  5814. (setq org-cycle-subtree-status 'children)
  5815. (unless (org-before-first-heading-p)
  5816. (run-hook-with-args 'org-cycle-hook 'children)))
  5817. ((or children-skipped
  5818. (and (eq last-command this-command)
  5819. (eq org-cycle-subtree-status 'children)))
  5820. ;; We just showed the children, or no children are there,
  5821. ;; now show everything.
  5822. (unless (org-before-first-heading-p)
  5823. (run-hook-with-args 'org-pre-cycle-hook 'subtree))
  5824. (org-flag-region eoh eos nil 'outline)
  5825. (org-unlogged-message
  5826. (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
  5827. (setq org-cycle-subtree-status 'subtree)
  5828. (unless (org-before-first-heading-p)
  5829. (run-hook-with-args 'org-cycle-hook 'subtree)))
  5830. (t
  5831. ;; Default action: hide the subtree.
  5832. (run-hook-with-args 'org-pre-cycle-hook 'folded)
  5833. (org-flag-region eoh eos t 'outline)
  5834. (org-unlogged-message "FOLDED")
  5835. (setq org-cycle-subtree-status 'folded)
  5836. (unless (org-before-first-heading-p)
  5837. (run-hook-with-args 'org-cycle-hook 'folded))))))
  5838. ;;;###autoload
  5839. (defun org-global-cycle (&optional arg)
  5840. "Cycle the global visibility. For details see `org-cycle'.
  5841. With `\\[universal-argument]' prefix ARG, switch to startup visibility.
  5842. With a numeric prefix, show all headlines up to that level."
  5843. (interactive "P")
  5844. (cond
  5845. ((integerp arg)
  5846. (org-content arg)
  5847. (setq org-cycle-global-status 'contents))
  5848. ((equal arg '(4))
  5849. (org-set-startup-visibility)
  5850. (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
  5851. (t
  5852. (org-cycle '(4)))))
  5853. (defun org-set-startup-visibility ()
  5854. "Set the visibility required by startup options and properties."
  5855. (cond
  5856. ((eq org-startup-folded t)
  5857. (org-overview))
  5858. ((eq org-startup-folded 'content)
  5859. (org-content))
  5860. ((eq org-startup-folded 'show2levels)
  5861. (org-content 2))
  5862. ((eq org-startup-folded 'show3levels)
  5863. (org-content 3))
  5864. ((eq org-startup-folded 'show4levels)
  5865. (org-content 4))
  5866. ((eq org-startup-folded 'show5levels)
  5867. (org-content 5))
  5868. ((or (eq org-startup-folded 'showeverything)
  5869. (eq org-startup-folded nil))
  5870. (org-show-all)))
  5871. (unless (eq org-startup-folded 'showeverything)
  5872. (when org-hide-block-startup (org-hide-block-all))
  5873. (org-set-visibility-according-to-property)
  5874. (org-cycle-hide-archived-subtrees 'all)
  5875. (org-cycle-hide-drawers 'all)
  5876. (org-cycle-show-empty-lines t)))
  5877. (defun org-set-visibility-according-to-property ()
  5878. "Switch subtree visibility according to VISIBILITY property."
  5879. (interactive)
  5880. (let ((regexp (org-re-property "VISIBILITY")))
  5881. (org-with-point-at 1
  5882. (while (re-search-forward regexp nil t)
  5883. (let ((state (match-string 3)))
  5884. (if (not (org-at-property-p)) (outline-next-heading)
  5885. (save-excursion
  5886. (org-back-to-heading t)
  5887. (org-flag-subtree t)
  5888. (org-reveal)
  5889. (pcase state
  5890. ("folded"
  5891. (org-flag-subtree t))
  5892. ("children"
  5893. (org-show-hidden-entry)
  5894. (org-show-children))
  5895. ("content"
  5896. (save-excursion
  5897. (save-restriction
  5898. (org-narrow-to-subtree)
  5899. (org-content))))
  5900. ((or "all" "showall")
  5901. (outline-show-subtree))
  5902. (_ nil)))
  5903. (org-end-of-subtree)))))))
  5904. (defun org-overview ()
  5905. "Switch to overview mode, showing only top-level headlines."
  5906. (interactive)
  5907. (org-show-all '(headings drawers))
  5908. (save-excursion
  5909. (goto-char (point-min))
  5910. (when (re-search-forward org-outline-regexp-bol nil t)
  5911. (let* ((last (line-end-position))
  5912. (level (- (match-end 0) (match-beginning 0) 1))
  5913. (regexp (format "^\\*\\{1,%d\\} " level)))
  5914. (while (re-search-forward regexp nil :move)
  5915. (org-flag-region last (line-end-position 0) t 'outline)
  5916. (setq last (line-end-position))
  5917. (setq level (- (match-end 0) (match-beginning 0) 1))
  5918. (setq regexp (format "^\\*\\{1,%d\\} " level)))
  5919. (org-flag-region last (point) t 'outline)))))
  5920. (defun org-content (&optional arg)
  5921. "Show all headlines in the buffer, like a table of contents.
  5922. With numerical argument N, show content up to level N."
  5923. (interactive "p")
  5924. (org-show-all '(headings drawers))
  5925. (save-excursion
  5926. (goto-char (point-max))
  5927. (let ((regexp (if (and (wholenump arg) (> arg 0))
  5928. (format "^\\*\\{1,%d\\} " arg)
  5929. "^\\*+ "))
  5930. (last (point)))
  5931. (while (re-search-backward regexp nil t)
  5932. (org-flag-region (line-end-position) last t 'outline)
  5933. (setq last (line-end-position 0))))))
  5934. (defvar org-scroll-position-to-restore nil
  5935. "Temporarily store scroll position to restore.")
  5936. (defun org-optimize-window-after-visibility-change (state)
  5937. "Adjust the window after a change in outline visibility.
  5938. This function is the default value of the hook `org-cycle-hook'."
  5939. (when (get-buffer-window (current-buffer))
  5940. (let ((repeat (eq last-command this-command)))
  5941. (unless repeat
  5942. (setq org-scroll-position-to-restore nil))
  5943. (cond
  5944. ((eq state 'content) nil)
  5945. ((eq state 'all) nil)
  5946. ((and org-scroll-position-to-restore repeat
  5947. (eq state 'folded))
  5948. (set-window-start nil org-scroll-position-to-restore))
  5949. ((eq state 'folded) nil)
  5950. ((eq state 'children)
  5951. (setq org-scroll-position-to-restore (window-start))
  5952. (or (org-subtree-end-visible-p) (recenter 1)))
  5953. ((eq state 'subtree)
  5954. (unless repeat
  5955. (setq org-scroll-position-to-restore (window-start)))
  5956. (or (org-subtree-end-visible-p) (recenter 1)))))))
  5957. (defun org-clean-visibility-after-subtree-move ()
  5958. "Fix visibility issues after moving a subtree."
  5959. ;; First, find a reasonable region to look at:
  5960. ;; Start two siblings above, end three below
  5961. (let* ((beg (save-excursion
  5962. (and (org-get-previous-sibling)
  5963. (org-get-previous-sibling))
  5964. (point)))
  5965. (end (save-excursion
  5966. (and (org-get-next-sibling)
  5967. (org-get-next-sibling)
  5968. (org-get-next-sibling))
  5969. (if (org-at-heading-p)
  5970. (point-at-eol)
  5971. (point))))
  5972. (level (looking-at "\\*+"))
  5973. (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
  5974. (save-excursion
  5975. (save-restriction
  5976. (narrow-to-region beg end)
  5977. (when re
  5978. ;; Properly fold already folded siblings
  5979. (goto-char (point-min))
  5980. (while (re-search-forward re nil t)
  5981. (when (and (not (org-invisible-p))
  5982. (org-invisible-p (line-end-position)))
  5983. (outline-hide-entry))))
  5984. (org-cycle-hide-drawers 'all)
  5985. (org-cycle-show-empty-lines 'overview)))))
  5986. (defun org-cycle-show-empty-lines (state)
  5987. "Show empty lines above all visible headlines.
  5988. The region to be covered depends on STATE when called through
  5989. `org-cycle-hook'. Lisp program can use t for STATE to get the
  5990. entire buffer covered. Note that an empty line is only shown if there
  5991. are at least `org-cycle-separator-lines' empty lines before the headline."
  5992. (when (/= org-cycle-separator-lines 0)
  5993. (save-excursion
  5994. (let* ((n (abs org-cycle-separator-lines))
  5995. (re (cond
  5996. ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
  5997. ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
  5998. (t (let ((ns (number-to-string (- n 2))))
  5999. (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
  6000. "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
  6001. beg end)
  6002. (cond
  6003. ((memq state '(overview contents t))
  6004. (setq beg (point-min) end (point-max)))
  6005. ((memq state '(children folded))
  6006. (setq beg (point)
  6007. end (progn (org-end-of-subtree t t)
  6008. (line-beginning-position 2)))))
  6009. (when beg
  6010. (goto-char beg)
  6011. (while (re-search-forward re end t)
  6012. (unless (get-char-property (match-end 1) 'invisible)
  6013. (let ((e (match-end 1))
  6014. (b (if (>= org-cycle-separator-lines 0)
  6015. (match-beginning 1)
  6016. (save-excursion
  6017. (goto-char (match-beginning 0))
  6018. (skip-chars-backward " \t\n")
  6019. (line-end-position)))))
  6020. (org-flag-region b e nil 'outline))))))))
  6021. ;; Never hide empty lines at the end of the file.
  6022. (save-excursion
  6023. (goto-char (point-max))
  6024. (outline-previous-heading)
  6025. (outline-end-of-heading)
  6026. (when (and (looking-at "[ \t\n]+")
  6027. (= (match-end 0) (point-max)))
  6028. (org-flag-region (point) (match-end 0) nil 'outline))))
  6029. ;;;; Reveal point location
  6030. (defun org-show-context (&optional key)
  6031. "Make sure point and context are visible.
  6032. Optional argument KEY, when non-nil, is a symbol. See
  6033. `org-show-context-detail' for allowed values and how much is to
  6034. be shown."
  6035. (org-show-set-visibility
  6036. (cond ((symbolp org-show-context-detail) org-show-context-detail)
  6037. ((cdr (assq key org-show-context-detail)))
  6038. (t (cdr (assq 'default org-show-context-detail))))))
  6039. (defun org-show-set-visibility (detail)
  6040. "Set visibility around point according to DETAIL.
  6041. DETAIL is either nil, `minimal', `local', `ancestors',
  6042. `ancestors-full', `lineage', `tree', `canonical' or t. See
  6043. `org-show-context-detail' for more information."
  6044. ;; Show current heading and possibly its entry, following headline
  6045. ;; or all children.
  6046. (if (and (org-at-heading-p) (not (eq detail 'local)))
  6047. (org-flag-heading nil)
  6048. (org-show-entry)
  6049. ;; If point is hidden within a drawer or a block, make sure to
  6050. ;; expose it.
  6051. (dolist (o (overlays-at (point)))
  6052. (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
  6053. (delete-overlay o)))
  6054. (unless (org-before-first-heading-p)
  6055. (org-with-limited-levels
  6056. (cl-case detail
  6057. ((tree canonical t) (org-show-children))
  6058. ((nil minimal ancestors ancestors-full))
  6059. (t (save-excursion
  6060. (outline-next-heading)
  6061. (org-flag-heading nil)))))))
  6062. ;; Show whole subtree.
  6063. (when (eq detail 'ancestors-full) (org-show-subtree))
  6064. ;; Show all siblings.
  6065. (when (eq detail 'lineage) (org-show-siblings))
  6066. ;; Show ancestors, possibly with their children.
  6067. (when (memq detail '(ancestors ancestors-full lineage tree canonical t))
  6068. (save-excursion
  6069. (while (org-up-heading-safe)
  6070. (org-flag-heading nil)
  6071. (when (memq detail '(canonical t)) (org-show-entry))
  6072. (when (memq detail '(tree canonical t)) (org-show-children))))))
  6073. (defvar org-reveal-start-hook nil
  6074. "Hook run before revealing a location.")
  6075. (defun org-reveal (&optional siblings)
  6076. "Show current entry, hierarchy above it, and the following headline.
  6077. This can be used to show a consistent set of context around
  6078. locations exposed with `org-show-context'.
  6079. With optional argument SIBLINGS, on each level of the hierarchy all
  6080. siblings are shown. This repairs the tree structure to what it would
  6081. look like when opened with hierarchical calls to `org-cycle'.
  6082. With a \\[universal-argument] \\[universal-argument] prefix, \
  6083. go to the parent and show the entire tree."
  6084. (interactive "P")
  6085. (run-hooks 'org-reveal-start-hook)
  6086. (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
  6087. ((equal siblings '(16))
  6088. (save-excursion
  6089. (when (org-up-heading-safe)
  6090. (org-show-subtree)
  6091. (run-hook-with-args 'org-cycle-hook 'subtree))))
  6092. (t (org-show-set-visibility 'lineage))))
  6093. ;;; Indirect buffer display of subtrees
  6094. (defvar org-indirect-dedicated-frame nil
  6095. "This is the frame being used for indirect tree display.")
  6096. (defvar org-last-indirect-buffer nil)
  6097. (defun org-tree-to-indirect-buffer (&optional arg)
  6098. "Create indirect buffer and narrow it to current subtree.
  6099. With a numerical prefix ARG, go up to this level and then take that tree.
  6100. If ARG is negative, go up that many levels.
  6101. If `org-indirect-buffer-display' is not `new-frame', the command removes the
  6102. indirect buffer previously made with this command, to avoid proliferation of
  6103. indirect buffers. However, when you call the command with a \
  6104. `\\[universal-argument]' prefix, or
  6105. when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
  6106. so that you can work with several indirect buffers at the same time. If
  6107. `org-indirect-buffer-display' is `dedicated-frame', the \
  6108. `\\[universal-argument]' prefix also
  6109. requests that a new frame be made for the new buffer, so that the dedicated
  6110. frame is not changed."
  6111. (interactive "P")
  6112. (let ((cbuf (current-buffer))
  6113. (cwin (selected-window))
  6114. (pos (point))
  6115. beg end level heading ibuf)
  6116. (save-excursion
  6117. (org-back-to-heading t)
  6118. (when (numberp arg)
  6119. (setq level (org-outline-level))
  6120. (when (< arg 0) (setq arg (+ level arg)))
  6121. (while (> (setq level (org-outline-level)) arg)
  6122. (org-up-heading-safe)))
  6123. (setq beg (point)
  6124. heading (org-get-heading 'no-tags))
  6125. (org-end-of-subtree t t)
  6126. (when (org-at-heading-p) (backward-char 1))
  6127. (setq end (point)))
  6128. (when (and (buffer-live-p org-last-indirect-buffer)
  6129. (not (eq org-indirect-buffer-display 'new-frame))
  6130. (not arg))
  6131. (kill-buffer org-last-indirect-buffer))
  6132. (setq ibuf (org-get-indirect-buffer cbuf heading)
  6133. org-last-indirect-buffer ibuf)
  6134. (cond
  6135. ((or (eq org-indirect-buffer-display 'new-frame)
  6136. (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
  6137. (select-frame (make-frame))
  6138. (delete-other-windows)
  6139. (pop-to-buffer-same-window ibuf)
  6140. (org-set-frame-title heading))
  6141. ((eq org-indirect-buffer-display 'dedicated-frame)
  6142. (raise-frame
  6143. (select-frame (or (and org-indirect-dedicated-frame
  6144. (frame-live-p org-indirect-dedicated-frame)
  6145. org-indirect-dedicated-frame)
  6146. (setq org-indirect-dedicated-frame (make-frame)))))
  6147. (delete-other-windows)
  6148. (pop-to-buffer-same-window ibuf)
  6149. (org-set-frame-title (concat "Indirect: " heading)))
  6150. ((eq org-indirect-buffer-display 'current-window)
  6151. (pop-to-buffer-same-window ibuf))
  6152. ((eq org-indirect-buffer-display 'other-window)
  6153. (pop-to-buffer ibuf))
  6154. (t (error "Invalid value")))
  6155. (narrow-to-region beg end)
  6156. (org-show-all '(headings drawers blocks))
  6157. (goto-char pos)
  6158. (run-hook-with-args 'org-cycle-hook 'all)
  6159. (and (window-live-p cwin) (select-window cwin))))
  6160. (defun org-get-indirect-buffer (&optional buffer heading)
  6161. (setq buffer (or buffer (current-buffer)))
  6162. (let ((n 1) (base (buffer-name buffer)) bname)
  6163. (while (buffer-live-p
  6164. (get-buffer
  6165. (setq bname
  6166. (concat base "-"
  6167. (if heading (concat heading "-" (number-to-string n))
  6168. (number-to-string n))))))
  6169. (setq n (1+ n)))
  6170. (condition-case nil
  6171. (make-indirect-buffer buffer bname 'clone)
  6172. (error (make-indirect-buffer buffer bname)))))
  6173. (defun org-set-frame-title (title)
  6174. "Set the title of the current frame to the string TITLE."
  6175. (modify-frame-parameters (selected-frame) (list (cons 'name title))))
  6176. ;;;; Structure editing
  6177. ;;; Inserting headlines
  6178. (defun org--blank-before-heading-p (&optional parent)
  6179. "Non-nil when an empty line should precede a new heading here.
  6180. When optional argument PARENT is non-nil, consider parent
  6181. headline instead of current one."
  6182. (pcase (assq 'heading org-blank-before-new-entry)
  6183. (`(heading . auto)
  6184. (save-excursion
  6185. (org-with-limited-levels
  6186. (unless (and (org-before-first-heading-p)
  6187. (not (outline-next-heading)))
  6188. (org-back-to-heading t)
  6189. (when parent (org-up-heading-safe))
  6190. (cond ((not (bobp))
  6191. (org-previous-line-empty-p))
  6192. ((outline-next-heading)
  6193. (org-previous-line-empty-p))
  6194. ;; Ignore trailing spaces on last buffer line.
  6195. ((progn (skip-chars-backward " \t") (bolp))
  6196. (org-previous-line-empty-p))
  6197. (t nil))))))
  6198. (`(heading . ,value) value)
  6199. (_ nil)))
  6200. (defun org-insert-heading (&optional arg invisible-ok top)
  6201. "Insert a new heading or an item with the same depth at point.
  6202. If point is at the beginning of a heading, insert a new heading
  6203. or a new headline above the current one. When at the beginning
  6204. of a regular line of text, turn it into a heading.
  6205. If point is in the middle of a line, split it and create a new
  6206. headline with the text in the current line after point (see
  6207. `org-M-RET-may-split-line' on how to modify this behavior). As
  6208. a special case, on a headline, splitting can only happen on the
  6209. title itself. E.g., this excludes breaking stars or tags.
  6210. With a `\\[universal-argument]' prefix, set \
  6211. `org-insert-heading-respect-content' to
  6212. a non-nil value for the duration of the command. This forces the
  6213. insertion of a heading after the current subtree, independently
  6214. on the location of point.
  6215. With a `\\[universal-argument] \\[universal-argument]' prefix, \
  6216. insert the heading at the end of the tree
  6217. above the current heading. For example, if point is within a
  6218. 2nd-level heading, then it will insert a 2nd-level heading at
  6219. the end of the 1st-level parent subtree.
  6220. When INVISIBLE-OK is set, stop at invisible headlines when going
  6221. back. This is important for non-interactive uses of the
  6222. command.
  6223. When optional argument TOP is non-nil, insert a level 1 heading,
  6224. unconditionally."
  6225. (interactive "P")
  6226. (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
  6227. (level (org-current-level))
  6228. (stars (make-string (if (and level (not top)) level 1) ?*)))
  6229. (cond
  6230. ((or org-insert-heading-respect-content
  6231. (member arg '((4) (16)))
  6232. (and (not invisible-ok)
  6233. (invisible-p (max (1- (point)) (point-min)))))
  6234. ;; Position point at the location of insertion. Make sure we
  6235. ;; end up on a visible headline if INVISIBLE-OK is nil.
  6236. (org-with-limited-levels
  6237. (if (not level) (outline-next-heading) ;before first headline
  6238. (org-back-to-heading invisible-ok)
  6239. (when (equal arg '(16)) (org-up-heading-safe))
  6240. (org-end-of-subtree)))
  6241. (unless (bolp) (insert "\n"))
  6242. (when (and blank? (save-excursion
  6243. (backward-char)
  6244. (org-before-first-heading-p)))
  6245. (insert "\n")
  6246. (backward-char))
  6247. (when (and (not level) (not (eobp)) (not (bobp)))
  6248. (when (org-at-heading-p) (insert "\n"))
  6249. (backward-char))
  6250. (unless (and blank? (org-previous-line-empty-p))
  6251. (org-N-empty-lines-before-current (if blank? 1 0)))
  6252. (insert stars " ")
  6253. ;; When INVISIBLE-OK is non-nil, ensure newly created headline
  6254. ;; is visible.
  6255. (unless invisible-ok
  6256. (pcase (get-char-property-and-overlay (point) 'invisible)
  6257. (`(outline . ,o)
  6258. (move-overlay o (overlay-start o) (line-end-position 0)))
  6259. (_ nil))))
  6260. ;; At a headline...
  6261. ((org-at-heading-p)
  6262. (cond ((bolp)
  6263. (when blank? (save-excursion (insert "\n")))
  6264. (save-excursion (insert stars " \n"))
  6265. (unless (and blank? (org-previous-line-empty-p))
  6266. (org-N-empty-lines-before-current (if blank? 1 0)))
  6267. (end-of-line))
  6268. ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
  6269. (org-match-line org-complex-heading-regexp)
  6270. (org-pos-in-match-range (point) 4))
  6271. ;; Grab the text that should moved to the new headline.
  6272. ;; Preserve tags.
  6273. (let ((split (delete-and-extract-region (point) (match-end 4))))
  6274. (if (looking-at "[ \t]*$") (replace-match "")
  6275. (org-align-tags))
  6276. (end-of-line)
  6277. (when blank? (insert "\n"))
  6278. (insert "\n" stars " ")
  6279. (when (org-string-nw-p split) (insert split))))
  6280. (t
  6281. (end-of-line)
  6282. (when blank? (insert "\n"))
  6283. (insert "\n" stars " "))))
  6284. ;; On regular text, turn line into a headline or split, if
  6285. ;; appropriate.
  6286. ((bolp)
  6287. (insert stars " ")
  6288. (unless (and blank? (org-previous-line-empty-p))
  6289. (org-N-empty-lines-before-current (if blank? 1 0))))
  6290. (t
  6291. (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
  6292. (end-of-line))
  6293. (insert "\n" stars " ")
  6294. (unless (and blank? (org-previous-line-empty-p))
  6295. (org-N-empty-lines-before-current (if blank? 1 0))))))
  6296. (run-hooks 'org-insert-heading-hook))
  6297. (defun org-N-empty-lines-before-current (n)
  6298. "Make the number of empty lines before current exactly N.
  6299. So this will delete or add empty lines."
  6300. (let ((column (current-column)))
  6301. (beginning-of-line)
  6302. (unless (bobp)
  6303. (let ((start (save-excursion
  6304. (skip-chars-backward " \r\t\n")
  6305. (line-end-position))))
  6306. (delete-region start (line-end-position 0))))
  6307. (insert (make-string n ?\n))
  6308. (move-to-column column)))
  6309. (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
  6310. "Return the heading of the current entry, without the stars.
  6311. When NO-TAGS is non-nil, don't include tags.
  6312. When NO-TODO is non-nil, don't include TODO keywords.
  6313. When NO-PRIORITY is non-nil, don't include priority cookie.
  6314. When NO-COMMENT is non-nil, don't include COMMENT string.
  6315. Return nil before first heading."
  6316. (unless (org-before-first-heading-p)
  6317. (save-excursion
  6318. (org-back-to-heading t)
  6319. (let ((case-fold-search nil))
  6320. (looking-at org-complex-heading-regexp)
  6321. (let ((todo (and (not no-todo) (match-string 2)))
  6322. (priority (and (not no-priority) (match-string 3)))
  6323. (headline (pcase (match-string 4)
  6324. (`nil "")
  6325. ((and (guard no-comment) h)
  6326. (replace-regexp-in-string
  6327. (eval-when-compile
  6328. (format "\\`%s[ \t]+" org-comment-string))
  6329. "" h))
  6330. (h h)))
  6331. (tags (and (not no-tags) (match-string 5))))
  6332. (mapconcat #'identity
  6333. (delq nil (list todo priority headline tags))
  6334. " "))))))
  6335. (defun org-heading-components ()
  6336. "Return the components of the current heading.
  6337. This is a list with the following elements:
  6338. - the level as an integer
  6339. - the reduced level, different if `org-odd-levels-only' is set.
  6340. - the TODO keyword, or nil
  6341. - the priority character, like ?A, or nil if no priority is given
  6342. - the headline text itself, or the tags string if no headline text
  6343. - the tags string, or nil."
  6344. (save-excursion
  6345. (org-back-to-heading t)
  6346. (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
  6347. (list (length (match-string 1))
  6348. (org-reduced-level (length (match-string 1)))
  6349. (match-string-no-properties 2)
  6350. (and (match-end 3) (aref (match-string 3) 2))
  6351. (match-string-no-properties 4)
  6352. (match-string-no-properties 5)))))
  6353. (defun org-get-entry ()
  6354. "Get the entry text, after heading, entire subtree."
  6355. (save-excursion
  6356. (org-back-to-heading t)
  6357. (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
  6358. (defun org-edit-headline (&optional heading)
  6359. "Edit the current headline.
  6360. Set it to HEADING when provided."
  6361. (interactive)
  6362. (org-with-wide-buffer
  6363. (org-back-to-heading t)
  6364. (let ((case-fold-search nil))
  6365. (when (looking-at org-complex-heading-regexp)
  6366. (let* ((old (match-string-no-properties 4))
  6367. (new (save-match-data
  6368. (org-trim (or heading (read-string "Edit: " old))))))
  6369. (unless (equal old new)
  6370. (if old (replace-match new t t nil 4)
  6371. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  6372. (insert " " new))
  6373. (org-align-tags)
  6374. (when (looking-at "[ \t]*$") (replace-match ""))))))))
  6375. (defun org-insert-heading-after-current ()
  6376. "Insert a new heading with same level as current, after current subtree."
  6377. (interactive)
  6378. (org-back-to-heading)
  6379. (org-insert-heading)
  6380. (org-move-subtree-down)
  6381. (end-of-line 1))
  6382. (defun org-insert-heading-respect-content (&optional invisible-ok)
  6383. "Insert heading with `org-insert-heading-respect-content' set to t."
  6384. (interactive)
  6385. (org-insert-heading '(4) invisible-ok))
  6386. (defun org-insert-todo-heading-respect-content (&optional force-state)
  6387. "Insert TODO heading with `org-insert-heading-respect-content' set to t."
  6388. (interactive)
  6389. (org-insert-todo-heading force-state '(4)))
  6390. (defun org-insert-todo-heading (arg &optional force-heading)
  6391. "Insert a new heading with the same level and TODO state as current heading.
  6392. If the heading has no TODO state, or if the state is DONE, use
  6393. the first state (TODO by default). Also with one prefix arg,
  6394. force first state. With two prefix args, force inserting at the
  6395. end of the parent subtree.
  6396. When called at a plain list item, insert a new item with an
  6397. unchecked check box."
  6398. (interactive "P")
  6399. (when (or force-heading (not (org-insert-item 'checkbox)))
  6400. (org-insert-heading (or (and (equal arg '(16)) '(16))
  6401. force-heading))
  6402. (save-excursion
  6403. (org-forward-heading-same-level -1)
  6404. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
  6405. (let* ((new-mark-x
  6406. (if (or (equal arg '(4))
  6407. (not (match-beginning 2))
  6408. (member (match-string 2) org-done-keywords))
  6409. (car org-todo-keywords-1)
  6410. (match-string 2)))
  6411. (new-mark
  6412. (or
  6413. (run-hook-with-args-until-success
  6414. 'org-todo-get-default-hook new-mark-x nil)
  6415. new-mark-x)))
  6416. (beginning-of-line 1)
  6417. (and (looking-at org-outline-regexp) (goto-char (match-end 0))
  6418. (if org-treat-insert-todo-heading-as-state-change
  6419. (org-todo new-mark)
  6420. (insert new-mark " "))))
  6421. (when org-provide-todo-statistics
  6422. (org-update-parent-todo-statistics))))
  6423. (defun org-insert-subheading (arg)
  6424. "Insert a new subheading and demote it.
  6425. Works for outline headings and for plain lists alike."
  6426. (interactive "P")
  6427. (org-insert-heading arg)
  6428. (cond
  6429. ((org-at-heading-p) (org-do-demote))
  6430. ((org-at-item-p) (org-indent-item))))
  6431. (defun org-insert-todo-subheading (arg)
  6432. "Insert a new subheading with TODO keyword or checkbox and demote it.
  6433. Works for outline headings and for plain lists alike."
  6434. (interactive "P")
  6435. (org-insert-todo-heading arg)
  6436. (cond
  6437. ((org-at-heading-p) (org-do-demote))
  6438. ((org-at-item-p) (org-indent-item))))
  6439. ;;; Promotion and Demotion
  6440. (defvar org-after-demote-entry-hook nil
  6441. "Hook run after an entry has been demoted.
  6442. The cursor will be at the beginning of the entry.
  6443. When a subtree is being demoted, the hook will be called for each node.")
  6444. (defvar org-after-promote-entry-hook nil
  6445. "Hook run after an entry has been promoted.
  6446. The cursor will be at the beginning of the entry.
  6447. When a subtree is being promoted, the hook will be called for each node.")
  6448. (defun org-promote-subtree ()
  6449. "Promote the entire subtree.
  6450. See also `org-promote'."
  6451. (interactive)
  6452. (save-excursion
  6453. (org-with-limited-levels (org-map-tree 'org-promote)))
  6454. (org-fix-position-after-promote))
  6455. (defun org-demote-subtree ()
  6456. "Demote the entire subtree.
  6457. See `org-demote' and `org-promote'."
  6458. (interactive)
  6459. (save-excursion
  6460. (org-with-limited-levels (org-map-tree 'org-demote)))
  6461. (org-fix-position-after-promote))
  6462. (defun org-do-promote ()
  6463. "Promote the current heading higher up the tree.
  6464. If the region is active in `transient-mark-mode', promote all
  6465. headings in the region."
  6466. (interactive)
  6467. (save-excursion
  6468. (if (org-region-active-p)
  6469. (org-map-region 'org-promote (region-beginning) (region-end))
  6470. (org-promote)))
  6471. (org-fix-position-after-promote))
  6472. (defun org-do-demote ()
  6473. "Demote the current heading lower down the tree.
  6474. If the region is active in `transient-mark-mode', demote all
  6475. headings in the region."
  6476. (interactive)
  6477. (save-excursion
  6478. (if (org-region-active-p)
  6479. (org-map-region 'org-demote (region-beginning) (region-end))
  6480. (org-demote)))
  6481. (org-fix-position-after-promote))
  6482. (defun org-fix-position-after-promote ()
  6483. "Fix cursor position and indentation after demoting/promoting."
  6484. (let ((pos (point)))
  6485. (when (save-excursion
  6486. (beginning-of-line)
  6487. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  6488. (or (eq pos (match-end 1)) (eq pos (match-end 2))))
  6489. (cond ((eobp) (insert " "))
  6490. ((eolp) (insert " "))
  6491. ((equal (char-after) ?\s) (forward-char 1))))))
  6492. (defun org-current-level ()
  6493. "Return the level of the current entry, or nil if before the first headline.
  6494. The level is the number of stars at the beginning of the
  6495. headline. Use `org-reduced-level' to remove the effect of
  6496. `org-odd-levels'. Unlike to `org-outline-level', this function
  6497. ignores inlinetasks."
  6498. (let ((level (org-with-limited-levels (org-outline-level))))
  6499. (and (> level 0) level)))
  6500. (defun org-get-previous-line-level ()
  6501. "Return the outline depth of the last headline before the current line.
  6502. Returns 0 for the first headline in the buffer, and nil if before the
  6503. first headline."
  6504. (and (org-current-level)
  6505. (or (and (/= (line-beginning-position) (point-min))
  6506. (save-excursion (beginning-of-line 0) (org-current-level)))
  6507. 0)))
  6508. (defun org-reduced-level (l)
  6509. "Compute the effective level of a heading.
  6510. This takes into account the setting of `org-odd-levels-only'."
  6511. (cond
  6512. ((zerop l) 0)
  6513. (org-odd-levels-only (1+ (floor (/ l 2))))
  6514. (t l)))
  6515. (defun org-level-increment ()
  6516. "Return the number of stars that will be added or removed at a
  6517. time to headlines when structure editing, based on the value of
  6518. `org-odd-levels-only'."
  6519. (if org-odd-levels-only 2 1))
  6520. (defun org-get-valid-level (level &optional change)
  6521. "Rectify a level change under the influence of `org-odd-levels-only'.
  6522. LEVEL is a current level, CHANGE is by how much the level should
  6523. be modified. Even if CHANGE is nil, LEVEL may be returned
  6524. modified because even level numbers will become the next higher
  6525. odd number. Returns values greater than 0."
  6526. (if org-odd-levels-only
  6527. (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
  6528. ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
  6529. ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
  6530. (max 1 (+ level (or change 0)))))
  6531. (defun org-promote ()
  6532. "Promote the current heading higher up the tree."
  6533. (org-with-wide-buffer
  6534. (org-back-to-heading t)
  6535. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6536. after-change-functions))
  6537. (level (save-match-data (funcall outline-level)))
  6538. (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
  6539. (diff (abs (- level (length up-head) -1))))
  6540. (cond
  6541. ((and (= level 1) org-allow-promoting-top-level-subtree)
  6542. (replace-match "# " nil t))
  6543. ((= level 1)
  6544. (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
  6545. (t (replace-match up-head nil t)))
  6546. (unless (= level 1)
  6547. (when org-auto-align-tags (org-align-tags))
  6548. (when org-adapt-indentation (org-fixup-indentation (- diff))))
  6549. (run-hooks 'org-after-promote-entry-hook))))
  6550. (defun org-demote ()
  6551. "Demote the current heading lower down the tree."
  6552. (org-with-wide-buffer
  6553. (org-back-to-heading t)
  6554. (let* ((after-change-functions (remq 'flyspell-after-change-function
  6555. after-change-functions))
  6556. (level (save-match-data (funcall outline-level)))
  6557. (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
  6558. (diff (abs (- level (length down-head) -1))))
  6559. (replace-match down-head nil t)
  6560. (when org-auto-align-tags (org-align-tags))
  6561. (when org-adapt-indentation (org-fixup-indentation diff))
  6562. (run-hooks 'org-after-demote-entry-hook))))
  6563. (defun org-cycle-level ()
  6564. "Cycle the level of an empty headline through possible states.
  6565. This goes first to child, then to parent, level, then up the hierarchy.
  6566. After top level, it switches back to sibling level."
  6567. (interactive)
  6568. (let ((org-adapt-indentation nil))
  6569. (when (org-point-at-end-of-empty-headline)
  6570. (setq this-command 'org-cycle-level) ; Only needed for caching
  6571. (let ((cur-level (org-current-level))
  6572. (prev-level (org-get-previous-line-level)))
  6573. (cond
  6574. ;; If first headline in file, promote to top-level.
  6575. ((= prev-level 0)
  6576. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6577. do (org-do-promote)))
  6578. ;; If same level as prev, demote one.
  6579. ((= prev-level cur-level)
  6580. (org-do-demote))
  6581. ;; If parent is top-level, promote to top level if not already.
  6582. ((= prev-level 1)
  6583. (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
  6584. do (org-do-promote)))
  6585. ;; If top-level, return to prev-level.
  6586. ((= cur-level 1)
  6587. (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
  6588. do (org-do-demote)))
  6589. ;; If less than prev-level, promote one.
  6590. ((< cur-level prev-level)
  6591. (org-do-promote))
  6592. ;; If deeper than prev-level, promote until higher than
  6593. ;; prev-level.
  6594. ((> cur-level prev-level)
  6595. (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
  6596. do (org-do-promote))))
  6597. t))))
  6598. (defun org-map-tree (fun)
  6599. "Call FUN for every heading underneath the current one."
  6600. (org-back-to-heading t)
  6601. (let ((level (funcall outline-level)))
  6602. (save-excursion
  6603. (funcall fun)
  6604. (while (and (progn
  6605. (outline-next-heading)
  6606. (> (funcall outline-level) level))
  6607. (not (eobp)))
  6608. (funcall fun)))))
  6609. (defun org-map-region (fun beg end)
  6610. "Call FUN for every heading between BEG and END."
  6611. (let ((org-ignore-region t))
  6612. (save-excursion
  6613. (setq end (copy-marker end))
  6614. (goto-char beg)
  6615. (when (and (re-search-forward org-outline-regexp-bol nil t)
  6616. (< (point) end))
  6617. (funcall fun))
  6618. (while (and (progn
  6619. (outline-next-heading)
  6620. (< (point) end))
  6621. (not (eobp)))
  6622. (funcall fun)))))
  6623. (defun org-fixup-indentation (diff)
  6624. "Change the indentation in the current entry by DIFF.
  6625. DIFF is an integer. Indentation is done according to the
  6626. following rules:
  6627. - Planning information and property drawers are always indented
  6628. according to the new level of the headline;
  6629. - Footnote definitions and their contents are ignored;
  6630. - Inlinetasks' boundaries are not shifted;
  6631. - Empty lines are ignored;
  6632. - Other lines' indentation are shifted by DIFF columns, unless
  6633. it would introduce a structural change in the document, in
  6634. which case no shifting is done at all.
  6635. Assume point is at a heading or an inlinetask beginning."
  6636. (org-with-wide-buffer
  6637. (narrow-to-region (line-beginning-position)
  6638. (save-excursion
  6639. (if (org-with-limited-levels (org-at-heading-p))
  6640. (org-with-limited-levels (outline-next-heading))
  6641. (org-inlinetask-goto-end))
  6642. (point)))
  6643. (forward-line)
  6644. ;; Indent properly planning info and property drawer.
  6645. (when (looking-at-p org-planning-line-re)
  6646. (org-indent-line)
  6647. (forward-line))
  6648. (when (looking-at org-property-drawer-re)
  6649. (goto-char (match-end 0))
  6650. (forward-line)
  6651. (org-indent-region (match-beginning 0) (match-end 0)))
  6652. (when (looking-at org-logbook-drawer-re)
  6653. (let ((end-marker (move-marker (make-marker) (match-end 0)))
  6654. (col (+ (current-indentation) diff)))
  6655. (when (wholenump col)
  6656. (while (< (point) end-marker)
  6657. (if (natnump diff)
  6658. (insert (make-string diff 32))
  6659. (delete-char (abs diff)))
  6660. (forward-line)))))
  6661. (catch 'no-shift
  6662. (when (or (zerop diff) (not (eq org-adapt-indentation t)))
  6663. (throw 'no-shift nil))
  6664. ;; If DIFF is negative, first check if a shift is possible at all
  6665. ;; (e.g., it doesn't break structure). This can only happen if
  6666. ;; some contents are not properly indented.
  6667. (let ((case-fold-search t))
  6668. (when (< diff 0)
  6669. (let ((diff (- diff))
  6670. (forbidden-re (concat org-outline-regexp
  6671. "\\|"
  6672. (substring org-footnote-definition-re 1))))
  6673. (save-excursion
  6674. (while (not (eobp))
  6675. (cond
  6676. ((looking-at-p "[ \t]*$") (forward-line))
  6677. ((and (looking-at-p org-footnote-definition-re)
  6678. (let ((e (org-element-at-point)))
  6679. (and (eq (org-element-type e) 'footnote-definition)
  6680. (goto-char (org-element-property :end e))))))
  6681. ((looking-at-p org-outline-regexp) (forward-line))
  6682. ;; Give up if shifting would move before column 0 or
  6683. ;; if it would introduce a headline or a footnote
  6684. ;; definition.
  6685. (t
  6686. (skip-chars-forward " \t")
  6687. (let ((ind (current-column)))
  6688. (when (or (< ind diff)
  6689. (and (= ind diff) (looking-at-p forbidden-re)))
  6690. (throw 'no-shift nil)))
  6691. ;; Ignore contents of example blocks and source
  6692. ;; blocks if their indentation is meant to be
  6693. ;; preserved. Jump to block's closing line.
  6694. (beginning-of-line)
  6695. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6696. (let ((e (org-element-at-point)))
  6697. (and (memq (org-element-type e)
  6698. '(example-block src-block))
  6699. (or org-src-preserve-indentation
  6700. (org-element-property :preserve-indent e))
  6701. (goto-char (org-element-property :end e))
  6702. (progn (skip-chars-backward " \r\t\n")
  6703. (beginning-of-line)
  6704. t))))
  6705. (forward-line))))))))
  6706. ;; Shift lines but footnote definitions, inlinetasks boundaries
  6707. ;; by DIFF. Also skip contents of source or example blocks
  6708. ;; when indentation is meant to be preserved.
  6709. (while (not (eobp))
  6710. (cond
  6711. ((and (looking-at-p org-footnote-definition-re)
  6712. (let ((e (org-element-at-point)))
  6713. (and (eq (org-element-type e) 'footnote-definition)
  6714. (goto-char (org-element-property :end e))))))
  6715. ((looking-at-p org-outline-regexp) (forward-line))
  6716. ((looking-at-p "[ \t]*$") (forward-line))
  6717. (t
  6718. (indent-line-to (+ (current-indentation) diff))
  6719. (beginning-of-line)
  6720. (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
  6721. (let ((e (org-element-at-point)))
  6722. (and (memq (org-element-type e)
  6723. '(example-block src-block))
  6724. (or org-src-preserve-indentation
  6725. (org-element-property :preserve-indent e))
  6726. (goto-char (org-element-property :end e))
  6727. (progn (skip-chars-backward " \r\t\n")
  6728. (beginning-of-line)
  6729. t))))
  6730. (forward-line)))))))))
  6731. (defun org-convert-to-odd-levels ()
  6732. "Convert an Org file with all levels allowed to one with odd levels.
  6733. This will leave level 1 alone, convert level 2 to level 3, level 3 to
  6734. level 5 etc."
  6735. (interactive)
  6736. (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
  6737. (let ((outline-level 'org-outline-level)
  6738. (org-odd-levels-only nil) n)
  6739. (save-excursion
  6740. (goto-char (point-min))
  6741. (while (re-search-forward "^\\*\\*+ " nil t)
  6742. (setq n (- (length (match-string 0)) 2))
  6743. (while (>= (setq n (1- n)) 0)
  6744. (org-demote))
  6745. (end-of-line 1))))))
  6746. (defun org-convert-to-oddeven-levels ()
  6747. "Convert an Org file with only odd levels to one with odd/even levels.
  6748. This promotes level 3 to level 2, level 5 to level 3 etc. If the
  6749. file contains a section with an even level, conversion would
  6750. destroy the structure of the file. An error is signaled in this
  6751. case."
  6752. (interactive)
  6753. (goto-char (point-min))
  6754. ;; First check if there are no even levels
  6755. (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
  6756. (org-show-set-visibility 'canonical)
  6757. (error "Not all levels are odd in this file. Conversion not possible"))
  6758. (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
  6759. (let ((outline-regexp org-outline-regexp)
  6760. (outline-level 'org-outline-level)
  6761. (org-odd-levels-only nil) n)
  6762. (save-excursion
  6763. (goto-char (point-min))
  6764. (while (re-search-forward "^\\*\\*+ " nil t)
  6765. (setq n (/ (1- (length (match-string 0))) 2))
  6766. (while (>= (setq n (1- n)) 0)
  6767. (org-promote))
  6768. (end-of-line 1))))))
  6769. (defun org-tr-level (n)
  6770. "Make N odd if required."
  6771. (if org-odd-levels-only (1+ (/ n 2)) n))
  6772. ;;; Vertical tree motion, cutting and pasting of subtrees
  6773. (defun org-move-subtree-up (&optional arg)
  6774. "Move the current subtree up past ARG headlines of the same level."
  6775. (interactive "p")
  6776. (org-move-subtree-down (- (prefix-numeric-value arg))))
  6777. (defun org-move-subtree-down (&optional arg)
  6778. "Move the current subtree down past ARG headlines of the same level."
  6779. (interactive "p")
  6780. (setq arg (prefix-numeric-value arg))
  6781. (org-preserve-local-variables
  6782. (let ((movfunc (if (> arg 0) 'org-get-next-sibling
  6783. 'org-get-previous-sibling))
  6784. (ins-point (make-marker))
  6785. (cnt (abs arg))
  6786. (col (current-column))
  6787. beg end txt folded)
  6788. ;; Select the tree
  6789. (org-back-to-heading)
  6790. (setq beg (point))
  6791. (save-match-data
  6792. (save-excursion (outline-end-of-heading)
  6793. (setq folded (org-invisible-p)))
  6794. (progn (org-end-of-subtree nil t)
  6795. (unless (eobp) (backward-char))))
  6796. (outline-next-heading)
  6797. (setq end (point))
  6798. (goto-char beg)
  6799. ;; Find insertion point, with error handling
  6800. (while (> cnt 0)
  6801. (unless (and (funcall movfunc) (looking-at org-outline-regexp))
  6802. (goto-char beg)
  6803. (user-error "Cannot move past superior level or buffer limit"))
  6804. (setq cnt (1- cnt)))
  6805. (when (> arg 0)
  6806. ;; Moving forward - still need to move over subtree
  6807. (org-end-of-subtree t t)
  6808. (save-excursion
  6809. (org-back-over-empty-lines)
  6810. (or (bolp) (newline))))
  6811. (move-marker ins-point (point))
  6812. (setq txt (buffer-substring beg end))
  6813. (org-save-markers-in-region beg end)
  6814. (delete-region beg end)
  6815. (org-remove-empty-overlays-at beg)
  6816. (unless (= beg (point-min)) (org-flag-region (1- beg) beg nil 'outline))
  6817. (unless (bobp) (org-flag-region (1- (point)) (point) nil 'outline))
  6818. (and (not (bolp)) (looking-at "\n") (forward-char 1))
  6819. (let ((bbb (point)))
  6820. (insert-before-markers txt)
  6821. (org-reinstall-markers-in-region bbb)
  6822. (move-marker ins-point bbb))
  6823. (or (bolp) (insert "\n"))
  6824. (goto-char ins-point)
  6825. (org-skip-whitespace)
  6826. (move-marker ins-point nil)
  6827. (if folded
  6828. (org-flag-subtree t)
  6829. (org-show-entry)
  6830. (org-show-children))
  6831. (org-clean-visibility-after-subtree-move)
  6832. ;; move back to the initial column we were at
  6833. (move-to-column col))))
  6834. (defvar org-subtree-clip ""
  6835. "Clipboard for cut and paste of subtrees.
  6836. This is actually only a copy of the kill, because we use the normal kill
  6837. ring. We need it to check if the kill was created by `org-copy-subtree'.")
  6838. (defvar org-subtree-clip-folded nil
  6839. "Was the last copied subtree folded?
  6840. This is used to fold the tree back after pasting.")
  6841. (defun org-cut-subtree (&optional n)
  6842. "Cut the current subtree into the clipboard.
  6843. With prefix arg N, cut this many sequential subtrees.
  6844. This is a short-hand for marking the subtree and then cutting it."
  6845. (interactive "p")
  6846. (org-copy-subtree n 'cut))
  6847. (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
  6848. "Copy the current subtree into the clipboard.
  6849. With prefix arg N, copy this many sequential subtrees.
  6850. This is a short-hand for marking the subtree and then copying it.
  6851. If CUT is non-nil, actually cut the subtree.
  6852. If FORCE-STORE-MARKERS is non-nil, store the relative locations
  6853. of some markers in the region, even if CUT is non-nil. This is
  6854. useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
  6855. (interactive "p")
  6856. (org-preserve-local-variables
  6857. (let (beg end folded (beg0 (point)))
  6858. (if (called-interactively-p 'any)
  6859. (org-back-to-heading nil) ; take what looks like a subtree
  6860. (org-back-to-heading t)) ; take what is really there
  6861. (setq beg (point))
  6862. (skip-chars-forward " \t\r\n")
  6863. (save-match-data
  6864. (if nosubtrees
  6865. (outline-next-heading)
  6866. (save-excursion (outline-end-of-heading)
  6867. (setq folded (org-invisible-p)))
  6868. (ignore-errors (org-forward-heading-same-level (1- n) t))
  6869. (org-end-of-subtree t t)))
  6870. ;; Include the end of an inlinetask
  6871. (when (and (featurep 'org-inlinetask)
  6872. (looking-at-p (concat (org-inlinetask-outline-regexp)
  6873. "END[ \t]*$")))
  6874. (end-of-line))
  6875. (setq end (point))
  6876. (goto-char beg0)
  6877. (when (> end beg)
  6878. (setq org-subtree-clip-folded folded)
  6879. (when (or cut force-store-markers)
  6880. (org-save-markers-in-region beg end))
  6881. (if cut (kill-region beg end) (copy-region-as-kill beg end))
  6882. (setq org-subtree-clip (current-kill 0))
  6883. (message "%s: Subtree(s) with %d characters"
  6884. (if cut "Cut" "Copied")
  6885. (length org-subtree-clip))))))
  6886. (defun org-paste-subtree (&optional level tree for-yank remove)
  6887. "Paste the clipboard as a subtree, with modification of headline level.
  6888. The entire subtree is promoted or demoted in order to match a new headline
  6889. level.
  6890. If the cursor is at the beginning of a headline, the same level as
  6891. that headline is used to paste the tree.
  6892. If not, the new level is derived from the *visible* headings
  6893. before and after the insertion point, and taken to be the inferior headline
  6894. level of the two. So if the previous visible heading is level 3 and the
  6895. next is level 4 (or vice versa), level 4 will be used for insertion.
  6896. This makes sure that the subtree remains an independent subtree and does
  6897. not swallow low level entries.
  6898. You can also force a different level, either by using a numeric prefix
  6899. argument, or by inserting the heading marker by hand. For example, if the
  6900. cursor is after \"*****\", then the tree will be shifted to level 5.
  6901. If optional TREE is given, use this text instead of the kill ring.
  6902. When FOR-YANK is set, this is called by `org-yank'. In this case, do not
  6903. move back over whitespace before inserting, and move point to the end of
  6904. the inserted text when done.
  6905. When REMOVE is non-nil, remove the subtree from the clipboard."
  6906. (interactive "P")
  6907. (setq tree (or tree (and kill-ring (current-kill 0))))
  6908. (unless (org-kill-is-subtree-p tree)
  6909. (user-error
  6910. (substitute-command-keys
  6911. "The kill is not a (set of) tree(s). Use `\\[yank]' to yank anyway")))
  6912. (org-with-limited-levels
  6913. (let* ((visp (not (org-invisible-p)))
  6914. (txt tree)
  6915. (old-level (if (string-match org-outline-regexp-bol txt)
  6916. (- (match-end 0) (match-beginning 0) 1)
  6917. -1))
  6918. (force-level
  6919. (cond
  6920. (level (prefix-numeric-value level))
  6921. ;; When point is after the stars in an otherwise empty
  6922. ;; headline, use the number of stars as the forced level.
  6923. ((and (org-match-line "^\\*+[ \t]*$")
  6924. (not (eq ?* (char-after))))
  6925. (org-outline-level))
  6926. ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
  6927. (previous-level
  6928. (save-excursion
  6929. (org-previous-visible-heading 1)
  6930. (if (org-at-heading-p) (org-outline-level) 1)))
  6931. (next-level
  6932. (save-excursion
  6933. (if (org-at-heading-p) (org-outline-level)
  6934. (org-next-visible-heading 1)
  6935. (if (org-at-heading-p) (org-outline-level) 1))))
  6936. (new-level (or force-level (max previous-level next-level)))
  6937. (shift (if (or (= old-level -1)
  6938. (= new-level -1)
  6939. (= old-level new-level))
  6940. 0
  6941. (- new-level old-level)))
  6942. (delta (if (> shift 0) -1 1))
  6943. (func (if (> shift 0) #'org-demote #'org-promote))
  6944. (org-odd-levels-only nil)
  6945. beg end newend)
  6946. ;; Remove the forced level indicator.
  6947. (when (and force-level (not level))
  6948. (delete-region (line-beginning-position) (point)))
  6949. ;; Paste before the next visible heading or at end of buffer,
  6950. ;; unless point is at the beginning of a headline.
  6951. (unless (and (bolp) (org-at-heading-p))
  6952. (org-next-visible-heading 1)
  6953. (unless (bolp) (insert "\n")))
  6954. (setq beg (point))
  6955. (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
  6956. (insert-before-markers txt)
  6957. (unless (string-suffix-p "\n" txt) (insert "\n"))
  6958. (setq newend (point))
  6959. (org-reinstall-markers-in-region beg)
  6960. (setq end (point))
  6961. (goto-char beg)
  6962. (skip-chars-forward " \t\n\r")
  6963. (setq beg (point))
  6964. (when (and (org-invisible-p) visp)
  6965. (save-excursion (outline-show-heading)))
  6966. ;; Shift if necessary.
  6967. (unless (= shift 0)
  6968. (save-restriction
  6969. (narrow-to-region beg end)
  6970. (while (not (= shift 0))
  6971. (org-map-region func (point-min) (point-max))
  6972. (setq shift (+ delta shift)))
  6973. (goto-char (point-min))
  6974. (setq newend (point-max))))
  6975. (when (or for-yank (called-interactively-p 'interactive))
  6976. (message "Clipboard pasted as level %d subtree" new-level))
  6977. (when (and (not for-yank) ; in this case, org-yank will decide about folding
  6978. kill-ring
  6979. (equal org-subtree-clip (current-kill 0))
  6980. org-subtree-clip-folded)
  6981. ;; The tree was folded before it was killed/copied
  6982. (org-flag-subtree t))
  6983. (when for-yank (goto-char newend))
  6984. (when remove (pop kill-ring)))))
  6985. (defun org-kill-is-subtree-p (&optional txt)
  6986. "Check if the current kill is an outline subtree, or a set of trees.
  6987. Returns nil if kill does not start with a headline, or if the first
  6988. headline level is not the largest headline level in the tree.
  6989. So this will actually accept several entries of equal levels as well,
  6990. which is OK for `org-paste-subtree'.
  6991. If optional TXT is given, check this string instead of the current kill."
  6992. (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
  6993. (re (org-get-limited-outline-regexp))
  6994. (^re (concat "^" re))
  6995. (start-level (and kill
  6996. (string-match
  6997. (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
  6998. kill)
  6999. (- (match-end 2) (match-beginning 2) 1)))
  7000. (start (1+ (or (match-beginning 2) -1))))
  7001. (if (not start-level)
  7002. (progn
  7003. nil) ;; does not even start with a heading
  7004. (catch 'exit
  7005. (while (setq start (string-match ^re kill (1+ start)))
  7006. (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
  7007. (throw 'exit nil)))
  7008. t))))
  7009. (defvar org-markers-to-move nil
  7010. "Markers that should be moved with a cut-and-paste operation.
  7011. Those markers are stored together with their positions relative to
  7012. the start of the region.")
  7013. (defun org-save-markers-in-region (beg end)
  7014. "Check markers in region.
  7015. If these markers are between BEG and END, record their position relative
  7016. to BEG, so that after moving the block of text, we can put the markers back
  7017. into place.
  7018. This function gets called just before an entry or tree gets cut from the
  7019. buffer. After re-insertion, `org-reinstall-markers-in-region' must be
  7020. called immediately, to move the markers with the entries."
  7021. (setq org-markers-to-move nil)
  7022. (when (featurep 'org-clock)
  7023. (org-clock-save-markers-for-cut-and-paste beg end))
  7024. (when (featurep 'org-agenda)
  7025. (org-agenda-save-markers-for-cut-and-paste beg end)))
  7026. (defun org-check-and-save-marker (marker beg end)
  7027. "Check if MARKER is between BEG and END.
  7028. If yes, remember the marker and the distance to BEG."
  7029. (when (and (marker-buffer marker)
  7030. (or (equal (marker-buffer marker) (current-buffer))
  7031. (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
  7032. (>= marker beg) (< marker end))
  7033. (push (cons marker (- marker beg)) org-markers-to-move)))
  7034. (defun org-reinstall-markers-in-region (beg)
  7035. "Move all remembered markers to their position relative to BEG."
  7036. (dolist (x org-markers-to-move)
  7037. (move-marker (car x) (+ beg (cdr x))))
  7038. (setq org-markers-to-move nil))
  7039. (defun org-narrow-to-subtree ()
  7040. "Narrow buffer to the current subtree."
  7041. (interactive)
  7042. (save-excursion
  7043. (save-match-data
  7044. (org-with-limited-levels
  7045. (narrow-to-region
  7046. (progn (org-back-to-heading t) (point))
  7047. (progn (org-end-of-subtree t t)
  7048. (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
  7049. (point)))))))
  7050. (defun org-toggle-narrow-to-subtree ()
  7051. "Narrow to the subtree at point or widen a narrowed buffer."
  7052. (interactive)
  7053. (if (buffer-narrowed-p)
  7054. (progn (widen) (message "Buffer widen"))
  7055. (org-narrow-to-subtree)
  7056. (message "Buffer narrowed to current subtree")))
  7057. (defun org-narrow-to-block ()
  7058. "Narrow buffer to the current block."
  7059. (interactive)
  7060. (let* ((case-fold-search t)
  7061. (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
  7062. "^[ \t]*#\\+end_.*")))
  7063. (if blockp
  7064. (narrow-to-region (car blockp) (cdr blockp))
  7065. (user-error "Not in a block"))))
  7066. (defun org-clone-subtree-with-time-shift (n &optional shift)
  7067. "Clone the task (subtree) at point N times.
  7068. The clones will be inserted as siblings.
  7069. In interactive use, the user will be prompted for the number of
  7070. clones to be produced. If the entry has a timestamp, the user
  7071. will also be prompted for a time shift, which may be a repeater
  7072. as used in time stamps, for example `+3d'. To disable this,
  7073. you can call the function with a universal prefix argument.
  7074. When a valid repeater is given and the entry contains any time
  7075. stamps, the clones will become a sequence in time, with time
  7076. stamps in the subtree shifted for each clone produced. If SHIFT
  7077. is nil or the empty string, time stamps will be left alone. The
  7078. ID property of the original subtree is removed.
  7079. In each clone, all the CLOCK entries will be removed. This
  7080. prevents Org from considering that the clocked times overlap.
  7081. If the original subtree did contain time stamps with a repeater,
  7082. the following will happen:
  7083. - the repeater will be removed in each clone
  7084. - an additional clone will be produced, with the current, unshifted
  7085. date(s) in the entry.
  7086. - the original entry will be placed *after* all the clones, with
  7087. repeater intact.
  7088. - the start days in the repeater in the original entry will be shifted
  7089. to past the last clone.
  7090. In this way you can spell out a number of instances of a repeating task,
  7091. and still retain the repeater to cover future instances of the task.
  7092. As described above, N+1 clones are produced when the original
  7093. subtree has a repeater. Setting N to 0, then, can be used to
  7094. remove the repeater from a subtree and create a shifted clone
  7095. with the original repeater."
  7096. (interactive "nNumber of clones to produce: ")
  7097. (unless (wholenump n) (user-error "Invalid number of replications %s" n))
  7098. (when (org-before-first-heading-p) (user-error "No subtree to clone"))
  7099. (let* ((beg (save-excursion (org-back-to-heading t) (point)))
  7100. (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
  7101. (shift
  7102. (or shift
  7103. (if (and (not (equal current-prefix-arg '(4)))
  7104. (save-excursion
  7105. (goto-char beg)
  7106. (re-search-forward org-ts-regexp-both end-of-tree t)))
  7107. (read-from-minibuffer
  7108. "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
  7109. ""))) ;No time shift
  7110. (doshift
  7111. (and (org-string-nw-p shift)
  7112. (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
  7113. shift)
  7114. (user-error "Invalid shift specification %s" shift)))))
  7115. (goto-char end-of-tree)
  7116. (unless (bolp) (insert "\n"))
  7117. (let* ((end (point))
  7118. (template (buffer-substring beg end))
  7119. (shift-n (and doshift (string-to-number (match-string 1 shift))))
  7120. (shift-what (pcase (and doshift (match-string 2 shift))
  7121. (`nil nil)
  7122. ("h" 'hour)
  7123. ("d" 'day)
  7124. ("w" (setq shift-n (* 7 shift-n)) 'day)
  7125. ("m" 'month)
  7126. ("y" 'year)
  7127. (_ (error "Unsupported time unit"))))
  7128. (nmin 1)
  7129. (nmax n)
  7130. (n-no-remove -1)
  7131. (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
  7132. (idprop (org-entry-get beg "ID")))
  7133. (when (and doshift
  7134. (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
  7135. template))
  7136. (delete-region beg end)
  7137. (setq end beg)
  7138. (setq nmin 0)
  7139. (setq nmax (1+ nmax))
  7140. (setq n-no-remove nmax))
  7141. (goto-char end)
  7142. (cl-loop for n from nmin to nmax do
  7143. (insert
  7144. ;; Prepare clone.
  7145. (with-temp-buffer
  7146. (insert template)
  7147. (org-mode)
  7148. (goto-char (point-min))
  7149. (org-show-subtree)
  7150. (and idprop (if org-clone-delete-id
  7151. (org-entry-delete nil "ID")
  7152. (org-id-get-create t)))
  7153. (unless (= n 0)
  7154. (while (re-search-forward org-clock-line-re nil t)
  7155. (delete-region (line-beginning-position)
  7156. (line-beginning-position 2)))
  7157. (goto-char (point-min))
  7158. (while (re-search-forward org-drawer-regexp nil t)
  7159. (org-remove-empty-drawer-at (point))))
  7160. (goto-char (point-min))
  7161. (when doshift
  7162. (while (re-search-forward org-ts-regexp-both nil t)
  7163. (org-timestamp-change (* n shift-n) shift-what))
  7164. (unless (= n n-no-remove)
  7165. (goto-char (point-min))
  7166. (while (re-search-forward org-ts-regexp nil t)
  7167. (save-excursion
  7168. (goto-char (match-beginning 0))
  7169. (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
  7170. (delete-region (match-beginning 1) (match-end 1)))))))
  7171. (buffer-string)))))
  7172. (goto-char beg)))
  7173. ;;; Outline path
  7174. (defvar org-outline-path-cache nil
  7175. "Alist between buffer positions and outline paths.
  7176. It value is an alist (POSITION . PATH) where POSITION is the
  7177. buffer position at the beginning of an entry and PATH is a list
  7178. of strings describing the outline path for that entry, in reverse
  7179. order.")
  7180. (defun org--get-outline-path-1 (&optional use-cache)
  7181. "Return outline path to current headline.
  7182. Outline path is a list of strings, in reverse order. When
  7183. optional argument USE-CACHE is non-nil, make use of a cache. See
  7184. `org-get-outline-path' for details.
  7185. Assume buffer is widened and point is on a headline."
  7186. (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
  7187. (let ((p (point))
  7188. (heading (let ((case-fold-search nil))
  7189. (looking-at org-complex-heading-regexp)
  7190. (if (not (match-end 4)) ""
  7191. ;; Remove statistics cookies.
  7192. (org-trim
  7193. (org-link-display-format
  7194. (replace-regexp-in-string
  7195. "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
  7196. (match-string-no-properties 4))))))))
  7197. (if (org-up-heading-safe)
  7198. (let ((path (cons heading (org--get-outline-path-1 use-cache))))
  7199. (when use-cache
  7200. (push (cons p path) org-outline-path-cache))
  7201. path)
  7202. ;; This is a new root node. Since we assume we are moving
  7203. ;; forward, we can drop previous cache so as to limit number
  7204. ;; of associations there.
  7205. (let ((path (list heading)))
  7206. (when use-cache (setq org-outline-path-cache (list (cons p path))))
  7207. path)))))
  7208. (defun org-get-outline-path (&optional with-self use-cache)
  7209. "Return the outline path to the current entry.
  7210. An outline path is a list of ancestors for current headline, as
  7211. a list of strings. Statistics cookies are removed and links are
  7212. replaced with their description, if any, or their path otherwise.
  7213. When optional argument WITH-SELF is non-nil, the path also
  7214. includes the current headline.
  7215. When optional argument USE-CACHE is non-nil, cache outline paths
  7216. between calls to this function so as to avoid backtracking. This
  7217. argument is useful when planning to find more than one outline
  7218. path in the same document. In that case, there are two
  7219. conditions to satisfy:
  7220. - `org-outline-path-cache' is set to nil before starting the
  7221. process;
  7222. - outline paths are computed by increasing buffer positions."
  7223. (org-with-wide-buffer
  7224. (and (or (and with-self (org-back-to-heading t))
  7225. (org-up-heading-safe))
  7226. (reverse (org--get-outline-path-1 use-cache)))))
  7227. (defun org-format-outline-path (path &optional width prefix separator)
  7228. "Format the outline path PATH for display.
  7229. WIDTH is the maximum number of characters that is available.
  7230. PREFIX is a prefix to be included in the returned string,
  7231. such as the file name.
  7232. SEPARATOR is inserted between the different parts of the path,
  7233. the default is \"/\"."
  7234. (setq width (or width 79))
  7235. (setq path (delq nil path))
  7236. (unless (> width 0)
  7237. (user-error "Argument `width' must be positive"))
  7238. (setq separator (or separator "/"))
  7239. (let* ((org-odd-levels-only nil)
  7240. (fpath (concat
  7241. prefix (and prefix path separator)
  7242. (mapconcat
  7243. (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
  7244. (cl-loop for head in path
  7245. for n from 0
  7246. collect (org-add-props
  7247. head nil 'face
  7248. (nth (% n org-n-level-faces) org-level-faces)))
  7249. separator))))
  7250. (when (> (length fpath) width)
  7251. (if (< width 7)
  7252. ;; It's unlikely that `width' will be this small, but don't
  7253. ;; waste characters by adding ".." if it is.
  7254. (setq fpath (substring fpath 0 width))
  7255. (setf (substring fpath (- width 2)) "..")))
  7256. fpath))
  7257. (defun org-display-outline-path (&optional file current separator just-return-string)
  7258. "Display the current outline path in the echo area.
  7259. If FILE is non-nil, prepend the output with the file name.
  7260. If CURRENT is non-nil, append the current heading to the output.
  7261. SEPARATOR is passed through to `org-format-outline-path'. It separates
  7262. the different parts of the path and defaults to \"/\".
  7263. If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
  7264. (interactive "P")
  7265. (let* (case-fold-search
  7266. (bfn (buffer-file-name (buffer-base-buffer)))
  7267. (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
  7268. res)
  7269. (when current (setq path (append path
  7270. (save-excursion
  7271. (org-back-to-heading t)
  7272. (when (looking-at org-complex-heading-regexp)
  7273. (list (match-string 4)))))))
  7274. (setq res
  7275. (org-format-outline-path
  7276. path
  7277. (1- (frame-width))
  7278. (and file bfn (concat (file-name-nondirectory bfn) separator))
  7279. separator))
  7280. (add-face-text-property 0 (length res)
  7281. `(:height ,(face-attribute 'default :height))
  7282. nil res)
  7283. (if just-return-string
  7284. res
  7285. (org-unlogged-message "%s" res))))
  7286. ;;; Outline Sorting
  7287. (defun org-sort (&optional with-case)
  7288. "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
  7289. Optional argument WITH-CASE means sort case-sensitively."
  7290. (interactive "P")
  7291. (org-call-with-arg
  7292. (cond ((org-at-table-p) #'org-table-sort-lines)
  7293. ((org-at-item-p) #'org-sort-list)
  7294. (t #'org-sort-entries))
  7295. with-case))
  7296. (defun org-sort-remove-invisible (s)
  7297. "Remove emphasis markers and any invisible property from string S.
  7298. Assume S may contain only objects."
  7299. ;; org-element-interpret-data clears any text property, including
  7300. ;; invisible part.
  7301. (org-element-interpret-data
  7302. (let ((tree (org-element-parse-secondary-string
  7303. s (org-element-restriction 'paragraph))))
  7304. (org-element-map tree '(bold code italic link strike-through underline verbatim)
  7305. (lambda (o)
  7306. (pcase (org-element-type o)
  7307. ;; Terminal object. Replace it with its value.
  7308. ((or `code `verbatim)
  7309. (let ((new (org-element-property :value o)))
  7310. (org-element-insert-before new o)
  7311. (org-element-put-property
  7312. new :post-blank (org-element-property :post-blank o))))
  7313. ;; Non-terminal objects. Splice contents.
  7314. (type
  7315. (let ((contents
  7316. (or (org-element-contents o)
  7317. (and (eq type 'link)
  7318. (list (org-element-property :raw-link o)))))
  7319. (c nil))
  7320. (while contents
  7321. (setq c (pop contents))
  7322. (org-element-insert-before c o))
  7323. (org-element-put-property
  7324. c :post-blank (org-element-property :post-blank o)))))
  7325. (org-element-extract-element o)))
  7326. ;; Return modified tree.
  7327. tree)))
  7328. (defvar org-after-sorting-entries-or-items-hook nil
  7329. "Hook that is run after a bunch of entries or items have been sorted.
  7330. When children are sorted, the cursor is in the parent line when this
  7331. hook gets called. When a region or a plain list is sorted, the cursor
  7332. will be in the first entry of the sorted region/list.")
  7333. (defun org-sort-entries
  7334. (&optional with-case sorting-type getkey-func compare-func property
  7335. interactive?)
  7336. "Sort entries on a certain level of an outline tree.
  7337. If there is an active region, the entries in the region are sorted.
  7338. Else, if the cursor is before the first entry, sort the top-level items.
  7339. Else, the children of the entry at point are sorted.
  7340. Sorting can be alphabetically, numerically, by date/time as given by
  7341. a time stamp, by a property, by priority order, or by a custom function.
  7342. The command prompts for the sorting type unless it has been given to the
  7343. function through the SORTING-TYPE argument, which needs to be a character,
  7344. \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
  7345. the precise meaning of each character:
  7346. a Alphabetically, ignoring the TODO keyword and the priority, if any.
  7347. c By creation time, which is assumed to be the first inactive time stamp
  7348. at the beginning of a line.
  7349. d By deadline date/time.
  7350. k By clocking time.
  7351. n Numerically, by converting the beginning of the entry/item to a number.
  7352. o By order of TODO keywords.
  7353. p By priority according to the cookie.
  7354. r By the value of a property.
  7355. s By scheduled date/time.
  7356. t By date/time, either the first active time stamp in the entry, or, if
  7357. none exist, by the first inactive one.
  7358. Capital letters will reverse the sort order.
  7359. If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
  7360. called with point at the beginning of the record. It must return a
  7361. value that is compatible with COMPARE-FUNC, the function used to
  7362. compare entries.
  7363. Comparing entries ignores case by default. However, with an optional argument
  7364. WITH-CASE, the sorting considers case as well.
  7365. Sorting is done against the visible part of the headlines, it ignores hidden
  7366. links.
  7367. When sorting is done, call `org-after-sorting-entries-or-items-hook'.
  7368. A non-nil value for INTERACTIVE? is used to signal that this
  7369. function is being called interactively."
  7370. (interactive (list current-prefix-arg nil nil nil nil t))
  7371. (let ((case-func (if with-case 'identity 'downcase))
  7372. start beg end stars re re2
  7373. txt what tmp)
  7374. ;; Find beginning and end of region to sort
  7375. (cond
  7376. ((org-region-active-p)
  7377. ;; we will sort the region
  7378. (setq end (region-end)
  7379. what "region")
  7380. (goto-char (region-beginning))
  7381. (unless (org-at-heading-p) (outline-next-heading))
  7382. (setq start (point)))
  7383. ((or (org-at-heading-p)
  7384. (ignore-errors (progn (org-back-to-heading) t)))
  7385. ;; we will sort the children of the current headline
  7386. (org-back-to-heading)
  7387. (setq start (point)
  7388. end (progn (org-end-of-subtree t t)
  7389. (or (bolp) (insert "\n"))
  7390. (when (>= (org-back-over-empty-lines) 1)
  7391. (forward-line 1))
  7392. (point))
  7393. what "children")
  7394. (goto-char start)
  7395. (outline-show-subtree)
  7396. (outline-next-heading))
  7397. (t
  7398. ;; we will sort the top-level entries in this file
  7399. (goto-char (point-min))
  7400. (or (org-at-heading-p) (outline-next-heading))
  7401. (setq start (point))
  7402. (goto-char (point-max))
  7403. (beginning-of-line 1)
  7404. (when (looking-at ".*?\\S-")
  7405. ;; File ends in a non-white line
  7406. (end-of-line 1)
  7407. (insert "\n"))
  7408. (setq end (point-max))
  7409. (setq what "top-level")
  7410. (goto-char start)
  7411. (org-show-all '(headings drawers blocks))))
  7412. (setq beg (point))
  7413. (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
  7414. (looking-at "\\(\\*+\\)")
  7415. (setq stars (match-string 1)
  7416. re (concat "^" (regexp-quote stars) " +")
  7417. re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
  7418. txt (buffer-substring beg end))
  7419. (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
  7420. (when (and (not (equal stars "*")) (string-match re2 txt))
  7421. (user-error "Region to sort contains a level above the first entry"))
  7422. (unless sorting-type
  7423. (message
  7424. "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
  7425. [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
  7426. A/N/P/R/O/F/T/S/D/C/K means reversed:"
  7427. what)
  7428. (setq sorting-type (read-char-exclusive)))
  7429. (unless getkey-func
  7430. (and (= (downcase sorting-type) ?f)
  7431. (setq getkey-func
  7432. (or (and interactive?
  7433. (org-read-function
  7434. "Function for extracting keys: "))
  7435. (error "Missing key extractor")))))
  7436. (and (= (downcase sorting-type) ?r)
  7437. (not property)
  7438. (setq property
  7439. (completing-read "Property: "
  7440. (mapcar #'list (org-buffer-property-keys t))
  7441. nil t)))
  7442. (when (member sorting-type '(?k ?K)) (org-clock-sum))
  7443. (message "Sorting entries...")
  7444. (save-restriction
  7445. (narrow-to-region start end)
  7446. (let ((restore-clock?
  7447. ;; The clock marker is lost when using `sort-subr'; mark
  7448. ;; the clock with temporary `:org-clock-marker-backup'
  7449. ;; text property.
  7450. (when (and (eq (org-clocking-buffer) (current-buffer))
  7451. (<= start (marker-position org-clock-marker))
  7452. (>= end (marker-position org-clock-marker)))
  7453. (with-silent-modifications
  7454. (put-text-property (1- org-clock-marker) org-clock-marker
  7455. :org-clock-marker-backup t))
  7456. t))
  7457. (dcst (downcase sorting-type))
  7458. (case-fold-search nil)
  7459. (now (current-time)))
  7460. (org-preserve-local-variables
  7461. (sort-subr
  7462. (/= dcst sorting-type)
  7463. ;; This function moves to the beginning character of the
  7464. ;; "record" to be sorted.
  7465. (lambda nil
  7466. (if (re-search-forward re nil t)
  7467. (goto-char (match-beginning 0))
  7468. (goto-char (point-max))))
  7469. ;; This function moves to the last character of the "record" being
  7470. ;; sorted.
  7471. (lambda nil
  7472. (save-match-data
  7473. (condition-case nil
  7474. (outline-forward-same-level 1)
  7475. (error
  7476. (goto-char (point-max))))))
  7477. ;; This function returns the value that gets sorted against.
  7478. (lambda ()
  7479. (cond
  7480. ((= dcst ?n)
  7481. (string-to-number
  7482. (org-sort-remove-invisible (org-get-heading t t t t))))
  7483. ((= dcst ?a)
  7484. (funcall case-func
  7485. (org-sort-remove-invisible (org-get-heading t t t t))))
  7486. ((= dcst ?k)
  7487. (or (get-text-property (point) :org-clock-minutes) 0))
  7488. ((= dcst ?t)
  7489. (let ((end (save-excursion (outline-next-heading) (point))))
  7490. (if (or (re-search-forward org-ts-regexp end t)
  7491. (re-search-forward org-ts-regexp-both end t))
  7492. (org-time-string-to-seconds (match-string 0))
  7493. (float-time now))))
  7494. ((= dcst ?c)
  7495. (let ((end (save-excursion (outline-next-heading) (point))))
  7496. (if (re-search-forward
  7497. (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
  7498. end t)
  7499. (org-time-string-to-seconds (match-string 0))
  7500. (float-time now))))
  7501. ((= dcst ?s)
  7502. (let ((end (save-excursion (outline-next-heading) (point))))
  7503. (if (re-search-forward org-scheduled-time-regexp end t)
  7504. (org-time-string-to-seconds (match-string 1))
  7505. (float-time now))))
  7506. ((= dcst ?d)
  7507. (let ((end (save-excursion (outline-next-heading) (point))))
  7508. (if (re-search-forward org-deadline-time-regexp end t)
  7509. (org-time-string-to-seconds (match-string 1))
  7510. (float-time now))))
  7511. ((= dcst ?p)
  7512. (if (re-search-forward org-priority-regexp (point-at-eol) t)
  7513. (string-to-char (match-string 2))
  7514. org-priority-default))
  7515. ((= dcst ?r)
  7516. (or (org-entry-get nil property) ""))
  7517. ((= dcst ?o)
  7518. (when (looking-at org-complex-heading-regexp)
  7519. (let* ((m (match-string 2))
  7520. (s (if (member m org-done-keywords) '- '+)))
  7521. (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
  7522. ((= dcst ?f)
  7523. (if getkey-func
  7524. (progn
  7525. (setq tmp (funcall getkey-func))
  7526. (when (stringp tmp) (setq tmp (funcall case-func tmp)))
  7527. tmp)
  7528. (error "Invalid key function `%s'" getkey-func)))
  7529. (t (error "Invalid sorting type `%c'" sorting-type))))
  7530. nil
  7531. (cond
  7532. ((= dcst ?a) 'string-collate-lessp)
  7533. ((= dcst ?f)
  7534. (or compare-func
  7535. (and interactive?
  7536. (org-read-function
  7537. (concat "Function for comparing keys "
  7538. "(empty for default `sort-subr' predicate): ")
  7539. 'allow-empty))))
  7540. ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
  7541. (org-cycle-hide-drawers 'all)
  7542. (when restore-clock?
  7543. (move-marker org-clock-marker
  7544. (1+ (next-single-property-change
  7545. start :org-clock-marker-backup)))
  7546. (remove-text-properties (1- org-clock-marker) org-clock-marker
  7547. '(:org-clock-marker-backup t)))))
  7548. (run-hooks 'org-after-sorting-entries-or-items-hook)
  7549. (message "Sorting entries...done")))
  7550. (defun org-contextualize-keys (alist contexts)
  7551. "Return valid elements in ALIST depending on CONTEXTS.
  7552. `org-agenda-custom-commands' or `org-capture-templates' are the
  7553. values used for ALIST, and `org-agenda-custom-commands-contexts'
  7554. or `org-capture-templates-contexts' are the associated contexts
  7555. definitions."
  7556. (let ((contexts
  7557. ;; normalize contexts
  7558. (mapcar
  7559. (lambda(c) (cond ((listp (cadr c))
  7560. (list (car c) (car c) (nth 1 c)))
  7561. ((string= "" (cadr c))
  7562. (list (car c) (car c) (nth 2 c)))
  7563. (t c)))
  7564. contexts))
  7565. (a alist) r s)
  7566. ;; loop over all commands or templates
  7567. (dolist (c a)
  7568. (let (vrules repl)
  7569. (cond
  7570. ((not (assoc (car c) contexts))
  7571. (push c r))
  7572. ((and (assoc (car c) contexts)
  7573. (setq vrules (org-contextualize-validate-key
  7574. (car c) contexts)))
  7575. (mapc (lambda (vr)
  7576. (unless (equal (car vr) (cadr vr))
  7577. (setq repl vr)))
  7578. vrules)
  7579. (if (not repl) (push c r)
  7580. (push (cadr repl) s)
  7581. (push
  7582. (cons (car c)
  7583. (cdr (or (assoc (cadr repl) alist)
  7584. (error "Undefined key `%s' as contextual replacement for `%s'"
  7585. (cadr repl) (car c)))))
  7586. r))))))
  7587. ;; Return limited ALIST, possibly with keys modified, and deduplicated
  7588. (delq
  7589. nil
  7590. (delete-dups
  7591. (mapcar (lambda (x)
  7592. (let ((tpl (car x)))
  7593. (unless (delq
  7594. nil
  7595. (mapcar (lambda (y)
  7596. (equal y tpl))
  7597. s))
  7598. x)))
  7599. (reverse r))))))
  7600. (defun org-contextualize-validate-key (key contexts)
  7601. "Check CONTEXTS for agenda or capture KEY."
  7602. (let (res)
  7603. (dolist (r contexts)
  7604. (dolist (rr (car (last r)))
  7605. (when
  7606. (and (equal key (car r))
  7607. (if (functionp rr) (funcall rr)
  7608. (or (and (eq (car rr) 'in-file)
  7609. (buffer-file-name)
  7610. (string-match (cdr rr) (buffer-file-name)))
  7611. (and (eq (car rr) 'in-mode)
  7612. (string-match (cdr rr) (symbol-name major-mode)))
  7613. (and (eq (car rr) 'in-buffer)
  7614. (string-match (cdr rr) (buffer-name)))
  7615. (when (and (eq (car rr) 'not-in-file)
  7616. (buffer-file-name))
  7617. (not (string-match (cdr rr) (buffer-file-name))))
  7618. (when (eq (car rr) 'not-in-mode)
  7619. (not (string-match (cdr rr) (symbol-name major-mode))))
  7620. (when (eq (car rr) 'not-in-buffer)
  7621. (not (string-match (cdr rr) (buffer-name)))))))
  7622. (push r res))))
  7623. (delete-dups (delq nil res))))
  7624. ;; Defined to provide a value for defcustom, since there is no
  7625. ;; string-collate-greaterp in Emacs.
  7626. (defun org-string-collate-greaterp (s1 s2)
  7627. "Return non-nil if S1 is greater than S2 in collation order."
  7628. (not (string-collate-lessp s1 s2)))
  7629. ;;;###autoload
  7630. (defun org-run-like-in-org-mode (cmd)
  7631. "Run a command, pretending that the current buffer is in Org mode.
  7632. This will temporarily bind local variables that are typically bound in
  7633. Org mode to the values they have in Org mode, and then interactively
  7634. call CMD."
  7635. (org-load-modules-maybe)
  7636. (let (binds)
  7637. (dolist (var (org-get-local-variables))
  7638. (when (or (not (boundp (car var)))
  7639. (eq (symbol-value (car var))
  7640. (default-value (car var))))
  7641. (push (list (car var) `(quote ,(cadr var))) binds)))
  7642. (eval `(let ,binds
  7643. (call-interactively (quote ,cmd))))))
  7644. (defun org-get-category (&optional pos force-refresh)
  7645. "Get the category applying to position POS."
  7646. (save-match-data
  7647. (when force-refresh (org-refresh-category-properties))
  7648. (let ((pos (or pos (point))))
  7649. (or (get-text-property pos 'org-category)
  7650. (progn (org-refresh-category-properties)
  7651. (get-text-property pos 'org-category))))))
  7652. ;;; Refresh properties
  7653. (defun org-refresh-properties (dprop tprop)
  7654. "Refresh buffer text properties.
  7655. DPROP is the drawer property and TPROP is either the
  7656. corresponding text property to set, or an alist with each element
  7657. being a text property (as a symbol) and a function to apply to
  7658. the value of the drawer property."
  7659. (let* ((case-fold-search t)
  7660. (inhibit-read-only t)
  7661. (inherit? (org-property-inherit-p dprop))
  7662. (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
  7663. (global-or-keyword (and inherit?
  7664. (org--property-global-or-keyword-value dprop nil))))
  7665. (with-silent-modifications
  7666. (org-with-point-at 1
  7667. ;; Set global and keyword based values to the whole buffer.
  7668. (when global-or-keyword
  7669. (put-text-property (point-min) (point-max) tprop global-or-keyword))
  7670. ;; Set values based on property-drawers throughout the document.
  7671. (while (re-search-forward property-re nil t)
  7672. (when (org-at-property-p)
  7673. (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
  7674. (outline-next-heading))))))
  7675. (defun org-refresh-property (tprop p &optional inherit)
  7676. "Refresh the buffer text property TPROP from the drawer property P.
  7677. The refresh happens only for the current entry, or the whole
  7678. sub-tree if optional argument INHERIT is non-nil.
  7679. If point is before first headline, the function applies to the
  7680. part before the first headline. In that particular case, when
  7681. optional argument INHERIT is non-nil, it refreshes properties for
  7682. the whole buffer."
  7683. (save-excursion
  7684. (org-back-to-heading-or-point-min t)
  7685. (let ((start (point))
  7686. (end (save-excursion
  7687. (cond ((and inherit (org-before-first-heading-p))
  7688. (point-max))
  7689. (inherit
  7690. (org-end-of-subtree t t))
  7691. ((outline-next-heading))
  7692. ((point-max))))))
  7693. (if (symbolp tprop)
  7694. ;; TPROP is a text property symbol.
  7695. (put-text-property start end tprop p)
  7696. ;; TPROP is an alist with (property . function) elements.
  7697. (pcase-dolist (`(,prop . ,f) tprop)
  7698. (put-text-property start end prop (funcall f p)))))))
  7699. (defun org-refresh-category-properties ()
  7700. "Refresh category text properties in the buffer."
  7701. (let ((case-fold-search t)
  7702. (inhibit-read-only t)
  7703. (default-category
  7704. (cond ((null org-category)
  7705. (if buffer-file-name
  7706. (file-name-sans-extension
  7707. (file-name-nondirectory buffer-file-name))
  7708. "???"))
  7709. ((symbolp org-category) (symbol-name org-category))
  7710. (t org-category))))
  7711. (with-silent-modifications
  7712. (org-with-wide-buffer
  7713. ;; Set buffer-wide property from keyword. Search last #+CATEGORY
  7714. ;; keyword. If none is found, fall-back to `org-category' or
  7715. ;; buffer file name, or set it by the document property drawer.
  7716. (put-text-property
  7717. (point-min) (point-max)
  7718. 'org-category
  7719. (catch 'buffer-category
  7720. (goto-char (point-max))
  7721. (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
  7722. (let ((element (org-element-at-point)))
  7723. (when (eq (org-element-type element) 'keyword)
  7724. (throw 'buffer-category
  7725. (org-element-property :value element)))))
  7726. default-category))
  7727. ;; Set categories from the document property drawer or
  7728. ;; property drawers in the outline. If category is found in
  7729. ;; the property drawer for the whole buffer that value
  7730. ;; overrides the keyword-based value set above.
  7731. (goto-char (point-min))
  7732. (let ((regexp (org-re-property "CATEGORY")))
  7733. (while (re-search-forward regexp nil t)
  7734. (let ((value (match-string-no-properties 3)))
  7735. (when (org-at-property-p)
  7736. (put-text-property
  7737. (save-excursion (org-back-to-heading-or-point-min t))
  7738. (save-excursion (if (org-before-first-heading-p)
  7739. (point-max)
  7740. (org-end-of-subtree t t)))
  7741. 'org-category
  7742. value)))))))))
  7743. (defun org-refresh-stats-properties ()
  7744. "Refresh stats text properties in the buffer."
  7745. (with-silent-modifications
  7746. (org-with-point-at 1
  7747. (let ((regexp (concat org-outline-regexp-bol
  7748. ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
  7749. (while (re-search-forward regexp nil t)
  7750. (let* ((numerator (string-to-number (match-string 1)))
  7751. (denominator (and (match-end 2)
  7752. (string-to-number (match-string 2))))
  7753. (stats (cond ((not denominator) numerator) ;percent
  7754. ((= denominator 0) 0)
  7755. (t (/ (* numerator 100) denominator)))))
  7756. (put-text-property (point) (progn (org-end-of-subtree t t) (point))
  7757. 'org-stats stats)))))))
  7758. (defun org-refresh-effort-properties ()
  7759. "Refresh effort properties."
  7760. (org-refresh-properties
  7761. org-effort-property
  7762. '((effort . identity)
  7763. (effort-minutes . org-duration-to-minutes))))
  7764. (defun org-find-file-at-mouse (ev)
  7765. "Open file link or URL at mouse."
  7766. (interactive "e")
  7767. (mouse-set-point ev)
  7768. (org-open-at-point 'in-emacs))
  7769. (defun org-open-at-mouse (ev)
  7770. "Open file link or URL at mouse.
  7771. See the docstring of `org-open-file' for details."
  7772. (interactive "e")
  7773. (mouse-set-point ev)
  7774. (when (eq major-mode 'org-agenda-mode)
  7775. (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
  7776. (org-open-at-point))
  7777. (defvar org-window-config-before-follow-link nil
  7778. "The window configuration before following a link.
  7779. This is saved in case the need arises to restore it.")
  7780. (defun org--file-default-apps ()
  7781. "Return the default applications for this operating system."
  7782. (pcase system-type
  7783. (`darwin org-file-apps-macos)
  7784. (`windows-nt org-file-apps-windowsnt)
  7785. (_ org-file-apps-gnu)))
  7786. (defun org--file-apps-entry-dlink-p (entry)
  7787. "Non-nil if ENTRY should be matched against the link by `org-open-file'.
  7788. It assumes that is the case when the entry uses a regular
  7789. expression which has at least one grouping construct and the
  7790. action is either a Lisp form or a command string containing
  7791. \"%1\", i.e., using at least one subexpression match as
  7792. a parameter."
  7793. (pcase entry
  7794. (`(,selector . ,action)
  7795. (and (stringp selector)
  7796. (> (regexp-opt-depth selector) 0)
  7797. (or (and (stringp action)
  7798. (string-match "%[0-9]" action))
  7799. (consp action))))
  7800. (_ nil)))
  7801. (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
  7802. "Convert extensions to regular expressions in the cars of LIST.
  7803. Also, weed out any non-string entries, because the return value
  7804. is used only for regexp matching.
  7805. When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
  7806. point to the symbol `emacs', indicating that the file should be
  7807. opened in Emacs."
  7808. (append
  7809. (delq nil
  7810. (mapcar (lambda (x)
  7811. (unless (not (stringp (car x)))
  7812. (if (string-match "\\W" (car x))
  7813. x
  7814. (cons (concat "\\." (car x) "\\'") (cdr x)))))
  7815. list))
  7816. (when add-auto-mode
  7817. (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
  7818. ;;;###autoload
  7819. (defun org-open-file (path &optional in-emacs line search)
  7820. "Open the file at PATH.
  7821. First, this expands any special file name abbreviations. Then the
  7822. configuration variable `org-file-apps' is checked if it contains an
  7823. entry for this file type, and if yes, the corresponding command is launched.
  7824. If no application is found, Emacs simply visits the file.
  7825. With optional prefix argument IN-EMACS, Emacs will visit the file.
  7826. With a double \\[universal-argument] \\[universal-argument] \
  7827. prefix arg, Org tries to avoid opening in Emacs
  7828. and to use an external application to visit the file.
  7829. Optional LINE specifies a line to go to, optional SEARCH a string
  7830. to search for. If LINE or SEARCH is given, the file will be
  7831. opened in Emacs, unless an entry from `org-file-apps' that makes
  7832. use of groups in a regexp matches.
  7833. If you want to change the way frames are used when following a
  7834. link, please customize `org-link-frame-setup'.
  7835. If the file does not exist, throw an error."
  7836. (let* ((file (if (equal path "") buffer-file-name
  7837. (substitute-in-file-name (expand-file-name path))))
  7838. (file-apps (append org-file-apps (org--file-default-apps)))
  7839. (apps (cl-remove-if #'org--file-apps-entry-dlink-p file-apps))
  7840. (apps-dlink (cl-remove-if-not #'org--file-apps-entry-dlink-p
  7841. file-apps))
  7842. (remp (and (assq 'remote apps) (file-remote-p file)))
  7843. (dirp (unless remp (file-directory-p file)))
  7844. (file (if (and dirp org-open-directory-means-index-dot-org)
  7845. (concat (file-name-as-directory file) "index.org")
  7846. file))
  7847. (a-m-a-p (assq 'auto-mode apps))
  7848. (dfile (downcase file))
  7849. ;; Reconstruct the original link from the PATH, LINE and
  7850. ;; SEARCH args.
  7851. (link (cond (line (concat file "::" (number-to-string line)))
  7852. (search (concat file "::" search))
  7853. (t file)))
  7854. (dlink (downcase link))
  7855. (ext
  7856. (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
  7857. (match-string 1 dfile)))
  7858. (save-position-maybe
  7859. (let ((old-buffer (current-buffer))
  7860. (old-pos (point))
  7861. (old-mode major-mode))
  7862. (lambda ()
  7863. (and (derived-mode-p 'org-mode)
  7864. (eq old-mode 'org-mode)
  7865. (or (not (eq old-buffer (current-buffer)))
  7866. (not (eq old-pos (point))))
  7867. (org-mark-ring-push old-pos old-buffer)))))
  7868. cmd link-match-data)
  7869. (cond
  7870. ((member in-emacs '((16) system))
  7871. (setq cmd (cdr (assq 'system apps))))
  7872. (in-emacs (setq cmd 'emacs))
  7873. (t
  7874. (setq cmd (or (and remp (cdr (assq 'remote apps)))
  7875. (and dirp (cdr (assq 'directory apps)))
  7876. ;; First, try matching against apps-dlink if we
  7877. ;; get a match here, store the match data for
  7878. ;; later.
  7879. (let ((match (assoc-default dlink apps-dlink
  7880. 'string-match)))
  7881. (if match
  7882. (progn (setq link-match-data (match-data))
  7883. match)
  7884. (progn (setq in-emacs (or in-emacs line search))
  7885. nil))) ; if we have no match in apps-dlink,
  7886. ; always open the file in emacs if line or search
  7887. ; is given (for backwards compatibility)
  7888. (assoc-default dfile
  7889. (org--file-apps-regexp-alist apps a-m-a-p)
  7890. 'string-match)
  7891. (cdr (assoc ext apps))
  7892. (cdr (assq t apps))))))
  7893. (when (eq cmd 'system)
  7894. (setq cmd (cdr (assq 'system apps))))
  7895. (when (eq cmd 'default)
  7896. (setq cmd (cdr (assoc t apps))))
  7897. (when (eq cmd 'mailcap)
  7898. (require 'mailcap)
  7899. (mailcap-parse-mailcaps)
  7900. (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
  7901. (command (mailcap-mime-info mime-type)))
  7902. (if (stringp command)
  7903. (setq cmd command)
  7904. (setq cmd 'emacs))))
  7905. (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
  7906. (not (file-exists-p file))
  7907. (not org-open-non-existing-files))
  7908. (user-error "No such file: %s" file))
  7909. (cond
  7910. ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
  7911. ;; Remove quotes around the file name - we'll use shell-quote-argument.
  7912. (while (string-match "['\"]%s['\"]" cmd)
  7913. (setq cmd (replace-match "%s" t t cmd)))
  7914. (setq cmd (replace-regexp-in-string
  7915. "%s"
  7916. (shell-quote-argument (convert-standard-filename file))
  7917. cmd
  7918. nil t))
  7919. ;; Replace "%1", "%2" etc. in command with group matches from regex
  7920. (save-match-data
  7921. (let ((match-index 1)
  7922. (number-of-groups (- (/ (length link-match-data) 2) 1)))
  7923. (set-match-data link-match-data)
  7924. (while (<= match-index number-of-groups)
  7925. (let ((regex (concat "%" (number-to-string match-index)))
  7926. (replace-with (match-string match-index dlink)))
  7927. (while (string-match regex cmd)
  7928. (setq cmd (replace-match replace-with t t cmd))))
  7929. (setq match-index (+ match-index 1)))))
  7930. (save-window-excursion
  7931. (message "Running %s...done" cmd)
  7932. ;; Handlers such as "gio open" and kde-open5 start viewer in background
  7933. ;; and exit immediately. Use pipe connection type instead of pty to
  7934. ;; avoid killing children processes with SIGHUP when temporary terminal
  7935. ;; session is finished.
  7936. ;;
  7937. ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
  7938. ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
  7939. ;; error messages.
  7940. (let ((process-connection-type nil))
  7941. (start-process-shell-command cmd nil cmd))
  7942. (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
  7943. ((or (stringp cmd)
  7944. (eq cmd 'emacs))
  7945. (funcall (cdr (assq 'file org-link-frame-setup)) file)
  7946. (widen)
  7947. (cond (line (org-goto-line line)
  7948. (when (derived-mode-p 'org-mode) (org-reveal)))
  7949. (search (condition-case err
  7950. (org-link-search search)
  7951. ;; Save position before error-ing out so user
  7952. ;; can easily move back to the original buffer.
  7953. (error (funcall save-position-maybe)
  7954. (error (nth 1 err)))))))
  7955. ((functionp cmd)
  7956. (save-match-data
  7957. (set-match-data link-match-data)
  7958. (condition-case nil
  7959. (funcall cmd file link)
  7960. ;; FIXME: Remove this check when most default installations
  7961. ;; of Emacs have at least Org 9.0.
  7962. ((debug wrong-number-of-arguments wrong-type-argument
  7963. invalid-function)
  7964. (user-error "Please see Org News for version 9.0 about \
  7965. `org-file-apps'--Lisp error: %S" cmd)))))
  7966. ((consp cmd)
  7967. ;; FIXME: Remove this check when most default installations of
  7968. ;; Emacs have at least Org 9.0. Heads-up instead of silently
  7969. ;; fall back to `org-link-frame-setup' for an old usage of
  7970. ;; `org-file-apps' with sexp instead of a function for `cmd'.
  7971. (user-error "Please see Org News for version 9.0 about \
  7972. `org-file-apps'--Error: Deprecated usage of %S" cmd))
  7973. (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
  7974. (funcall save-position-maybe)))
  7975. ;;;###autoload
  7976. (defun org-open-at-point-global ()
  7977. "Follow a link or a time-stamp like Org mode does.
  7978. Also follow links and emails as seen by `thing-at-point'.
  7979. This command can be called in any mode to follow an external
  7980. link or a time-stamp that has Org mode syntax. Its behavior
  7981. is undefined when called on internal links like fuzzy links.
  7982. Raise a user error when there is nothing to follow."
  7983. (interactive)
  7984. (let ((tap-url (thing-at-point 'url))
  7985. (tap-email (thing-at-point 'email)))
  7986. (cond ((org-in-regexp org-link-any-re)
  7987. (org-link-open-from-string (match-string-no-properties 0)))
  7988. ((or (org-in-regexp org-ts-regexp-both nil t)
  7989. (org-in-regexp org-tsr-regexp-both nil t))
  7990. (org-follow-timestamp-link))
  7991. (tap-url (org-link-open-from-string tap-url))
  7992. (tap-email (org-link-open-from-string
  7993. (concat "mailto:" tap-email)))
  7994. (t (user-error "No link found")))))
  7995. (defvar org-open-at-point-functions nil
  7996. "Hook that is run when following a link at point.
  7997. Functions in this hook must return t if they identify and follow
  7998. a link at point. If they don't find anything interesting at point,
  7999. they must return nil.")
  8000. (defun org-open-at-point (&optional arg)
  8001. "Open link, timestamp, footnote or tags at point.
  8002. When point is on a link, follow it. Normally, files will be
  8003. opened by an appropriate application. If the optional prefix
  8004. argument ARG is non-nil, Emacs will visit the file. With
  8005. a double prefix argument, try to open outside of Emacs, in the
  8006. application the system uses for this file type.
  8007. When point is on a timestamp, open the agenda at the day
  8008. specified.
  8009. When point is a footnote definition, move to the first reference
  8010. found. If it is on a reference, move to the associated
  8011. definition.
  8012. When point is on a headline, display a list of every link in the
  8013. entry, so it is possible to pick one, or all, of them. If point
  8014. is on a tag, call `org-tags-view' instead.
  8015. On top of syntactically correct links, this function also tries
  8016. to open links and time-stamps in comments, node properties, and
  8017. keywords if point is on something looking like a timestamp or
  8018. a link."
  8019. (interactive "P")
  8020. (org-load-modules-maybe)
  8021. (setq org-window-config-before-follow-link (current-window-configuration))
  8022. (org-remove-occur-highlights nil nil t)
  8023. (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
  8024. (let* ((context
  8025. ;; Only consider supported types, even if they are not the
  8026. ;; closest one.
  8027. (org-element-lineage
  8028. (org-element-context)
  8029. '(citation citation-reference clock comment comment-block
  8030. footnote-definition footnote-reference headline
  8031. inline-src-block inlinetask keyword link node-property
  8032. planning src-block timestamp)
  8033. t))
  8034. (type (org-element-type context))
  8035. (value (org-element-property :value context)))
  8036. (cond
  8037. ((not type) (user-error "No link found"))
  8038. ;; No valid link at point. For convenience, look if something
  8039. ;; looks like a link under point in some specific places.
  8040. ((memq type '(comment comment-block node-property keyword))
  8041. (call-interactively #'org-open-at-point-global))
  8042. ;; On a headline or an inlinetask, but not on a timestamp,
  8043. ;; a link, a footnote reference or a citation.
  8044. ((memq type '(headline inlinetask))
  8045. (org-match-line org-complex-heading-regexp)
  8046. (let ((tags-beg (match-beginning 5))
  8047. (tags-end (match-end 5)))
  8048. (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
  8049. ;; On tags.
  8050. (org-tags-view
  8051. arg
  8052. (save-excursion
  8053. (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
  8054. (end-tag (search-forward ":" tags-end nil 2)))
  8055. (buffer-substring (1+ beg-tag) (1- end-tag)))))
  8056. ;; Not on tags.
  8057. (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
  8058. (`(nil . ,_)
  8059. (require 'org-attach)
  8060. (when (org-attach-dir)
  8061. (message "Opening attachment")
  8062. (if (equal arg '(4))
  8063. (org-attach-reveal-in-emacs)
  8064. (org-attach-reveal))))
  8065. (`(,links . ,links-end)
  8066. (dolist (link (if (stringp links) (list links) links))
  8067. (search-forward link nil links-end)
  8068. (goto-char (match-beginning 0))
  8069. (org-open-at-point arg)))))))
  8070. ;; On a footnote reference or at definition's label.
  8071. ((or (eq type 'footnote-reference)
  8072. (and (eq type 'footnote-definition)
  8073. (save-excursion
  8074. ;; Do not validate action when point is on the
  8075. ;; spaces right after the footnote label, in order
  8076. ;; to be on par with behavior on links.
  8077. (skip-chars-forward " \t")
  8078. (let ((begin
  8079. (org-element-property :contents-begin context)))
  8080. (if begin (< (point) begin)
  8081. (= (org-element-property :post-affiliated context)
  8082. (line-beginning-position)))))))
  8083. (org-footnote-action))
  8084. ;; On a planning line. Check if we are really on a timestamp.
  8085. ((and (eq type 'planning)
  8086. (org-in-regexp org-ts-regexp-both nil t))
  8087. (org-follow-timestamp-link))
  8088. ;; On a clock line, make sure point is on the timestamp
  8089. ;; before opening it.
  8090. ((and (eq type 'clock)
  8091. value
  8092. (>= (point) (org-element-property :begin value))
  8093. (<= (point) (org-element-property :end value)))
  8094. (org-follow-timestamp-link))
  8095. ((eq type 'src-block) (org-babel-open-src-block-result))
  8096. ;; Do nothing on white spaces after an object.
  8097. ((>= (point)
  8098. (save-excursion
  8099. (goto-char (org-element-property :end context))
  8100. (skip-chars-backward " \t")
  8101. (point)))
  8102. (user-error "No link found"))
  8103. ((eq type 'inline-src-block) (org-babel-open-src-block-result))
  8104. ((eq type 'timestamp) (org-follow-timestamp-link))
  8105. ((eq type 'link) (org-link-open context arg))
  8106. ((memq type '(citation citation-reference)) (org-cite-follow context arg))
  8107. (t (user-error "No link found")))))
  8108. (run-hook-with-args 'org-follow-link-hook))
  8109. ;;;###autoload
  8110. (defun org-offer-links-in-entry (buffer marker &optional nth zero)
  8111. "Offer links in the current entry and return the selected link.
  8112. If there is only one link, return it.
  8113. If NTH is an integer, return the NTH link found.
  8114. If ZERO is a string, check also this string for a link, and if
  8115. there is one, return it."
  8116. (with-current-buffer buffer
  8117. (org-with-wide-buffer
  8118. (goto-char marker)
  8119. (let ((cnt ?0)
  8120. have-zero end links link c)
  8121. (when (and (stringp zero) (string-match org-link-bracket-re zero))
  8122. (push (match-string 0 zero) links)
  8123. (setq cnt (1- cnt) have-zero t))
  8124. (save-excursion
  8125. (org-back-to-heading t)
  8126. (setq end (save-excursion (outline-next-heading) (point)))
  8127. (while (re-search-forward org-link-any-re end t)
  8128. (push (match-string 0) links))
  8129. (setq links (org-uniquify (reverse links))))
  8130. (cond
  8131. ((null links)
  8132. (message "No links"))
  8133. ((equal (length links) 1)
  8134. (setq link (car links)))
  8135. ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
  8136. (setq link (nth (if have-zero nth (1- nth)) links)))
  8137. (t ; we have to select a link
  8138. (save-excursion
  8139. (save-window-excursion
  8140. (delete-other-windows)
  8141. (with-output-to-temp-buffer "*Select Link*"
  8142. (dolist (l links)
  8143. (cond
  8144. ((not (string-match org-link-bracket-re l))
  8145. (princ (format "[%c] %s\n" (cl-incf cnt)
  8146. (org-unbracket-string "<" ">" l))))
  8147. ((match-end 2)
  8148. (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
  8149. (match-string 2 l) (match-string 1 l))))
  8150. (t (princ (format "[%c] %s\n" (cl-incf cnt)
  8151. (match-string 1 l)))))))
  8152. (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
  8153. (message "Select link to open, RET to open all:")
  8154. (setq c (read-char-exclusive))
  8155. (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
  8156. (when (equal c ?q) (user-error "Abort"))
  8157. (if (equal c ?\C-m)
  8158. (setq link links)
  8159. (setq nth (- c ?0))
  8160. (when have-zero (setq nth (1+ nth)))
  8161. (unless (and (integerp nth) (>= (length links) nth))
  8162. (user-error "Invalid link selection"))
  8163. (setq link (nth (1- nth) links)))))
  8164. (cons link end)))))
  8165. ;;; File search
  8166. (defun org-do-occur (regexp &optional cleanup)
  8167. "Call the Emacs command `occur'.
  8168. If CLEANUP is non-nil, remove the printout of the regular expression
  8169. in the *Occur* buffer. This is useful if the regex is long and not useful
  8170. to read."
  8171. (occur regexp)
  8172. (when cleanup
  8173. (let ((cwin (selected-window)) win beg end)
  8174. (when (setq win (get-buffer-window "*Occur*"))
  8175. (select-window win))
  8176. (goto-char (point-min))
  8177. (when (re-search-forward "match[a-z]+" nil t)
  8178. (setq beg (match-end 0))
  8179. (when (re-search-forward "^[ \t]*[0-9]+" nil t)
  8180. (setq end (1- (match-beginning 0)))))
  8181. (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
  8182. (goto-char (point-min))
  8183. (select-window cwin))))
  8184. ;;; The Mark Ring
  8185. (defvar org-mark-ring nil
  8186. "Mark ring for positions before jumps in Org mode.")
  8187. (defvar org-mark-ring-last-goto nil
  8188. "Last position in the mark ring used to go back.")
  8189. ;; Fill and close the ring
  8190. (setq org-mark-ring nil)
  8191. (setq org-mark-ring-last-goto nil) ;in case file is reloaded
  8192. (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
  8193. (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
  8194. org-mark-ring)
  8195. (defun org-mark-ring-push (&optional pos buffer)
  8196. "Put the current position into the mark ring and rotate it.
  8197. Also push position into the Emacs mark ring. If optional
  8198. argument POS and BUFFER are not nil, mark this location instead."
  8199. (interactive)
  8200. (let ((pos (or pos (point)))
  8201. (buffer (or buffer (current-buffer))))
  8202. (with-current-buffer buffer
  8203. (org-with-point-at pos (push-mark nil t)))
  8204. (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
  8205. (move-marker (car org-mark-ring) pos buffer))
  8206. (message
  8207. (substitute-command-keys
  8208. "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
  8209. (defun org-mark-ring-goto (&optional n)
  8210. "Jump to the previous position in the mark ring.
  8211. With prefix arg N, jump back that many stored positions. When
  8212. called several times in succession, walk through the entire ring.
  8213. Org mode commands jumping to a different position in the current file,
  8214. or to another Org file, automatically push the old position onto the ring."
  8215. (interactive "p")
  8216. (let (p m)
  8217. (if (eq last-command this-command)
  8218. (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
  8219. (setq p org-mark-ring))
  8220. (setq org-mark-ring-last-goto p)
  8221. (setq m (car p))
  8222. (pop-to-buffer-same-window (marker-buffer m))
  8223. (goto-char m)
  8224. (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
  8225. ;;; Following specific links
  8226. (defvar org-agenda-buffer-tmp-name)
  8227. (defvar org-agenda-start-on-weekday)
  8228. (defvar org-agenda-buffer-name)
  8229. (defun org-follow-timestamp-link ()
  8230. "Open an agenda view for the time-stamp date/range at point."
  8231. ;; Avoid changing the global value.
  8232. (let ((org-agenda-buffer-name org-agenda-buffer-name))
  8233. (cond
  8234. ((org-at-date-range-p t)
  8235. (let ((org-agenda-start-on-weekday)
  8236. (t1 (match-string 1))
  8237. (t2 (match-string 2)) tt1 tt2)
  8238. (setq tt1 (time-to-days (org-time-string-to-time t1))
  8239. tt2 (time-to-days (org-time-string-to-time t2)))
  8240. (let ((org-agenda-buffer-tmp-name
  8241. (format "*Org Agenda(a:%s)"
  8242. (concat (substring t1 0 10) "--" (substring t2 0 10)))))
  8243. (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
  8244. ((org-at-timestamp-p 'lax)
  8245. (let ((org-agenda-buffer-tmp-name
  8246. (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
  8247. (org-agenda-list nil (time-to-days (org-time-string-to-time
  8248. (substring (match-string 1) 0 10)))
  8249. 1)))
  8250. (t (error "This should not happen")))))
  8251. ;;; Following file links
  8252. (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
  8253. (declare-function mailcap-extension-to-mime "mailcap" (extn))
  8254. (declare-function mailcap-mime-info
  8255. "mailcap" (string &optional request no-decode))
  8256. (defvar org-wait nil)
  8257. ;;;; Refiling
  8258. (defun org-get-org-file ()
  8259. "Read a filename, with default directory `org-directory'."
  8260. (let ((default (or org-default-notes-file remember-data-file)))
  8261. (read-file-name (format "File name [%s]: " default)
  8262. (file-name-as-directory org-directory)
  8263. default)))
  8264. (defun org-notes-order-reversed-p ()
  8265. "Check if the current file should receive notes in reversed order."
  8266. (cond
  8267. ((not org-reverse-note-order) nil)
  8268. ((eq t org-reverse-note-order) t)
  8269. ((not (listp org-reverse-note-order)) nil)
  8270. (t (catch 'exit
  8271. (dolist (entry org-reverse-note-order)
  8272. (when (string-match (car entry) buffer-file-name)
  8273. (throw 'exit (cdr entry))))))))
  8274. (defvar org-agenda-new-buffers nil
  8275. "Buffers created to visit agenda files.")
  8276. (declare-function org-string-nw-p "org-macs" (s))
  8277. ;;;; Dynamic blocks
  8278. (defun org-find-dblock (name)
  8279. "Find the first dynamic block with name NAME in the buffer.
  8280. If not found, stay at current position and return nil."
  8281. (let ((case-fold-search t) pos)
  8282. (save-excursion
  8283. (goto-char (point-min))
  8284. (setq pos (and (re-search-forward
  8285. (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
  8286. (match-beginning 0))))
  8287. (when pos (goto-char pos))
  8288. pos))
  8289. (defun org-create-dblock (plist)
  8290. "Create a dynamic block section, with parameters taken from PLIST.
  8291. PLIST must contain a :name entry which is used as the name of the block."
  8292. (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
  8293. (end-of-line 1)
  8294. (newline))
  8295. (let ((col (current-column))
  8296. (name (plist-get plist :name)))
  8297. (insert "#+BEGIN: " name)
  8298. (while plist
  8299. (if (eq (car plist) :name)
  8300. (setq plist (cddr plist))
  8301. (insert " " (prin1-to-string (pop plist)))))
  8302. (insert "\n\n" (make-string col ?\ ) "#+END:\n")
  8303. (beginning-of-line -2)))
  8304. (defun org-prepare-dblock ()
  8305. "Prepare dynamic block for refresh.
  8306. This empties the block, puts the cursor at the insert position and returns
  8307. the property list including an extra property :name with the block name."
  8308. (unless (looking-at org-dblock-start-re)
  8309. (user-error "Not at a dynamic block"))
  8310. (let* ((begdel (1+ (match-end 0)))
  8311. (name (org-no-properties (match-string 1)))
  8312. (params (append (list :name name)
  8313. (read (concat "(" (match-string 3) ")")))))
  8314. (save-excursion
  8315. (beginning-of-line 1)
  8316. (skip-chars-forward " \t")
  8317. (setq params (plist-put params :indentation-column (current-column))))
  8318. (unless (re-search-forward org-dblock-end-re nil t)
  8319. (error "Dynamic block not terminated"))
  8320. (setq params
  8321. (append params
  8322. (list :content (buffer-substring
  8323. begdel (match-beginning 0)))))
  8324. (delete-region begdel (match-beginning 0))
  8325. (goto-char begdel)
  8326. (open-line 1)
  8327. params))
  8328. (defun org-map-dblocks (&optional command)
  8329. "Apply COMMAND to all dynamic blocks in the current buffer.
  8330. If COMMAND is not given, use `org-update-dblock'."
  8331. (let ((cmd (or command 'org-update-dblock)))
  8332. (save-excursion
  8333. (goto-char (point-min))
  8334. (while (re-search-forward org-dblock-start-re nil t)
  8335. (goto-char (match-beginning 0))
  8336. (save-excursion
  8337. (condition-case nil
  8338. (funcall cmd)
  8339. (error (message "Error during update of dynamic block"))))
  8340. (unless (re-search-forward org-dblock-end-re nil t)
  8341. (error "Dynamic block not terminated"))))))
  8342. (defvar org-dynamic-block-alist nil
  8343. "Alist defining all the Org dynamic blocks.
  8344. The key is the dynamic block type name, as a string. The value
  8345. is the function used to insert the dynamic block.
  8346. Use `org-dynamic-block-define' to populate it.")
  8347. (defun org-dynamic-block-function (type)
  8348. "Return function associated to a given dynamic block type.
  8349. TYPE is the dynamic block type, as a string."
  8350. (cdr (assoc type org-dynamic-block-alist)))
  8351. (defun org-dynamic-block-types ()
  8352. "List all defined dynamic block types."
  8353. (mapcar #'car org-dynamic-block-alist))
  8354. (defun org-dynamic-block-define (type func)
  8355. "Define dynamic block TYPE with FUNC.
  8356. TYPE is a string. FUNC is the function creating the dynamic
  8357. block of such type."
  8358. (pcase (assoc type org-dynamic-block-alist)
  8359. (`nil (push (cons type func) org-dynamic-block-alist))
  8360. (def (setcdr def func))))
  8361. (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
  8362. "Insert a dynamic block of type TYPE.
  8363. When used interactively, select the dynamic block types among
  8364. defined types, per `org-dynamic-block-define'. If INTERACTIVE-P
  8365. is non-nil, call the dynamic block function interactively."
  8366. (interactive (list (completing-read "Dynamic block: "
  8367. (org-dynamic-block-types))
  8368. t))
  8369. (pcase (org-dynamic-block-function type)
  8370. (`nil (error "No such dynamic block: %S" type))
  8371. ((and f (pred functionp))
  8372. (if interactive-p (call-interactively f) (funcall f)))
  8373. (_ (error "Invalid function for dynamic block %S" type))))
  8374. (defun org-dblock-update (&optional arg)
  8375. "User command for updating dynamic blocks.
  8376. Update the dynamic block at point. With prefix ARG, update all dynamic
  8377. blocks in the buffer."
  8378. (interactive "P")
  8379. (if arg
  8380. (org-update-all-dblocks)
  8381. (or (looking-at org-dblock-start-re)
  8382. (org-beginning-of-dblock))
  8383. (org-update-dblock)))
  8384. (defun org-update-dblock ()
  8385. "Update the dynamic block at point.
  8386. This means to empty the block, parse for parameters and then call
  8387. the correct writing function."
  8388. (interactive)
  8389. (save-excursion
  8390. (let* ((win (selected-window))
  8391. (pos (point))
  8392. (line (org-current-line))
  8393. (params (org-prepare-dblock))
  8394. (name (plist-get params :name))
  8395. (indent (plist-get params :indentation-column))
  8396. (cmd (intern (concat "org-dblock-write:" name))))
  8397. (message "Updating dynamic block `%s' at line %d..." name line)
  8398. (funcall cmd params)
  8399. (message "Updating dynamic block `%s' at line %d...done" name line)
  8400. (goto-char pos)
  8401. (when (and indent (> indent 0))
  8402. (setq indent (make-string indent ?\ ))
  8403. (save-excursion
  8404. (select-window win)
  8405. (org-beginning-of-dblock)
  8406. (forward-line 1)
  8407. (while (not (looking-at org-dblock-end-re))
  8408. (insert indent)
  8409. (beginning-of-line 2))
  8410. (when (looking-at org-dblock-end-re)
  8411. (and (looking-at "[ \t]+")
  8412. (replace-match ""))
  8413. (insert indent)))))))
  8414. (defun org-beginning-of-dblock ()
  8415. "Find the beginning of the dynamic block at point.
  8416. Error if there is no such block at point."
  8417. (let ((pos (point))
  8418. beg)
  8419. (end-of-line 1)
  8420. (if (and (re-search-backward org-dblock-start-re nil t)
  8421. (setq beg (match-beginning 0))
  8422. (re-search-forward org-dblock-end-re nil t)
  8423. (> (match-end 0) pos))
  8424. (goto-char beg)
  8425. (goto-char pos)
  8426. (error "Not in a dynamic block"))))
  8427. (defun org-update-all-dblocks ()
  8428. "Update all dynamic blocks in the buffer.
  8429. This function can be used in a hook."
  8430. (interactive)
  8431. (when (derived-mode-p 'org-mode)
  8432. (org-map-dblocks 'org-update-dblock)))
  8433. ;;;; Completion
  8434. (declare-function org-export-backend-options "ox" (cl-x) t)
  8435. (defun org-get-export-keywords ()
  8436. "Return a list of all currently understood export keywords.
  8437. Export keywords include options, block names, attributes and
  8438. keywords relative to each registered export back-end."
  8439. (let (keywords)
  8440. (dolist (backend
  8441. (bound-and-true-p org-export-registered-backends)
  8442. (delq nil keywords))
  8443. ;; Back-end name (for keywords, like #+LATEX:)
  8444. (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
  8445. (dolist (option-entry (org-export-backend-options backend))
  8446. ;; Back-end options.
  8447. (push (nth 1 option-entry) keywords)))))
  8448. (defconst org-options-keywords
  8449. '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
  8450. "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
  8451. "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
  8452. "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
  8453. "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
  8454. (defcustom org-structure-template-alist
  8455. '(("a" . "export ascii")
  8456. ("c" . "center")
  8457. ("C" . "comment")
  8458. ("e" . "example")
  8459. ("E" . "export")
  8460. ("h" . "export html")
  8461. ("l" . "export latex")
  8462. ("q" . "quote")
  8463. ("s" . "src")
  8464. ("v" . "verse"))
  8465. "An alist of keys and block types.
  8466. `org-insert-structure-template' will display a menu with this
  8467. list of templates to choose from. The block type is inserted,
  8468. with \"#+BEGIN_\" and \"#+END_\" added automatically.
  8469. The menu keys are defined by the car of each entry in this alist.
  8470. If two entries have the keys \"a\" and \"aa\" respectively, the
  8471. former will be inserted by typing \"a TAB/RET/SPC\" and the
  8472. latter will be inserted by typing \"aa\". If an entry with the
  8473. key \"aab\" is later added, it can be inserted by typing \"ab\".
  8474. If loaded, Org Tempo also uses `org-structure-template-alist'. A
  8475. block can be inserted by pressing TAB after the string \"<KEY\"."
  8476. :group 'org-edit-structure
  8477. :type '(repeat
  8478. (cons (string :tag "Key")
  8479. (string :tag "Template")))
  8480. :package-version '(Org . "9.2"))
  8481. (defun org--check-org-structure-template-alist (&optional checklist)
  8482. "Check whether `org-structure-template-alist' is set up correctly.
  8483. In particular, check if the Org 9.2 format is used as opposed to
  8484. previous format."
  8485. (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
  8486. (or (eval checklist)
  8487. org-structure-template-alist))))
  8488. (when elm
  8489. (org-display-warning
  8490. (format "
  8491. Please update the entries of `%s'.
  8492. In Org 9.2 the format was changed from something like
  8493. (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
  8494. to something like
  8495. (\"s\" . \"src\")
  8496. Please refer to the documentation of `org-structure-template-alist'.
  8497. The following entries must be updated:
  8498. %s"
  8499. (or checklist 'org-structure-template-alist)
  8500. (pp-to-string elm))))))
  8501. (defun org--insert-structure-template-mks ()
  8502. "Present `org-structure-template-alist' with `org-mks'.
  8503. Menus are added if keys require more than one keystroke. Tabs
  8504. are added to single key entries when more than one stroke is
  8505. needed. Keys longer than two characters are reduced to two
  8506. characters."
  8507. (org--check-org-structure-template-alist)
  8508. (let* (case-fold-search
  8509. (templates (append org-structure-template-alist
  8510. '(("\t" . "Press TAB, RET or SPC to write block name"))))
  8511. (keys (mapcar #'car templates))
  8512. (start-letters
  8513. (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
  8514. ;; Sort each element of `org-structure-template-alist' into
  8515. ;; sublists according to the first letter.
  8516. (superlist
  8517. (mapcar (lambda (letter)
  8518. (list letter
  8519. (cl-remove-if-not
  8520. (apply-partially #'string-match-p (concat "^" letter))
  8521. templates :key #'car)))
  8522. start-letters)))
  8523. (org-mks
  8524. (apply #'append
  8525. ;; Make an `org-mks' table. If only one element is
  8526. ;; present in a sublist, make it part of the top-menu,
  8527. ;; otherwise make a submenu according to the starting
  8528. ;; letter and populate it.
  8529. (mapcar (lambda (sublist)
  8530. (if (eq 1 (length (cadr sublist)))
  8531. (mapcar (lambda (elm)
  8532. (list (substring (car elm) 0 1)
  8533. (cdr elm) ""))
  8534. (cadr sublist))
  8535. ;; Create submenu.
  8536. (let* ((topkey (car sublist))
  8537. (elms (cadr sublist))
  8538. (keys (mapcar #'car elms))
  8539. (long (> (length elms) 3)))
  8540. (append
  8541. (list
  8542. ;; Make a description of the submenu.
  8543. (list topkey
  8544. (concat
  8545. (mapconcat #'cdr
  8546. (cl-subseq elms 0 (if long 3 (length elms)))
  8547. ", ")
  8548. (when long ", ..."))))
  8549. ;; List of entries in submenu.
  8550. (cl-mapcar #'list
  8551. (org--insert-structure-template-unique-keys keys)
  8552. (mapcar #'cdr elms)
  8553. (make-list (length elms) ""))))))
  8554. superlist))
  8555. "Select a key\n============"
  8556. "Key: ")))
  8557. (defun org--insert-structure-template-unique-keys (keys)
  8558. "Make a list of unique, two characters long elements from KEYS.
  8559. Elements of length one have a tab appended. Elements of length
  8560. two are kept as is. Longer elements are truncated to length two.
  8561. If an element cannot be made unique, an error is raised."
  8562. (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
  8563. menu-keys)
  8564. (dolist (key ordered-keys)
  8565. (let ((potential-key
  8566. (cl-case (length key)
  8567. (1 (concat key "\t"))
  8568. (2 key)
  8569. (otherwise
  8570. (cl-find-if-not (lambda (k) (assoc k menu-keys))
  8571. (mapcar (apply-partially #'concat (substring key 0 1))
  8572. (split-string (substring key 1) "" t)))))))
  8573. (if (or (not potential-key) (assoc potential-key menu-keys))
  8574. (user-error "Could not make unique key for `%s'" key)
  8575. (push (cons potential-key key) menu-keys))))
  8576. (mapcar #'car
  8577. (cl-sort menu-keys #'<
  8578. :key (lambda (elm) (cl-position (cdr elm) keys))))))
  8579. (defun org-insert-structure-template (type)
  8580. "Insert a block structure of the type #+begin_foo/#+end_foo.
  8581. Select a block from `org-structure-template-alist' then type
  8582. either RET, TAB or SPC to write the block type. With an active
  8583. region, wrap the region in the block. Otherwise, insert an empty
  8584. block."
  8585. (interactive
  8586. (list (pcase (org--insert-structure-template-mks)
  8587. (`("\t" . ,_) (read-string "Structure type: "))
  8588. (`(,_ ,choice . ,_) choice))))
  8589. (let* ((region? (use-region-p))
  8590. (region-start (and region? (region-beginning)))
  8591. (region-end (and region? (copy-marker (region-end))))
  8592. (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
  8593. (verbatim? (string-match-p
  8594. (concat "\\`" (regexp-opt '("example" "export" "src")))
  8595. type)))
  8596. (when region? (goto-char region-start))
  8597. (let ((column (current-indentation)))
  8598. (if (save-excursion (skip-chars-backward " \t") (bolp))
  8599. (beginning-of-line)
  8600. (insert "\n"))
  8601. (save-excursion
  8602. (indent-to column)
  8603. (insert (format "#+begin_%s%s\n" type (if extended? " " "")))
  8604. (when region?
  8605. (when verbatim? (org-escape-code-in-region (point) region-end))
  8606. (goto-char region-end)
  8607. ;; Ignore empty lines at the end of the region.
  8608. (skip-chars-backward " \r\t\n")
  8609. (end-of-line))
  8610. (unless (bolp) (insert "\n"))
  8611. (indent-to column)
  8612. (insert (format "#+end_%s" (car (split-string type))))
  8613. (if (looking-at "[ \t]*$") (replace-match "")
  8614. (insert "\n"))
  8615. (when (and (eobp) (not (bolp))) (insert "\n")))
  8616. (if extended? (end-of-line)
  8617. (forward-line)
  8618. (skip-chars-forward " \t")))))
  8619. ;;;; TODO, DEADLINE, Comments
  8620. (defun org-toggle-comment ()
  8621. "Change the COMMENT state of an entry."
  8622. (interactive)
  8623. (save-excursion
  8624. (org-back-to-heading)
  8625. (let ((case-fold-search nil))
  8626. (looking-at org-complex-heading-regexp))
  8627. (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
  8628. (skip-chars-forward " \t")
  8629. (unless (memq (char-before) '(?\s ?\t)) (insert " "))
  8630. (if (org-in-commented-heading-p t)
  8631. (delete-region (point)
  8632. (progn (search-forward " " (line-end-position) 'move)
  8633. (skip-chars-forward " \t")
  8634. (point)))
  8635. (insert org-comment-string)
  8636. (unless (eolp) (insert " ")))))
  8637. (defvar org-last-todo-state-is-todo nil
  8638. "This is non-nil when the last TODO state change led to a TODO state.
  8639. If the last change removed the TODO tag or switched to DONE, then
  8640. this is nil.")
  8641. (defvar org-todo-setup-filter-hook nil
  8642. "Hook for functions that pre-filter todo specs.
  8643. Each function takes a todo spec and returns either nil or the spec
  8644. transformed into canonical form." )
  8645. (defvar org-todo-get-default-hook nil
  8646. "Hook for functions that get a default item for todo.
  8647. Each function takes arguments (NEW-MARK OLD-MARK) and returns either
  8648. nil or a string to be used for the todo mark." )
  8649. (defvar org-agenda-headline-snapshot-before-repeat)
  8650. (defun org-current-effective-time ()
  8651. "Return current time adjusted for `org-extend-today-until' variable."
  8652. (let* ((ct (org-current-time))
  8653. (dct (decode-time ct))
  8654. (ct1
  8655. (cond
  8656. (org-use-last-clock-out-time-as-effective-time
  8657. (or (org-clock-get-last-clock-out-time) ct))
  8658. ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
  8659. (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
  8660. (t ct))))
  8661. ct1))
  8662. (defun org-todo-yesterday (&optional arg)
  8663. "Like `org-todo' but the time of change will be 23:59 of yesterday."
  8664. (interactive "P")
  8665. (if (eq major-mode 'org-agenda-mode)
  8666. (apply 'org-agenda-todo-yesterday arg)
  8667. (let* ((org-use-effective-time t)
  8668. (hour (nth 2 (decode-time (org-current-time))))
  8669. (org-extend-today-until (1+ hour)))
  8670. (org-todo arg))))
  8671. (defvar org-block-entry-blocking ""
  8672. "First entry preventing the TODO state change.")
  8673. (defun org-cancel-repeater ()
  8674. "Cancel a repeater by setting its numeric value to zero."
  8675. (interactive)
  8676. (save-excursion
  8677. (org-back-to-heading t)
  8678. (let ((bound1 (point))
  8679. (bound0 (save-excursion (outline-next-heading) (point))))
  8680. (when (and (re-search-forward
  8681. (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
  8682. org-deadline-time-regexp "\\)\\|\\("
  8683. org-ts-regexp "\\)")
  8684. bound0 t)
  8685. (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
  8686. bound1 t))
  8687. (replace-match "0" t nil nil 1)))))
  8688. (defvar org-state)
  8689. (defvar org-blocked-by-checkboxes)
  8690. (defun org-todo (&optional arg)
  8691. "Change the TODO state of an item.
  8692. The state of an item is given by a keyword at the start of the heading,
  8693. like
  8694. *** TODO Write paper
  8695. *** DONE Call mom
  8696. The different keywords are specified in the variable `org-todo-keywords'.
  8697. By default the available states are \"TODO\" and \"DONE\". So, for this
  8698. example: when the item starts with TODO, it is changed to DONE.
  8699. When it starts with DONE, the DONE is removed. And when neither TODO nor
  8700. DONE are present, add TODO at the beginning of the heading.
  8701. You can set up single-character keys to fast-select the new state. See the
  8702. `org-todo-keywords' and `org-use-fast-todo-selection' for details.
  8703. With `\\[universal-argument]' prefix ARG, force logging the state change \
  8704. and take a
  8705. logging note.
  8706. With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
  8707. next set of TODO \
  8708. keywords (nextset).
  8709. Another way to achieve this is `S-C-<right>'.
  8710. With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
  8711. prefix, circumvent any state blocking.
  8712. With numeric prefix arg, switch to the Nth state.
  8713. With a numeric prefix arg of 0, inhibit note taking for the change.
  8714. With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
  8715. When called through ELisp, arg is also interpreted in the following way:
  8716. `none' -> empty state
  8717. \"\" -> switch to empty state
  8718. `done' -> switch to DONE
  8719. `nextset' -> switch to the next set of keywords
  8720. `previousset' -> switch to the previous set of keywords
  8721. \"WAITING\" -> switch to the specified keyword, but only if it
  8722. really is a member of `org-todo-keywords'."
  8723. (interactive "P")
  8724. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  8725. (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  8726. 'region-start-level 'region))
  8727. org-loop-over-headlines-in-active-region)
  8728. (org-map-entries
  8729. (lambda () (org-todo arg))
  8730. nil cl
  8731. (when (org-invisible-p) (org-end-of-subtree nil t))))
  8732. (when (equal arg '(16)) (setq arg 'nextset))
  8733. (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
  8734. (let ((org-blocker-hook org-blocker-hook)
  8735. commentp
  8736. case-fold-search)
  8737. (when (equal arg '(64))
  8738. (setq arg nil org-blocker-hook nil))
  8739. (when (and org-blocker-hook
  8740. (or org-inhibit-blocking
  8741. (org-entry-get nil "NOBLOCKING")))
  8742. (setq org-blocker-hook nil))
  8743. (save-excursion
  8744. (catch 'exit
  8745. (org-back-to-heading t)
  8746. (when (org-in-commented-heading-p t)
  8747. (org-toggle-comment)
  8748. (setq commentp t))
  8749. (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
  8750. (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
  8751. (looking-at "\\(?: *\\|[ \t]*$\\)"))
  8752. (let* ((match-data (match-data))
  8753. (startpos (copy-marker (line-beginning-position)))
  8754. (force-log (and (equal arg '(4)) (prog1 t (setq arg nil))))
  8755. (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
  8756. (org-log-done org-log-done)
  8757. (org-log-repeat org-log-repeat)
  8758. (org-todo-log-states org-todo-log-states)
  8759. (org-inhibit-logging
  8760. (if (equal arg 0)
  8761. (progn (setq arg nil) 'note) org-inhibit-logging))
  8762. (this (match-string 1))
  8763. (hl-pos (match-beginning 0))
  8764. (head (org-get-todo-sequence-head this))
  8765. (ass (assoc head org-todo-kwd-alist))
  8766. (interpret (nth 1 ass))
  8767. (done-word (nth 3 ass))
  8768. (final-done-word (nth 4 ass))
  8769. (org-last-state (or this ""))
  8770. (completion-ignore-case t)
  8771. (member (member this org-todo-keywords-1))
  8772. (tail (cdr member))
  8773. (org-state (cond
  8774. ((eq arg 'right)
  8775. ;; Next state
  8776. (if this
  8777. (if tail (car tail) nil)
  8778. (car org-todo-keywords-1)))
  8779. ((eq arg 'left)
  8780. ;; Previous state
  8781. (unless (equal member org-todo-keywords-1)
  8782. (if this
  8783. (nth (- (length org-todo-keywords-1)
  8784. (length tail) 2)
  8785. org-todo-keywords-1)
  8786. (org-last org-todo-keywords-1))))
  8787. (arg
  8788. ;; User or caller requests a specific state.
  8789. (cond
  8790. ((equal arg "") nil)
  8791. ((eq arg 'none) nil)
  8792. ((eq arg 'done) (or done-word (car org-done-keywords)))
  8793. ((eq arg 'nextset)
  8794. (or (car (cdr (member head org-todo-heads)))
  8795. (car org-todo-heads)))
  8796. ((eq arg 'previousset)
  8797. (let ((org-todo-heads (reverse org-todo-heads)))
  8798. (or (car (cdr (member head org-todo-heads)))
  8799. (car org-todo-heads))))
  8800. ((car (member arg org-todo-keywords-1)))
  8801. ((stringp arg)
  8802. (user-error "State `%s' not valid in this file" arg))
  8803. ((nth (1- (prefix-numeric-value arg))
  8804. org-todo-keywords-1))))
  8805. ((and org-todo-key-trigger org-use-fast-todo-selection)
  8806. ;; Use fast selection.
  8807. (org-fast-todo-selection this))
  8808. ((null member) (or head (car org-todo-keywords-1)))
  8809. ((equal this final-done-word) nil) ;-> make empty
  8810. ((null tail) nil) ;-> first entry
  8811. ((memq interpret '(type priority))
  8812. (if (eq this-command last-command)
  8813. (car tail)
  8814. (if (> (length tail) 0)
  8815. (or done-word (car org-done-keywords))
  8816. nil)))
  8817. (t
  8818. (car tail))))
  8819. (org-state (or
  8820. (run-hook-with-args-until-success
  8821. 'org-todo-get-default-hook org-state org-last-state)
  8822. org-state))
  8823. (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
  8824. (change-plist (list :type 'todo-state-change :from this :to org-state
  8825. :position startpos))
  8826. dolog now-done-p)
  8827. (when org-blocker-hook
  8828. (let (org-blocked-by-checkboxes block-reason)
  8829. (setq org-last-todo-state-is-todo
  8830. (not (member this org-done-keywords)))
  8831. (unless (save-excursion
  8832. (save-match-data
  8833. (org-with-wide-buffer
  8834. (run-hook-with-args-until-failure
  8835. 'org-blocker-hook change-plist))))
  8836. (setq block-reason (if org-blocked-by-checkboxes
  8837. "contained checkboxes"
  8838. (format "\"%s\"" org-block-entry-blocking)))
  8839. (if (called-interactively-p 'interactive)
  8840. (user-error "TODO state change from %s to %s blocked (by %s)"
  8841. this org-state block-reason)
  8842. ;; Fail silently.
  8843. (message "TODO state change from %s to %s blocked (by %s)"
  8844. this org-state block-reason)
  8845. (throw 'exit nil)))))
  8846. (store-match-data match-data)
  8847. (replace-match next t t)
  8848. (cond ((and org-state (equal this org-state))
  8849. (message "TODO state was already %s" (org-trim next)))
  8850. ((not (pos-visible-in-window-p hl-pos))
  8851. (message "TODO state changed to %s" (org-trim next))))
  8852. (unless head
  8853. (setq head (org-get-todo-sequence-head org-state)
  8854. ass (assoc head org-todo-kwd-alist)
  8855. interpret (nth 1 ass)
  8856. done-word (nth 3 ass)
  8857. final-done-word (nth 4 ass)))
  8858. (when (memq arg '(nextset previousset))
  8859. (message "Keyword-Set %d/%d: %s"
  8860. (- (length org-todo-sets) -1
  8861. (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
  8862. (length org-todo-sets)
  8863. (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
  8864. (setq org-last-todo-state-is-todo
  8865. (not (member org-state org-done-keywords)))
  8866. (setq now-done-p (and (member org-state org-done-keywords)
  8867. (not (member this org-done-keywords))))
  8868. (and logging (org-local-logging logging))
  8869. (when (or (and (or org-todo-log-states org-log-done)
  8870. (not (eq org-inhibit-logging t))
  8871. (not (memq arg '(nextset previousset))))
  8872. force-log)
  8873. ;; We need to look at recording a time and note.
  8874. (setq dolog (or (if force-log 'note)
  8875. (nth 1 (assoc org-state org-todo-log-states))
  8876. (nth 2 (assoc this org-todo-log-states))))
  8877. (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
  8878. (setq dolog 'time))
  8879. (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
  8880. (and org-state
  8881. (member org-state org-not-done-keywords)
  8882. (not (member this org-not-done-keywords))))
  8883. ;; This is now a todo state and was not one before
  8884. ;; If there was a CLOSED time stamp, get rid of it.
  8885. (org-add-planning-info nil nil 'closed))
  8886. (when (and now-done-p org-log-done)
  8887. ;; It is now done, and it was not done before.
  8888. (org-add-planning-info 'closed (org-current-effective-time))
  8889. (when (and (not dolog) (eq 'note org-log-done))
  8890. (org-add-log-setup 'done org-state this 'note)))
  8891. (when (and org-state dolog)
  8892. ;; This is a non-nil state, and we need to log it.
  8893. (org-add-log-setup 'state org-state this dolog)))
  8894. ;; Fixup tag positioning.
  8895. (org-todo-trigger-tag-changes org-state)
  8896. (when org-auto-align-tags (org-align-tags))
  8897. (when org-provide-todo-statistics
  8898. (org-update-parent-todo-statistics))
  8899. (when (bound-and-true-p org-clock-out-when-done)
  8900. (org-clock-out-if-current))
  8901. (run-hooks 'org-after-todo-state-change-hook)
  8902. (when (and arg (not (member org-state org-done-keywords)))
  8903. (setq head (org-get-todo-sequence-head org-state)))
  8904. (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
  8905. ;; Do we need to trigger a repeat?
  8906. (when now-done-p
  8907. (when (boundp 'org-agenda-headline-snapshot-before-repeat)
  8908. ;; This is for the agenda, take a snapshot of the headline.
  8909. (save-match-data
  8910. (setq org-agenda-headline-snapshot-before-repeat
  8911. (org-get-heading))))
  8912. (org-auto-repeat-maybe org-state))
  8913. ;; Fixup cursor location if close to the keyword.
  8914. (when (and (outline-on-heading-p)
  8915. (not (bolp))
  8916. (save-excursion (beginning-of-line 1)
  8917. (looking-at org-todo-line-regexp))
  8918. (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
  8919. (goto-char (or (match-end 2) (match-end 1)))
  8920. (and (looking-at " ")
  8921. (not (looking-at " *:"))
  8922. (just-one-space)))
  8923. (when org-trigger-hook
  8924. (save-excursion
  8925. (run-hook-with-args 'org-trigger-hook change-plist)))
  8926. (when commentp (org-toggle-comment))))))))
  8927. (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
  8928. "Block turning an entry into a TODO, using the hierarchy.
  8929. This checks whether the current task should be blocked from state
  8930. changes. Such blocking occurs when:
  8931. 1. The task has children which are not all in a completed state.
  8932. 2. A task has a parent with the property :ORDERED:, and there
  8933. are siblings prior to the current task with incomplete
  8934. status.
  8935. 3. The parent of the task is blocked because it has siblings that should
  8936. be done first, or is child of a block grandparent TODO entry."
  8937. (if (not org-enforce-todo-dependencies)
  8938. t ; if locally turned off don't block
  8939. (catch 'dont-block
  8940. ;; If this is not a todo state change, or if this entry is already DONE,
  8941. ;; do not block
  8942. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  8943. (member (plist-get change-plist :from)
  8944. (cons 'done org-done-keywords))
  8945. (member (plist-get change-plist :to)
  8946. (cons 'todo org-not-done-keywords))
  8947. (not (plist-get change-plist :to)))
  8948. (throw 'dont-block t))
  8949. ;; If this task has children, and any are undone, it's blocked
  8950. (save-excursion
  8951. (org-back-to-heading t)
  8952. (let ((this-level (funcall outline-level)))
  8953. (outline-next-heading)
  8954. (let ((child-level (funcall outline-level)))
  8955. (while (and (not (eobp))
  8956. (> child-level this-level))
  8957. ;; this todo has children, check whether they are all
  8958. ;; completed
  8959. (when (and (not (org-entry-is-done-p))
  8960. (org-entry-is-todo-p))
  8961. (setq org-block-entry-blocking (org-get-heading))
  8962. (throw 'dont-block nil))
  8963. (outline-next-heading)
  8964. (setq child-level (funcall outline-level))))))
  8965. ;; Otherwise, if the task's parent has the :ORDERED: property, and
  8966. ;; any previous siblings are undone, it's blocked
  8967. (save-excursion
  8968. (org-back-to-heading t)
  8969. (let* ((pos (point))
  8970. (parent-pos (and (org-up-heading-safe) (point)))
  8971. (case-fold-search nil))
  8972. (unless parent-pos (throw 'dont-block t)) ; no parent
  8973. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8974. (forward-line 1)
  8975. (re-search-forward org-not-done-heading-regexp pos t))
  8976. (setq org-block-entry-blocking (match-string 0))
  8977. (throw 'dont-block nil)) ; block, there is an older sibling not done.
  8978. ;; Search further up the hierarchy, to see if an ancestor is blocked
  8979. (while t
  8980. (goto-char parent-pos)
  8981. (unless (looking-at org-not-done-heading-regexp)
  8982. (throw 'dont-block t)) ; do not block, parent is not a TODO
  8983. (setq pos (point))
  8984. (setq parent-pos (and (org-up-heading-safe) (point)))
  8985. (unless parent-pos (throw 'dont-block t)) ; no parent
  8986. (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
  8987. (forward-line 1)
  8988. (re-search-forward org-not-done-heading-regexp pos t)
  8989. (setq org-block-entry-blocking (org-get-heading)))
  8990. (throw 'dont-block nil)))))))) ; block, older sibling not done.
  8991. (defcustom org-track-ordered-property-with-tag nil
  8992. "Should the ORDERED property also be shown as a tag?
  8993. The ORDERED property decides if an entry should require subtasks to be
  8994. completed in sequence. Since a property is not very visible, setting
  8995. this option means that toggling the ORDERED property with the command
  8996. `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
  8997. not relevant for the behavior, but it makes things more visible.
  8998. Note that toggling the tag with tags commands will not change the property
  8999. and therefore not influence behavior!
  9000. This can be t, meaning the tag ORDERED should be used. It can also be a
  9001. string to select a different tag for this task."
  9002. :group 'org-todo
  9003. :type '(choice
  9004. (const :tag "No tracking" nil)
  9005. (const :tag "Track with ORDERED tag" t)
  9006. (string :tag "Use other tag")))
  9007. (defun org-toggle-ordered-property ()
  9008. "Toggle the ORDERED property of the current entry.
  9009. For better visibility, you can track the value of this property with a tag.
  9010. See variable `org-track-ordered-property-with-tag'."
  9011. (interactive)
  9012. (let* ((t1 org-track-ordered-property-with-tag)
  9013. (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
  9014. (save-excursion
  9015. (org-back-to-heading)
  9016. (if (org-entry-get nil "ORDERED")
  9017. (progn
  9018. (org-delete-property "ORDERED")
  9019. (and tag (org-toggle-tag tag 'off))
  9020. (message "Subtasks can be completed in arbitrary order"))
  9021. (org-entry-put nil "ORDERED" "t")
  9022. (and tag (org-toggle-tag tag 'on))
  9023. (message "Subtasks must be completed in sequence")))))
  9024. (defun org-block-todo-from-checkboxes (change-plist)
  9025. "Block turning an entry into a TODO, using checkboxes.
  9026. This checks whether the current task should be blocked from state
  9027. changes because there are unchecked boxes in this entry."
  9028. (if (not org-enforce-todo-checkbox-dependencies)
  9029. t ; if locally turned off don't block
  9030. (catch 'dont-block
  9031. ;; If this is not a todo state change, or if this entry is already DONE,
  9032. ;; do not block
  9033. (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
  9034. (member (plist-get change-plist :from)
  9035. (cons 'done org-done-keywords))
  9036. (member (plist-get change-plist :to)
  9037. (cons 'todo org-not-done-keywords))
  9038. (not (plist-get change-plist :to)))
  9039. (throw 'dont-block t))
  9040. ;; If this task has checkboxes that are not checked, it's blocked
  9041. (save-excursion
  9042. (org-back-to-heading t)
  9043. (let ((beg (point)) end)
  9044. (outline-next-heading)
  9045. (setq end (point))
  9046. (goto-char beg)
  9047. (when (org-list-search-forward
  9048. (concat (org-item-beginning-re)
  9049. "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
  9050. "\\[[- ]\\]")
  9051. end t)
  9052. (when (boundp 'org-blocked-by-checkboxes)
  9053. (setq org-blocked-by-checkboxes t))
  9054. (throw 'dont-block nil))))
  9055. t))) ; do not block
  9056. (defun org-entry-blocked-p ()
  9057. "Non-nil if entry at point is blocked."
  9058. (and (not (org-entry-get nil "NOBLOCKING"))
  9059. (member (org-entry-get nil "TODO") org-not-done-keywords)
  9060. (not (run-hook-with-args-until-failure
  9061. 'org-blocker-hook
  9062. (list :type 'todo-state-change
  9063. :position (point)
  9064. :from 'todo
  9065. :to 'done)))))
  9066. (defun org-update-statistics-cookies (all)
  9067. "Update the statistics cookie, either from TODO or from checkboxes.
  9068. This should be called with the cursor in a line with a statistics
  9069. cookie. When called with a \\[universal-argument] prefix, update
  9070. all statistics cookies in the buffer."
  9071. (interactive "P")
  9072. (if all
  9073. (progn
  9074. (org-update-checkbox-count 'all)
  9075. (org-map-region 'org-update-parent-todo-statistics
  9076. (point-min) (point-max)))
  9077. (if (not (org-at-heading-p))
  9078. (org-update-checkbox-count)
  9079. (let ((pos (point-marker))
  9080. end l1 l2)
  9081. (ignore-errors (org-back-to-heading t))
  9082. (if (not (org-at-heading-p))
  9083. (org-update-checkbox-count)
  9084. (setq l1 (org-outline-level))
  9085. (setq end
  9086. (save-excursion
  9087. (outline-next-heading)
  9088. (when (org-at-heading-p) (setq l2 (org-outline-level)))
  9089. (point)))
  9090. (if (and (save-excursion
  9091. (re-search-forward
  9092. "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
  9093. (not (save-excursion
  9094. (re-search-forward
  9095. ":COOKIE_DATA:.*\\<todo\\>" end t))))
  9096. (org-update-checkbox-count)
  9097. (if (and l2 (> l2 l1))
  9098. (progn
  9099. (goto-char end)
  9100. (org-update-parent-todo-statistics))
  9101. (goto-char pos)
  9102. (beginning-of-line 1)
  9103. (while (re-search-forward
  9104. "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
  9105. (point-at-eol) t)
  9106. (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
  9107. (goto-char pos)
  9108. (move-marker pos nil)))))
  9109. (defvar org-entry-property-inherited-from) ;; defined below
  9110. (defun org-update-parent-todo-statistics ()
  9111. "Update any statistics cookie in the parent of the current headline.
  9112. When `org-hierarchical-todo-statistics' is nil, statistics will cover
  9113. the entire subtree and this will travel up the hierarchy and update
  9114. statistics everywhere."
  9115. (let* ((prop (save-excursion
  9116. (org-up-heading-safe)
  9117. (org-entry-get nil "COOKIE_DATA" 'inherit)))
  9118. (recursive (or (not org-hierarchical-todo-statistics)
  9119. (and prop (string-match "\\<recursive\\>" prop))))
  9120. (lim (or (and prop (marker-position org-entry-property-inherited-from))
  9121. 0))
  9122. (first t)
  9123. (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
  9124. level ltoggle l1 new ndel
  9125. (cnt-all 0) (cnt-done 0) is-percent kwd
  9126. checkbox-beg cookie-present)
  9127. (catch 'exit
  9128. (save-excursion
  9129. (beginning-of-line 1)
  9130. (setq ltoggle (funcall outline-level))
  9131. ;; Three situations are to consider:
  9132. ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
  9133. ;; to the top-level ancestor on the headline;
  9134. ;; 2. If parent has "recursive" property, repeat up to the
  9135. ;; headline setting that property, taking inheritance into
  9136. ;; account;
  9137. ;; 3. Else, move up to direct parent and proceed only once.
  9138. (while (and (setq level (org-up-heading-safe))
  9139. (or recursive first)
  9140. (>= (point) lim))
  9141. (setq first nil cookie-present nil)
  9142. (unless (and level
  9143. (not (string-match
  9144. "\\<checkbox\\>"
  9145. (downcase (or (org-entry-get nil "COOKIE_DATA")
  9146. "")))))
  9147. (throw 'exit nil))
  9148. (while (re-search-forward box-re (point-at-eol) t)
  9149. (setq cnt-all 0 cnt-done 0 cookie-present t)
  9150. (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
  9151. (save-match-data
  9152. (unless (outline-next-heading) (throw 'exit nil))
  9153. (while (and (looking-at org-complex-heading-regexp)
  9154. (> (setq l1 (length (match-string 1))) level))
  9155. (setq kwd (and (or recursive (= l1 ltoggle))
  9156. (match-string 2)))
  9157. (if (or (eq org-provide-todo-statistics 'all-headlines)
  9158. (and (eq org-provide-todo-statistics t)
  9159. (or (member kwd org-done-keywords)))
  9160. (and (listp org-provide-todo-statistics)
  9161. (stringp (car org-provide-todo-statistics))
  9162. (or (member kwd org-provide-todo-statistics)
  9163. (member kwd org-done-keywords)))
  9164. (and (listp org-provide-todo-statistics)
  9165. (listp (car org-provide-todo-statistics))
  9166. (or (member kwd (car org-provide-todo-statistics))
  9167. (and (member kwd org-done-keywords)
  9168. (member kwd (cadr org-provide-todo-statistics))))))
  9169. (setq cnt-all (1+ cnt-all))
  9170. (and (eq org-provide-todo-statistics t)
  9171. kwd
  9172. (setq cnt-all (1+ cnt-all))))
  9173. (when (or (and (member org-provide-todo-statistics '(t all-headlines))
  9174. (member kwd org-done-keywords))
  9175. (and (listp org-provide-todo-statistics)
  9176. (listp (car org-provide-todo-statistics))
  9177. (member kwd org-done-keywords)
  9178. (member kwd (cadr org-provide-todo-statistics)))
  9179. (and (listp org-provide-todo-statistics)
  9180. (stringp (car org-provide-todo-statistics))
  9181. (member kwd org-done-keywords)))
  9182. (setq cnt-done (1+ cnt-done)))
  9183. (outline-next-heading)))
  9184. (setq new
  9185. (if is-percent
  9186. (format "[%d%%]" (floor (* 100.0 cnt-done)
  9187. (max 1 cnt-all)))
  9188. (format "[%d/%d]" cnt-done cnt-all))
  9189. ndel (- (match-end 0) checkbox-beg))
  9190. (goto-char checkbox-beg)
  9191. (insert new)
  9192. (delete-region (point) (+ (point) ndel))
  9193. (when org-auto-align-tags (org-fix-tags-on-the-fly)))
  9194. (when cookie-present
  9195. (run-hook-with-args 'org-after-todo-statistics-hook
  9196. cnt-done (- cnt-all cnt-done))))))
  9197. (run-hooks 'org-todo-statistics-hook)))
  9198. (defvar org-after-todo-statistics-hook nil
  9199. "Hook that is called after a TODO statistics cookie has been updated.
  9200. Each function is called with two arguments: the number of not-done entries
  9201. and the number of done entries.
  9202. For example, the following function, when added to this hook, will switch
  9203. an entry to DONE when all children are done, and back to TODO when new
  9204. entries are set to a TODO status. Note that this hook is only called
  9205. when there is a statistics cookie in the headline!
  9206. (defun org-summary-todo (n-done n-not-done)
  9207. \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
  9208. (let (org-log-done org-log-states) ; turn off logging
  9209. (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
  9210. (defvar org-todo-statistics-hook nil
  9211. "Hook that is run whenever Org thinks TODO statistics should be updated.
  9212. This hook runs even if there is no statistics cookie present, in which case
  9213. `org-after-todo-statistics-hook' would not run.")
  9214. (defun org-todo-trigger-tag-changes (state)
  9215. "Apply the changes defined in `org-todo-state-tags-triggers'."
  9216. (let ((l org-todo-state-tags-triggers)
  9217. changes)
  9218. (when (or (not state) (equal state ""))
  9219. (setq changes (append changes (cdr (assoc "" l)))))
  9220. (when (and (stringp state) (> (length state) 0))
  9221. (setq changes (append changes (cdr (assoc state l)))))
  9222. (when (member state org-not-done-keywords)
  9223. (setq changes (append changes (cdr (assq 'todo l)))))
  9224. (when (member state org-done-keywords)
  9225. (setq changes (append changes (cdr (assq 'done l)))))
  9226. (dolist (c changes)
  9227. (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
  9228. (defun org-local-logging (value)
  9229. "Get logging settings from a property VALUE."
  9230. ;; Directly set the variables, they are already local.
  9231. (setq org-log-done nil
  9232. org-log-repeat nil
  9233. org-todo-log-states nil)
  9234. (dolist (w (split-string value))
  9235. (let (a)
  9236. (cond
  9237. ((setq a (assoc w org-startup-options))
  9238. (and (member (nth 1 a) '(org-log-done org-log-repeat))
  9239. (set (nth 1 a) (nth 2 a))))
  9240. ((setq a (org-extract-log-state-settings w))
  9241. (and (member (car a) org-todo-keywords-1)
  9242. (push a org-todo-log-states)))))))
  9243. (defun org-get-todo-sequence-head (kwd)
  9244. "Return the head of the TODO sequence to which KWD belongs.
  9245. If KWD is not set, check if there is a text property remembering the
  9246. right sequence."
  9247. (let (p)
  9248. (cond
  9249. ((not kwd)
  9250. (or (get-text-property (point-at-bol) 'org-todo-head)
  9251. (progn
  9252. (setq p (next-single-property-change (point-at-bol) 'org-todo-head
  9253. nil (point-at-eol)))
  9254. (get-text-property p 'org-todo-head))))
  9255. ((not (member kwd org-todo-keywords-1))
  9256. (car org-todo-keywords-1))
  9257. (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
  9258. (defun org-fast-todo-selection (&optional current-state)
  9259. "Fast TODO keyword selection with single keys.
  9260. Returns the new TODO keyword, or nil if no state change should occur.
  9261. When CURRENT-STATE is given and selection letters are not unique globally,
  9262. prefer a state in the current sequence over on in another sequence."
  9263. (let* ((fulltable org-todo-key-alist)
  9264. (head (org-get-todo-sequence-head current-state))
  9265. (done-keywords org-done-keywords) ;; needed for the faces.
  9266. (maxlen (apply 'max (mapcar
  9267. (lambda (x)
  9268. (if (stringp (car x)) (string-width (car x)) 0))
  9269. fulltable)))
  9270. (expert (equal org-use-fast-todo-selection 'expert))
  9271. (prompt "")
  9272. (fwidth (+ maxlen 3 1 3))
  9273. (ncol (/ (- (window-width) 4) fwidth))
  9274. tg cnt e c tbl subtable
  9275. groups ingroup in-current-sequence)
  9276. (save-excursion
  9277. (save-window-excursion
  9278. (if expert
  9279. (set-buffer (get-buffer-create " *Org todo*"))
  9280. (delete-other-windows)
  9281. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
  9282. (org-switch-to-buffer-other-window " *Org todo*"))
  9283. (erase-buffer)
  9284. (setq-local org-done-keywords done-keywords)
  9285. (setq tbl fulltable cnt 0)
  9286. (while (setq e (pop tbl))
  9287. (cond
  9288. ((equal e '(:startgroup))
  9289. (push '() groups) (setq ingroup t)
  9290. (unless (= cnt 0)
  9291. (setq cnt 0)
  9292. (insert "\n"))
  9293. (setq prompt (concat prompt "{"))
  9294. (insert "{ "))
  9295. ((equal e '(:endgroup))
  9296. (setq ingroup nil cnt 0 in-current-sequence nil)
  9297. (setq prompt (concat prompt "}"))
  9298. (insert "}\n"))
  9299. ((equal e '(:newline))
  9300. (unless (= cnt 0)
  9301. (setq cnt 0)
  9302. (insert "\n")
  9303. (setq e (car tbl))
  9304. (while (equal (car tbl) '(:newline))
  9305. (insert "\n")
  9306. (setq tbl (cdr tbl)))))
  9307. (t
  9308. (setq tg (car e) c (cdr e))
  9309. (if (equal tg head) (setq in-current-sequence t))
  9310. (when ingroup (push tg (car groups)))
  9311. (when in-current-sequence (push e subtable))
  9312. (setq tg (org-add-props tg nil 'face
  9313. (org-get-todo-face tg)))
  9314. (when (and (= cnt 0) (not ingroup)) (insert " "))
  9315. (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
  9316. (insert "[" c "] " tg (make-string
  9317. (- fwidth 4 (length tg)) ?\ ))
  9318. (when (and (= (setq cnt (1+ cnt)) ncol)
  9319. ;; Avoid lines with just a closing delimiter.
  9320. (not (equal (car tbl) '(:endgroup))))
  9321. (insert "\n")
  9322. (when ingroup (insert " "))
  9323. (setq cnt 0)))))
  9324. (insert "\n")
  9325. (goto-char (point-min))
  9326. (unless expert (org-fit-window-to-buffer))
  9327. (message (concat "[a-z..]:Set [SPC]:clear"
  9328. (if expert (concat "\n" prompt) "")))
  9329. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  9330. (setq subtable (nreverse subtable))
  9331. (cond
  9332. ((or (= c ?\C-g)
  9333. (and (= c ?q) (not (rassoc c fulltable))))
  9334. (setq quit-flag t))
  9335. ((= c ?\ ) nil)
  9336. ((setq e (or (rassoc c subtable) (rassoc c fulltable))
  9337. tg (car e))
  9338. tg)
  9339. (t (setq quit-flag t)))))))
  9340. (defun org-entry-is-todo-p ()
  9341. (member (org-get-todo-state) org-not-done-keywords))
  9342. (defun org-entry-is-done-p ()
  9343. (member (org-get-todo-state) org-done-keywords))
  9344. (defun org-get-todo-state ()
  9345. "Return the TODO keyword of the current subtree."
  9346. (save-excursion
  9347. (org-back-to-heading t)
  9348. (and (let ((case-fold-search nil))
  9349. (looking-at org-todo-line-regexp))
  9350. (match-end 2)
  9351. (match-string 2))))
  9352. (defun org-at-date-range-p (&optional inactive-ok)
  9353. "Non-nil if point is inside a date range.
  9354. When optional argument INACTIVE-OK is non-nil, also consider
  9355. inactive time ranges.
  9356. When this function returns a non-nil value, match data is set
  9357. according to `org-tr-regexp-both' or `org-tr-regexp', depending
  9358. on INACTIVE-OK."
  9359. (interactive)
  9360. (save-excursion
  9361. (catch 'exit
  9362. (let ((pos (point)))
  9363. (skip-chars-backward "^[<\r\n")
  9364. (skip-chars-backward "<[")
  9365. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9366. (>= (match-end 0) pos)
  9367. (throw 'exit t))
  9368. (skip-chars-backward "^<[\r\n")
  9369. (skip-chars-backward "<[")
  9370. (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
  9371. (>= (match-end 0) pos)
  9372. (throw 'exit t)))
  9373. nil)))
  9374. (defun org-get-repeat (&optional timestamp)
  9375. "Check if there is a time-stamp with repeater in this entry.
  9376. Return the repeater, as a string, or nil. Also return nil when
  9377. this function is called before first heading.
  9378. When optional argument TIMESTAMP is a string, extract the
  9379. repeater from there instead."
  9380. (save-match-data
  9381. (cond
  9382. (timestamp
  9383. (and (string-match org-repeat-re timestamp)
  9384. (match-string-no-properties 1 timestamp)))
  9385. ((org-before-first-heading-p) nil)
  9386. (t
  9387. (save-excursion
  9388. (org-back-to-heading t)
  9389. (let ((end (org-entry-end-position)))
  9390. (catch :repeat
  9391. (while (re-search-forward org-repeat-re end t)
  9392. (when (save-match-data (org-at-timestamp-p 'agenda))
  9393. (throw :repeat (match-string-no-properties 1)))))))))))
  9394. (defvar org-last-changed-timestamp)
  9395. (defvar org-last-inserted-timestamp)
  9396. (defvar org-log-post-message)
  9397. (defvar org-log-note-purpose)
  9398. (defvar org-log-note-how nil)
  9399. (defvar org-log-note-extra)
  9400. (defvar org-log-setup nil)
  9401. (defun org-auto-repeat-maybe (done-word)
  9402. "Check if the current headline contains a repeated time-stamp.
  9403. If yes, set TODO state back to what it was and change the base date
  9404. of repeating deadline/scheduled time stamps to new date.
  9405. This function is run automatically after each state change to a DONE state."
  9406. (let* ((repeat (org-get-repeat))
  9407. (aa (assoc org-last-state org-todo-kwd-alist))
  9408. (interpret (nth 1 aa))
  9409. (head (nth 2 aa))
  9410. (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
  9411. (msg "Entry repeats: ")
  9412. (org-log-done nil)
  9413. (org-todo-log-states nil)
  9414. (end (copy-marker (org-entry-end-position))))
  9415. (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
  9416. (when (eq org-log-repeat t) (setq org-log-repeat 'state))
  9417. (let ((to-state
  9418. (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
  9419. (and (stringp org-todo-repeat-to-state)
  9420. org-todo-repeat-to-state)
  9421. (and org-todo-repeat-to-state org-last-state))))
  9422. (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
  9423. to-state)
  9424. ((eq interpret 'type) org-last-state)
  9425. (head)
  9426. (t 'none))))
  9427. (org-back-to-heading t)
  9428. (org-add-planning-info nil nil 'closed)
  9429. ;; When `org-log-repeat' is non-nil or entry contains
  9430. ;; a clock, set LAST_REPEAT property.
  9431. (when (or org-log-repeat
  9432. (catch :clock
  9433. (save-excursion
  9434. (while (re-search-forward org-clock-line-re end t)
  9435. (when (org-at-clock-log-p) (throw :clock t))))))
  9436. (org-entry-put nil "LAST_REPEAT" (format-time-string
  9437. (org-time-stamp-format t t))))
  9438. (when org-log-repeat
  9439. (if org-log-setup
  9440. ;; We are already setup for some record.
  9441. (when (eq org-log-repeat 'note)
  9442. ;; Make sure we take a note, not only a time stamp.
  9443. (setq org-log-note-how 'note))
  9444. ;; Set up for taking a record.
  9445. (org-add-log-setup 'state
  9446. (or done-word (car org-done-keywords))
  9447. org-last-state
  9448. org-log-repeat)))
  9449. ;; Time-stamps without a repeater are usually skipped. However,
  9450. ;; a SCHEDULED time-stamp without one is removed, as they are no
  9451. ;; longer relevant.
  9452. (save-excursion
  9453. (let ((scheduled (org-entry-get (point) "SCHEDULED")))
  9454. (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
  9455. (org-remove-timestamp-with-keyword org-scheduled-string))))
  9456. ;; Update every time-stamp with a repeater in the entry.
  9457. (let ((planning-re (regexp-opt
  9458. (list org-scheduled-string org-deadline-string))))
  9459. (while (re-search-forward org-repeat-re end t)
  9460. (let* ((ts (match-string 0))
  9461. (type (if (not (org-at-planning-p)) "Plain:"
  9462. (save-excursion
  9463. (re-search-backward
  9464. planning-re (line-beginning-position) t)
  9465. (match-string 0)))))
  9466. (when (and (org-at-timestamp-p 'agenda)
  9467. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
  9468. (let ((n (string-to-number (match-string 2 ts)))
  9469. (what (match-string 3 ts)))
  9470. (when (equal what "w") (setq n (* n 7) what "d"))
  9471. (when (and (equal what "h")
  9472. (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
  9473. ts)))
  9474. (user-error
  9475. "Cannot repeat in %d hour(s) because no hour has been set"
  9476. n))
  9477. ;; Preparation, see if we need to modify the start
  9478. ;; date for the change.
  9479. (when (match-end 1)
  9480. (let ((time (save-match-data (org-time-string-to-time ts)))
  9481. (repeater-type (match-string 1 ts)))
  9482. (cond
  9483. ((equal "." repeater-type)
  9484. ;; Shift starting date to today, or now if
  9485. ;; repeater is by hours.
  9486. (if (equal what "h")
  9487. (org-timestamp-change
  9488. (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
  9489. (org-timestamp-change
  9490. (- (org-today) (time-to-days time)) 'day)))
  9491. ((equal "+" repeater-type)
  9492. (let ((nshiftmax 10)
  9493. (nshift 0))
  9494. (while (or (= nshift 0)
  9495. (not (time-less-p nil time)))
  9496. (when (= nshiftmax (cl-incf nshift))
  9497. (or (y-or-n-p
  9498. (format "%d repeater intervals were not \
  9499. enough to shift date past today. Continue? "
  9500. nshift))
  9501. (user-error "Abort")))
  9502. (org-timestamp-change n (cdr (assoc what whata)))
  9503. (org-in-regexp org-ts-regexp3)
  9504. (setq ts (match-string 1))
  9505. (setq time
  9506. (save-match-data
  9507. (org-time-string-to-time ts)))))
  9508. (org-timestamp-change (- n) (cdr (assoc what whata)))
  9509. ;; Rematch, so that we have everything in place
  9510. ;; for the real shift.
  9511. (org-in-regexp org-ts-regexp3)
  9512. (setq ts (match-string 1))
  9513. (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  9514. ts)))))
  9515. (save-excursion
  9516. (org-timestamp-change n (cdr (assoc what whata)) nil t))
  9517. (setq msg
  9518. (concat msg type " " org-last-changed-timestamp " ")))))))
  9519. (run-hooks 'org-todo-repeat-hook)
  9520. (setq org-log-post-message msg)
  9521. (message msg))))
  9522. (defun org-show-todo-tree (arg)
  9523. "Make a compact tree which shows all headlines marked with TODO.
  9524. The tree will show the lines where the regexp matches, and all higher
  9525. headlines above the match.
  9526. With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  9527. With a numeric prefix N, construct a sparse tree for the Nth element
  9528. of `org-todo-keywords-1'."
  9529. (interactive "P")
  9530. (let ((case-fold-search nil)
  9531. (kwd-re
  9532. (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  9533. ((equal arg '(4))
  9534. (let ((kwd
  9535. (completing-read "Keyword (or KWD1|KWD2|...): "
  9536. (mapcar #'list org-todo-keywords-1))))
  9537. (concat "\\("
  9538. (mapconcat 'identity (org-split-string kwd "|") "\\|")
  9539. "\\)\\>")))
  9540. ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  9541. (regexp-quote (nth (1- (prefix-numeric-value arg))
  9542. org-todo-keywords-1)))
  9543. (t (user-error "Invalid prefix argument: %s" arg)))))
  9544. (message "%d TODO entries found"
  9545. (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  9546. (defun org--deadline-or-schedule (arg type time)
  9547. "Insert DEADLINE or SCHEDULE information in current entry.
  9548. TYPE is either `deadline' or `scheduled'. See `org-deadline' or
  9549. `org-schedule' for information about ARG and TIME arguments."
  9550. (let* ((deadline? (eq type 'deadline))
  9551. (keyword (if deadline? org-deadline-string org-scheduled-string))
  9552. (log (if deadline? org-log-redeadline org-log-reschedule))
  9553. (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  9554. (old-date-time (and old-date (org-time-string-to-time old-date)))
  9555. ;; Save repeater cookie from either TIME or current scheduled
  9556. ;; time stamp. We are going to insert it back at the end of
  9557. ;; the process.
  9558. (repeater (or (and (org-string-nw-p time)
  9559. ;; We use `org-repeat-re' because we need
  9560. ;; to tell the difference between a real
  9561. ;; repeater and a time delta, e.g. "+2d".
  9562. (string-match org-repeat-re time)
  9563. (match-string 1 time))
  9564. (and (org-string-nw-p old-date)
  9565. (string-match "\\([.+-]+[0-9]+[hdwmy]\
  9566. \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  9567. old-date)
  9568. (match-string 1 old-date)))))
  9569. (pcase arg
  9570. (`(4)
  9571. (if (not old-date)
  9572. (message (if deadline? "Entry had no deadline to remove"
  9573. "Entry was not scheduled"))
  9574. (when (and old-date log)
  9575. (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  9576. nil old-date log))
  9577. (org-remove-timestamp-with-keyword keyword)
  9578. (message (if deadline? "Entry no longer has a deadline."
  9579. "Entry is no longer scheduled."))))
  9580. (`(16)
  9581. (save-excursion
  9582. (org-back-to-heading t)
  9583. (let ((regexp (if deadline? org-deadline-time-regexp
  9584. org-scheduled-time-regexp)))
  9585. (if (not (re-search-forward regexp (line-end-position 2) t))
  9586. (user-error (if deadline? "No deadline information to update"
  9587. "No scheduled information to update"))
  9588. (let* ((rpl0 (match-string 1))
  9589. (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  9590. (msg (if deadline? "Warn starting from" "Delay until")))
  9591. (replace-match
  9592. (concat keyword
  9593. " <" rpl
  9594. (format " -%dd"
  9595. (abs (- (time-to-days
  9596. (save-match-data
  9597. (org-read-date
  9598. nil t nil msg old-date-time)))
  9599. (time-to-days old-date-time))))
  9600. ">") t t))))))
  9601. (_
  9602. (org-add-planning-info type time 'closed)
  9603. (when (and old-date
  9604. log
  9605. (not (equal old-date org-last-inserted-timestamp)))
  9606. (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  9607. org-last-inserted-timestamp
  9608. old-date
  9609. log))
  9610. (when repeater
  9611. (save-excursion
  9612. (org-back-to-heading t)
  9613. (when (re-search-forward
  9614. (concat keyword " " org-last-inserted-timestamp)
  9615. (line-end-position 2)
  9616. t)
  9617. (goto-char (1- (match-end 0)))
  9618. (insert " " repeater)
  9619. (setq org-last-inserted-timestamp
  9620. (concat (substring org-last-inserted-timestamp 0 -1)
  9621. " " repeater
  9622. (substring org-last-inserted-timestamp -1))))))
  9623. (message (if deadline? "Deadline on %s" "Scheduled to %s")
  9624. org-last-inserted-timestamp)))))
  9625. (defun org-deadline (arg &optional time)
  9626. "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  9627. When called interactively, this command pops up the Emacs calendar to let
  9628. the user select a date.
  9629. With one universal prefix argument, remove any deadline from the item.
  9630. With two universal prefix arguments, prompt for a warning delay.
  9631. With argument TIME, set the deadline at the corresponding date. TIME
  9632. can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9633. (interactive "P")
  9634. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9635. (org-map-entries
  9636. (lambda () (org--deadline-or-schedule arg 'deadline time))
  9637. nil
  9638. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9639. 'region-start-level
  9640. 'region)
  9641. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9642. (org--deadline-or-schedule arg 'deadline time)))
  9643. (defun org-schedule (arg &optional time)
  9644. "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  9645. When called interactively, this command pops up the Emacs calendar to let
  9646. the user select a date.
  9647. With one universal prefix argument, remove any scheduling date from the item.
  9648. With two universal prefix arguments, prompt for a delay cookie.
  9649. With argument TIME, scheduled at the corresponding date. TIME can
  9650. either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  9651. (interactive "P")
  9652. (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  9653. (org-map-entries
  9654. (lambda () (org--deadline-or-schedule arg 'scheduled time))
  9655. nil
  9656. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  9657. 'region-start-level
  9658. 'region)
  9659. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  9660. (org--deadline-or-schedule arg 'scheduled time)))
  9661. (defun org-get-scheduled-time (pom &optional inherit)
  9662. "Get the scheduled time as a time tuple, of a format suitable
  9663. for calling org-schedule with, or if there is no scheduling,
  9664. returns nil."
  9665. (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  9666. (when time
  9667. (org-time-string-to-time time))))
  9668. (defun org-get-deadline-time (pom &optional inherit)
  9669. "Get the deadline as a time tuple, of a format suitable for
  9670. calling org-deadline with, or if there is no scheduling, returns
  9671. nil."
  9672. (let ((time (org-entry-get pom "DEADLINE" inherit)))
  9673. (when time
  9674. (org-time-string-to-time time))))
  9675. (defun org-remove-timestamp-with-keyword (keyword)
  9676. "Remove all time stamps with KEYWORD in the current entry."
  9677. (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  9678. beg)
  9679. (save-excursion
  9680. (org-back-to-heading t)
  9681. (setq beg (point))
  9682. (outline-next-heading)
  9683. (while (re-search-backward re beg t)
  9684. (replace-match "")
  9685. (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
  9686. (equal (char-before) ?\ ))
  9687. (backward-delete-char 1)
  9688. (when (string-match "^[ \t]*$" (buffer-substring
  9689. (point-at-bol) (point-at-eol)))
  9690. (delete-region (point-at-bol)
  9691. (min (point-max) (1+ (point-at-eol))))))))))
  9692. (defvar org-time-was-given) ; dynamically scoped parameter
  9693. (defvar org-end-time-was-given) ; dynamically scoped parameter
  9694. (defun org-at-planning-p ()
  9695. "Non-nil when point is on a planning info line."
  9696. ;; This is as accurate and faster than `org-element-at-point' since
  9697. ;; planning info location is fixed in the section.
  9698. (org-with-wide-buffer
  9699. (beginning-of-line)
  9700. (and (looking-at-p org-planning-line-re)
  9701. (eq (point)
  9702. (ignore-errors
  9703. (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  9704. (org-back-to-heading t)
  9705. (org-with-limited-levels (org-back-to-heading t)))
  9706. (line-beginning-position 2))))))
  9707. (defun org-add-planning-info (what &optional time &rest remove)
  9708. "Insert new timestamp with keyword in the planning line.
  9709. WHAT indicates what kind of time stamp to add. It is a symbol
  9710. among `closed', `deadline', `scheduled' and nil. TIME indicates
  9711. the time to use. If none is given, the user is prompted for
  9712. a date. REMOVE indicates what kind of entries to remove. An old
  9713. WHAT entry will also be removed."
  9714. (let (org-time-was-given org-end-time-was-given default-time default-input)
  9715. (when (and (memq what '(scheduled deadline))
  9716. (or (not time)
  9717. (and (stringp time)
  9718. (string-match "^[-+]+[0-9]" time))))
  9719. ;; Try to get a default date/time from existing timestamp
  9720. (save-excursion
  9721. (org-back-to-heading t)
  9722. (let ((end (save-excursion (outline-next-heading) (point))) ts)
  9723. (when (re-search-forward (if (eq what 'scheduled)
  9724. org-scheduled-time-regexp
  9725. org-deadline-time-regexp)
  9726. end t)
  9727. (setq ts (match-string 1)
  9728. default-time (org-time-string-to-time ts)
  9729. default-input (and ts (org-get-compact-tod ts)))))))
  9730. (when what
  9731. (setq time
  9732. (if (stringp time)
  9733. ;; This is a string (relative or absolute), set
  9734. ;; proper date.
  9735. (apply #'encode-time
  9736. (org-read-date-analyze
  9737. time default-time (decode-time default-time)))
  9738. ;; If necessary, get the time from the user
  9739. (or time (org-read-date nil 'to-time nil
  9740. (cl-case what
  9741. (deadline "DEADLINE")
  9742. (scheduled "SCHEDULED")
  9743. (otherwise nil))
  9744. default-time default-input)))))
  9745. (org-with-wide-buffer
  9746. (org-back-to-heading t)
  9747. (let ((planning? (save-excursion
  9748. (forward-line)
  9749. (looking-at-p org-planning-line-re))))
  9750. (cond
  9751. (planning?
  9752. (forward-line)
  9753. ;; Move to current indentation.
  9754. (skip-chars-forward " \t")
  9755. ;; Check if we have to remove something.
  9756. (dolist (type (if what (cons what remove) remove))
  9757. (save-excursion
  9758. (when (re-search-forward
  9759. (cl-case type
  9760. (closed org-closed-time-regexp)
  9761. (deadline org-deadline-time-regexp)
  9762. (scheduled org-scheduled-time-regexp)
  9763. (otherwise (error "Invalid planning type: %s" type)))
  9764. (line-end-position)
  9765. t)
  9766. ;; Delete until next keyword or end of line.
  9767. (delete-region
  9768. (match-beginning 0)
  9769. (if (re-search-forward org-keyword-time-not-clock-regexp
  9770. (line-end-position)
  9771. t)
  9772. (match-beginning 0)
  9773. (line-end-position))))))
  9774. ;; If there is nothing more to add and no more keyword is
  9775. ;; left, remove the line completely.
  9776. (if (and (looking-at-p "[ \t]*$") (not what))
  9777. (delete-region (line-end-position 0)
  9778. (line-end-position))
  9779. ;; If we removed last keyword, do not leave trailing white
  9780. ;; space at the end of line.
  9781. (let ((p (point)))
  9782. (save-excursion
  9783. (end-of-line)
  9784. (unless (= (skip-chars-backward " \t" p) 0)
  9785. (delete-region (point) (line-end-position)))))))
  9786. (what
  9787. (end-of-line)
  9788. (insert "\n")
  9789. (when org-adapt-indentation
  9790. (indent-to-column (1+ (org-outline-level)))))
  9791. (t nil)))
  9792. (when what
  9793. ;; Insert planning keyword.
  9794. (insert (cl-case what
  9795. (closed org-closed-string)
  9796. (deadline org-deadline-string)
  9797. (scheduled org-scheduled-string)
  9798. (otherwise (error "Invalid planning type: %s" what)))
  9799. " ")
  9800. ;; Insert associated timestamp.
  9801. (let ((ts (org-insert-time-stamp
  9802. time
  9803. (or org-time-was-given
  9804. (and (eq what 'closed) org-log-done-with-time))
  9805. (eq what 'closed)
  9806. nil nil (list org-end-time-was-given))))
  9807. (unless (eolp) (insert " "))
  9808. ts)))))
  9809. (defvar org-log-note-marker (make-marker)
  9810. "Marker pointing at the entry where the note is to be inserted.")
  9811. (defvar org-log-note-purpose nil)
  9812. (defvar org-log-note-state nil)
  9813. (defvar org-log-note-previous-state nil)
  9814. (defvar org-log-note-extra nil)
  9815. (defvar org-log-note-window-configuration nil)
  9816. (defvar org-log-note-return-to (make-marker))
  9817. (defvar org-log-note-effective-time nil
  9818. "Remembered current time.
  9819. So that dynamically scoped `org-extend-today-until' affects
  9820. timestamps in state change log.")
  9821. (defvar org-log-post-message nil
  9822. "Message to be displayed after a log note has been stored.
  9823. The auto-repeater uses this.")
  9824. (defun org-add-note ()
  9825. "Add a note to the current entry.
  9826. This is done in the same way as adding a state change note."
  9827. (interactive)
  9828. (org-add-log-setup 'note))
  9829. (defun org-log-beginning (&optional create)
  9830. "Return expected start of log notes in current entry.
  9831. When optional argument CREATE is non-nil, the function creates
  9832. a drawer to store notes, if necessary. Returned position ignores
  9833. narrowing."
  9834. (org-with-wide-buffer
  9835. (let ((drawer (org-log-into-drawer)))
  9836. (cond
  9837. (drawer
  9838. (org-end-of-meta-data)
  9839. (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  9840. (end (if (org-at-heading-p) (point)
  9841. (save-excursion (outline-next-heading) (point))))
  9842. (case-fold-search t))
  9843. (catch 'exit
  9844. ;; Try to find existing drawer.
  9845. (while (re-search-forward regexp end t)
  9846. (let ((element (org-element-at-point)))
  9847. (when (eq (org-element-type element) 'drawer)
  9848. (let ((cend (org-element-property :contents-end element)))
  9849. (when (and (not org-log-states-order-reversed) cend)
  9850. (goto-char cend)))
  9851. (throw 'exit nil))))
  9852. ;; No drawer found. Create one, if permitted.
  9853. (when create
  9854. (unless (bolp) (insert "\n"))
  9855. (let ((beg (point)))
  9856. (insert ":" drawer ":\n:END:\n")
  9857. (org-indent-region beg (point))
  9858. (org-flag-region (line-end-position -1)
  9859. (1- (point)) t 'outline))
  9860. (end-of-line -1)))))
  9861. (t
  9862. (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  9863. (skip-chars-forward " \t\n")
  9864. (beginning-of-line)
  9865. (unless org-log-states-order-reversed
  9866. (org-skip-over-state-notes)
  9867. (skip-chars-backward " \t\n")
  9868. (forward-line)))))
  9869. (if (bolp) (point) (line-beginning-position 2))))
  9870. (defun org-add-log-setup (&optional purpose state prev-state how extra)
  9871. "Set up the post command hook to take a note.
  9872. If this is about to TODO state change, the new state is expected in STATE.
  9873. HOW is an indicator what kind of note should be created.
  9874. EXTRA is additional text that will be inserted into the notes buffer."
  9875. (move-marker org-log-note-marker (point))
  9876. (setq org-log-note-purpose purpose
  9877. org-log-note-state state
  9878. org-log-note-previous-state prev-state
  9879. org-log-note-how how
  9880. org-log-note-extra extra
  9881. org-log-note-effective-time (org-current-effective-time)
  9882. org-log-setup t)
  9883. (add-hook 'post-command-hook 'org-add-log-note 'append))
  9884. (defun org-skip-over-state-notes ()
  9885. "Skip past the list of State notes in an entry."
  9886. (when (ignore-errors (goto-char (org-in-item-p)))
  9887. (let* ((struct (org-list-struct))
  9888. (prevs (org-list-prevs-alist struct))
  9889. (regexp
  9890. (concat "[ \t]*- +"
  9891. (replace-regexp-in-string
  9892. " +" " +"
  9893. (org-replace-escapes
  9894. (regexp-quote (cdr (assq 'state org-log-note-headings)))
  9895. `(("%d" . ,org-ts-regexp-inactive)
  9896. ("%D" . ,org-ts-regexp)
  9897. ("%s" . "\\(?:\"\\S-+\"\\)?")
  9898. ("%S" . "\\(?:\"\\S-+\"\\)?")
  9899. ("%t" . ,org-ts-regexp-inactive)
  9900. ("%T" . ,org-ts-regexp)
  9901. ("%u" . ".*?")
  9902. ("%U" . ".*?")))))))
  9903. (while (looking-at-p regexp)
  9904. (goto-char (or (org-list-get-next-item (point) struct prevs)
  9905. (org-list-get-item-end (point) struct)))))))
  9906. (defun org-add-log-note (&optional _purpose)
  9907. "Pop up a window for taking a note, and add this note later."
  9908. (remove-hook 'post-command-hook 'org-add-log-note)
  9909. (setq org-log-setup nil)
  9910. (setq org-log-note-window-configuration (current-window-configuration))
  9911. (delete-other-windows)
  9912. (move-marker org-log-note-return-to (point))
  9913. (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  9914. (goto-char org-log-note-marker)
  9915. (org-switch-to-buffer-other-window "*Org Note*")
  9916. (erase-buffer)
  9917. (if (memq org-log-note-how '(time state))
  9918. (org-store-log-note)
  9919. (let ((org-inhibit-startup t)) (org-mode))
  9920. (insert (format "# Insert note for %s.
  9921. # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  9922. (cl-case org-log-note-purpose
  9923. (clock-out "stopped clock")
  9924. (done "closed todo item")
  9925. (reschedule "rescheduling")
  9926. (delschedule "no longer scheduled")
  9927. (redeadline "changing deadline")
  9928. (deldeadline "removing deadline")
  9929. (refile "refiling")
  9930. (note "this entry")
  9931. (state
  9932. (format "state change from \"%s\" to \"%s\""
  9933. (or org-log-note-previous-state "")
  9934. (or org-log-note-state "")))
  9935. (t (error "This should not happen")))))
  9936. (when org-log-note-extra (insert org-log-note-extra))
  9937. (setq-local org-finish-function 'org-store-log-note)
  9938. (run-hooks 'org-log-buffer-setup-hook)))
  9939. (defvar org-note-abort nil) ; dynamically scoped
  9940. (defun org-store-log-note ()
  9941. "Finish taking a log note, and insert it to where it belongs."
  9942. (let ((txt (prog1 (buffer-string)
  9943. (kill-buffer)))
  9944. (note (cdr (assq org-log-note-purpose org-log-note-headings)))
  9945. lines)
  9946. (while (string-match "\\`# .*\n[ \t\n]*" txt)
  9947. (setq txt (replace-match "" t t txt)))
  9948. (when (string-match "\\s-+\\'" txt)
  9949. (setq txt (replace-match "" t t txt)))
  9950. (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  9951. (when (org-string-nw-p note)
  9952. (setq note
  9953. (org-replace-escapes
  9954. note
  9955. (list (cons "%u" (user-login-name))
  9956. (cons "%U" user-full-name)
  9957. (cons "%t" (format-time-string
  9958. (org-time-stamp-format 'long 'inactive)
  9959. org-log-note-effective-time))
  9960. (cons "%T" (format-time-string
  9961. (org-time-stamp-format 'long nil)
  9962. org-log-note-effective-time))
  9963. (cons "%d" (format-time-string
  9964. (org-time-stamp-format nil 'inactive)
  9965. org-log-note-effective-time))
  9966. (cons "%D" (format-time-string
  9967. (org-time-stamp-format nil nil)
  9968. org-log-note-effective-time))
  9969. (cons "%s" (cond
  9970. ((not org-log-note-state) "")
  9971. ((string-match-p org-ts-regexp
  9972. org-log-note-state)
  9973. (format "\"[%s]\""
  9974. (substring org-log-note-state 1 -1)))
  9975. (t (format "\"%s\"" org-log-note-state))))
  9976. (cons "%S"
  9977. (cond
  9978. ((not org-log-note-previous-state) "")
  9979. ((string-match-p org-ts-regexp
  9980. org-log-note-previous-state)
  9981. (format "\"[%s]\""
  9982. (substring
  9983. org-log-note-previous-state 1 -1)))
  9984. (t (format "\"%s\""
  9985. org-log-note-previous-state)))))))
  9986. (when lines (setq note (concat note " \\\\")))
  9987. (push note lines))
  9988. (when (and lines (not org-note-abort))
  9989. (with-current-buffer (marker-buffer org-log-note-marker)
  9990. (org-with-wide-buffer
  9991. ;; Find location for the new note.
  9992. (goto-char org-log-note-marker)
  9993. (set-marker org-log-note-marker nil)
  9994. ;; Note associated to a clock is to be located right after
  9995. ;; the clock. Do not move point.
  9996. (unless (eq org-log-note-purpose 'clock-out)
  9997. (goto-char (org-log-beginning t)))
  9998. ;; Make sure point is at the beginning of an empty line.
  9999. (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
  10000. ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
  10001. ;; In an existing list, add a new item at the top level.
  10002. ;; Otherwise, indent line like a regular one.
  10003. (let ((itemp (org-in-item-p)))
  10004. (if itemp
  10005. (indent-line-to
  10006. (let ((struct (save-excursion
  10007. (goto-char itemp) (org-list-struct))))
  10008. (org-list-get-ind (org-list-get-top-point struct) struct)))
  10009. (org-indent-line)))
  10010. (insert (org-list-bullet-string "-") (pop lines))
  10011. (let ((ind (org-list-item-body-column (line-beginning-position))))
  10012. (dolist (line lines)
  10013. (insert "\n")
  10014. (indent-line-to ind)
  10015. (insert line)))
  10016. (message "Note stored")
  10017. (org-back-to-heading t)))))
  10018. ;; Don't add undo information when called from `org-agenda-todo'.
  10019. (set-window-configuration org-log-note-window-configuration)
  10020. (with-current-buffer (marker-buffer org-log-note-return-to)
  10021. (goto-char org-log-note-return-to))
  10022. (move-marker org-log-note-return-to nil)
  10023. (when org-log-post-message (message "%s" org-log-post-message)))
  10024. (defun org-remove-empty-drawer-at (pos)
  10025. "Remove an empty drawer at position POS.
  10026. POS may also be a marker."
  10027. (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10028. (org-with-wide-buffer
  10029. (goto-char pos)
  10030. (let ((drawer (org-element-at-point)))
  10031. (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10032. (not (org-element-property :contents-begin drawer)))
  10033. (delete-region (org-element-property :begin drawer)
  10034. (progn (goto-char (org-element-property :end drawer))
  10035. (skip-chars-backward " \r\t\n")
  10036. (forward-line)
  10037. (point))))))))
  10038. (defvar org-ts-type nil)
  10039. (defun org-sparse-tree (&optional arg type)
  10040. "Create a sparse tree, prompt for the details.
  10041. This command can create sparse trees. You first need to select the type
  10042. of match used to create the tree:
  10043. t Show all TODO entries.
  10044. T Show entries with a specific TODO keyword.
  10045. m Show entries selected by a tags/property match.
  10046. p Enter a property name and its value (both with completion on existing
  10047. names/values) and show entries with that property.
  10048. r Show entries matching a regular expression (`/' can be used as well).
  10049. b Show deadlines and scheduled items before a date.
  10050. a Show deadlines and scheduled items after a date.
  10051. d Show deadlines due within `org-deadline-warning-days'.
  10052. D Show deadlines and scheduled items between a date range."
  10053. (interactive "P")
  10054. (setq type (or type org-sparse-tree-default-date-type))
  10055. (setq org-ts-type type)
  10056. (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10057. [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10058. [c]ycle through date types: %s"
  10059. (cl-case type
  10060. (all "all timestamps")
  10061. (scheduled "only scheduled")
  10062. (deadline "only deadline")
  10063. (active "only active timestamps")
  10064. (inactive "only inactive timestamps")
  10065. (closed "with a closed time-stamp")
  10066. (otherwise "scheduled/deadline")))
  10067. (let ((answer (read-char-exclusive)))
  10068. (cl-case answer
  10069. (?c
  10070. (org-sparse-tree
  10071. arg
  10072. (cadr
  10073. (memq type '(nil all scheduled deadline active inactive closed)))))
  10074. (?d (call-interactively 'org-check-deadlines))
  10075. (?b (call-interactively 'org-check-before-date))
  10076. (?a (call-interactively 'org-check-after-date))
  10077. (?D (call-interactively 'org-check-dates-range))
  10078. (?t (call-interactively 'org-show-todo-tree))
  10079. (?T (org-show-todo-tree '(4)))
  10080. (?m (call-interactively 'org-match-sparse-tree))
  10081. ((?p ?P)
  10082. (let* ((kwd (completing-read
  10083. "Property: " (mapcar #'list (org-buffer-property-keys))))
  10084. (value (completing-read
  10085. "Value: " (mapcar #'list (org-property-values kwd)))))
  10086. (unless (string-match "\\`{.*}\\'" value)
  10087. (setq value (concat "\"" value "\"")))
  10088. (org-match-sparse-tree arg (concat kwd "=" value))))
  10089. ((?r ?R ?/) (call-interactively 'org-occur))
  10090. (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10091. (defvar-local org-occur-highlights nil
  10092. "List of overlays used for occur matches.")
  10093. (defvar-local org-occur-parameters nil
  10094. "Parameters of the active org-occur calls.
  10095. This is a list, each call to org-occur pushes as cons cell,
  10096. containing the regular expression and the callback, onto the list.
  10097. The list can contain several entries if `org-occur' has been called
  10098. several time with the KEEP-PREVIOUS argument. Otherwise, this list
  10099. will only contain one set of parameters. When the highlights are
  10100. removed (for example with `C-c C-c', or with the next edit (depending
  10101. on `org-remove-highlights-with-change'), this variable is emptied
  10102. as well.")
  10103. (defun org-occur (regexp &optional keep-previous callback)
  10104. "Make a compact tree showing all matches of REGEXP.
  10105. The tree will show the lines where the regexp matches, and any other context
  10106. defined in `org-show-context-detail', which see.
  10107. When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10108. done by a previous call to `org-occur' will be kept, to allow stacking of
  10109. calls to this command.
  10110. Optional argument CALLBACK can be a function of no argument. In this case,
  10111. it is called with point at the end of the match, match data being set
  10112. accordingly. Current match is shown only if the return value is non-nil.
  10113. The function must neither move point nor alter narrowing."
  10114. (interactive "sRegexp: \nP")
  10115. (when (equal regexp "")
  10116. (user-error "Regexp cannot be empty"))
  10117. (unless keep-previous
  10118. (org-remove-occur-highlights nil nil t))
  10119. (push (cons regexp callback) org-occur-parameters)
  10120. (let ((cnt 0))
  10121. (save-excursion
  10122. (goto-char (point-min))
  10123. (when (or (not keep-previous) ; do not want to keep
  10124. (not org-occur-highlights)) ; no previous matches
  10125. ;; hide everything
  10126. (org-overview))
  10127. (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10128. (isearch-no-upper-case-p regexp t)
  10129. org-occur-case-fold-search)))
  10130. (while (re-search-forward regexp nil t)
  10131. (when (or (not callback)
  10132. (save-match-data (funcall callback)))
  10133. (setq cnt (1+ cnt))
  10134. (when org-highlight-sparse-tree-matches
  10135. (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10136. (org-show-context 'occur-tree)))))
  10137. (when org-remove-highlights-with-change
  10138. (add-hook 'before-change-functions 'org-remove-occur-highlights
  10139. nil 'local))
  10140. (unless org-sparse-tree-open-archived-trees
  10141. (org-hide-archived-subtrees (point-min) (point-max)))
  10142. (run-hooks 'org-occur-hook)
  10143. (when (called-interactively-p 'interactive)
  10144. (message "%d match(es) for regexp %s" cnt regexp))
  10145. cnt))
  10146. (defun org-occur-next-match (&optional n _reset)
  10147. "Function for `next-error-function' to find sparse tree matches.
  10148. N is the number of matches to move, when negative move backwards.
  10149. This function always goes back to the starting point when no
  10150. match is found."
  10151. (let* ((limit (if (< n 0) (point-min) (point-max)))
  10152. (search-func (if (< n 0)
  10153. 'previous-single-char-property-change
  10154. 'next-single-char-property-change))
  10155. (n (abs n))
  10156. (pos (point))
  10157. p1)
  10158. (catch 'exit
  10159. (while (setq p1 (funcall search-func (point) 'org-type))
  10160. (when (equal p1 limit)
  10161. (goto-char pos)
  10162. (user-error "No more matches"))
  10163. (when (equal (get-char-property p1 'org-type) 'org-occur)
  10164. (setq n (1- n))
  10165. (when (= n 0)
  10166. (goto-char p1)
  10167. (throw 'exit (point))))
  10168. (goto-char p1))
  10169. (goto-char p1)
  10170. (user-error "No more matches"))))
  10171. (defun org-highlight-new-match (beg end)
  10172. "Highlight from BEG to END and mark the highlight is an occur headline."
  10173. (let ((ov (make-overlay beg end)))
  10174. (overlay-put ov 'face 'secondary-selection)
  10175. (overlay-put ov 'org-type 'org-occur)
  10176. (push ov org-occur-highlights)))
  10177. (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10178. "Remove the occur highlights from the buffer.
  10179. BEG and END are ignored. If NOREMOVE is nil, remove this function
  10180. from the `before-change-functions' in the current buffer."
  10181. (interactive)
  10182. (unless org-inhibit-highlight-removal
  10183. (mapc #'delete-overlay org-occur-highlights)
  10184. (setq org-occur-highlights nil)
  10185. (setq org-occur-parameters nil)
  10186. (unless noremove
  10187. (remove-hook 'before-change-functions
  10188. 'org-remove-occur-highlights 'local))))
  10189. ;;;; Priorities
  10190. (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10191. "Regular expression matching the priority indicator.
  10192. A priority indicator can be e.g. [#A] or [#1].
  10193. This regular expression matches these groups:
  10194. 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10195. 1 : the priority cookie, e.g. \"[#A]\"
  10196. 2 : the value of the priority cookie, e.g. \"A\".")
  10197. (defun org-priority-up ()
  10198. "Increase the priority of the current item."
  10199. (interactive)
  10200. (org-priority 'up))
  10201. (defun org-priority-down ()
  10202. "Decrease the priority of the current item."
  10203. (interactive)
  10204. (org-priority 'down))
  10205. (defun org-priority (&optional action show)
  10206. "Change the priority of an item.
  10207. When called interactively with a `\\[universal-argument]' prefix,
  10208. show the priority in the minibuffer instead of changing it.
  10209. When called programmatically, ACTION can be `set', `up', `down',
  10210. or a character."
  10211. (interactive "P")
  10212. (when show
  10213. ;; Deprecation warning inserted for Org 9.2; once enough time has
  10214. ;; passed the SHOW argument should be removed.
  10215. (warn "`org-priority' called with deprecated SHOW argument"))
  10216. (if (equal action '(4))
  10217. (org-priority-show)
  10218. (unless org-priority-enable-commands
  10219. (user-error "Priority commands are disabled"))
  10220. (setq action (or action 'set))
  10221. (let ((nump (< org-priority-lowest 65))
  10222. current new news have remove)
  10223. (save-excursion
  10224. (org-back-to-heading t)
  10225. (when (looking-at org-priority-regexp)
  10226. (let ((ms (match-string 2)))
  10227. (setq current (org-priority-to-value ms)
  10228. have t)))
  10229. (cond
  10230. ((eq action 'remove)
  10231. (setq remove t new ?\ ))
  10232. ((or (eq action 'set)
  10233. (integerp action))
  10234. (if (not (eq action 'set))
  10235. (setq new action)
  10236. (setq
  10237. new
  10238. (if nump
  10239. (let ((msg (format "Priority %s-%s, SPC to remove: "
  10240. (number-to-string org-priority-highest)
  10241. (number-to-string org-priority-lowest))))
  10242. (if (< 9 org-priority-lowest)
  10243. (string-to-number (read-string msg))
  10244. (message msg)
  10245. (string-to-number (char-to-string (read-char-exclusive)))))
  10246. (progn (message "Priority %c-%c, SPC to remove: "
  10247. org-priority-highest org-priority-lowest)
  10248. (save-match-data
  10249. (setq new (read-char-exclusive)))))))
  10250. (when (and (= (upcase org-priority-highest) org-priority-highest)
  10251. (= (upcase org-priority-lowest) org-priority-lowest))
  10252. (setq new (upcase new)))
  10253. (cond ((equal new ?\s) (setq remove t))
  10254. ((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10255. (user-error
  10256. (if nump
  10257. "Priority must be between `%s' and `%s'"
  10258. "Priority must be between `%c' and `%c'")
  10259. org-priority-highest org-priority-lowest))))
  10260. ((eq action 'up)
  10261. (setq new (if have
  10262. (1- current) ; normal cycling
  10263. ;; last priority was empty
  10264. (if (eq last-command this-command)
  10265. org-priority-lowest ; wrap around empty to lowest
  10266. ;; default
  10267. (if org-priority-start-cycle-with-default
  10268. org-priority-default
  10269. (1- org-priority-default))))))
  10270. ((eq action 'down)
  10271. (setq new (if have
  10272. (1+ current) ; normal cycling
  10273. ;; last priority was empty
  10274. (if (eq last-command this-command)
  10275. org-priority-highest ; wrap around empty to highest
  10276. ;; default
  10277. (if org-priority-start-cycle-with-default
  10278. org-priority-default
  10279. (1+ org-priority-default))))))
  10280. (t (user-error "Invalid action")))
  10281. (when (or (< (upcase new) org-priority-highest)
  10282. (> (upcase new) org-priority-lowest))
  10283. (if (and (memq action '(up down))
  10284. (not have) (not (eq last-command this-command)))
  10285. ;; `new' is from default priority
  10286. (error
  10287. "The default can not be set, see `org-priority-default' why")
  10288. ;; normal cycling: `new' is beyond highest/lowest priority
  10289. ;; and is wrapped around to the empty priority
  10290. (setq remove t)))
  10291. ;; Numerical priorities are limited to 64, beyond that number,
  10292. ;; assume the priority cookie is a character.
  10293. (setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10294. (if have
  10295. (if remove
  10296. (replace-match "" t t nil 1)
  10297. (replace-match news t t nil 2))
  10298. (if remove
  10299. (user-error "No priority cookie found in line")
  10300. (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10301. (if (match-end 2)
  10302. (progn
  10303. (goto-char (match-end 2))
  10304. (insert " [#" news "]"))
  10305. (goto-char (match-beginning 3))
  10306. (insert "[#" news "] "))))
  10307. (org-align-tags))
  10308. (if remove
  10309. (message "Priority removed")
  10310. (message "Priority of current item set to %s" news)))))
  10311. (defalias 'org-show-priority 'org-priority-show)
  10312. (defun org-priority-show ()
  10313. "Show the priority of the current item.
  10314. This priority is composed of the main priority given with the [#A] cookies,
  10315. and by additional input from the age of a schedules or deadline entry."
  10316. (interactive)
  10317. (let ((pri (if (eq major-mode 'org-agenda-mode)
  10318. (org-get-at-bol 'priority)
  10319. (save-excursion
  10320. (save-match-data
  10321. (beginning-of-line)
  10322. (and (looking-at org-heading-regexp)
  10323. (org-get-priority (match-string 0))))))))
  10324. (message "Priority is %d" (if pri pri -1000))))
  10325. (defun org-get-priority (s)
  10326. "Find priority cookie and return priority.
  10327. S is a string against which you can match `org-priority-regexp'.
  10328. If `org-priority-get-priority-function' is set to a custom
  10329. function, use it. Otherwise process S and output the priority
  10330. value, an integer."
  10331. (save-match-data
  10332. (if (functionp org-priority-get-priority-function)
  10333. (funcall org-priority-get-priority-function s)
  10334. (if (not (string-match org-priority-regexp s))
  10335. (* 1000 (- org-priority-lowest org-priority-default))
  10336. (* 1000 (- org-priority-lowest
  10337. (org-priority-to-value (match-string 2 s))))))))
  10338. ;;;; Tags
  10339. (defvar org-agenda-archives-mode)
  10340. (defvar org-map-continue-from nil
  10341. "Position from where mapping should continue.
  10342. Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10343. (defvar org-scanner-tags nil
  10344. "The current tag list while the tags scanner is running.")
  10345. (defvar org-trust-scanner-tags nil
  10346. "Should `org-get-tags' use the tags for the scanner.
  10347. This is for internal dynamical scoping only.
  10348. When this is non-nil, the function `org-get-tags' will return the value
  10349. of `org-scanner-tags' instead of building the list by itself. This
  10350. can lead to large speed-ups when the tags scanner is used in a file with
  10351. many entries, and when the list of tags is retrieved, for example to
  10352. obtain a list of properties. Building the tags list for each entry in such
  10353. a file becomes an N^2 operation - but with this variable set, it scales
  10354. as N.")
  10355. (defvar org--matcher-tags-todo-only nil)
  10356. (defun org-scan-tags (action matcher todo-only &optional start-level)
  10357. "Scan headline tags with inheritance and produce output ACTION.
  10358. ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10359. or `agenda' to produce an entry list for an agenda view. It can also be
  10360. a Lisp form or a function that should be called at each matched headline, in
  10361. this case the return value is a list of all return values from these calls.
  10362. MATCHER is a function accepting three arguments, returning
  10363. a non-nil value whenever a given set of tags qualifies a headline
  10364. for inclusion. See `org-make-tags-matcher' for more information.
  10365. As a special case, it can also be set to t (respectively nil) in
  10366. order to match all (respectively none) headline.
  10367. When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10368. included in the output.
  10369. START-LEVEL can be a string with asterisks, reducing the scope to
  10370. headlines matching this string."
  10371. (require 'org-agenda)
  10372. (let* ((re (concat "^"
  10373. (if start-level
  10374. ;; Get the correct level to match
  10375. (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10376. org-outline-regexp)
  10377. " *\\(" (regexp-opt org-todo-keywords-1 'words) "\\)?"
  10378. " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10379. (props (list 'face 'default
  10380. 'done-face 'org-agenda-done
  10381. 'undone-face 'default
  10382. 'mouse-face 'highlight
  10383. 'org-not-done-regexp org-not-done-regexp
  10384. 'org-todo-regexp org-todo-regexp
  10385. 'org-complex-heading-regexp org-complex-heading-regexp
  10386. 'help-echo
  10387. (format "mouse-2 or RET jump to Org file %S"
  10388. (abbreviate-file-name
  10389. (or (buffer-file-name (buffer-base-buffer))
  10390. (buffer-name (buffer-base-buffer)))))))
  10391. (org-map-continue-from nil)
  10392. lspos tags tags-list
  10393. (tags-alist (list (cons 0 org-file-tags)))
  10394. (llast 0) rtn rtn1 level category i txt
  10395. todo marker entry priority
  10396. ts-date ts-date-type ts-date-pair)
  10397. (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10398. (setq action (list 'lambda nil action)))
  10399. (save-excursion
  10400. (goto-char (point-min))
  10401. (when (eq action 'sparse-tree)
  10402. (org-overview)
  10403. (org-remove-occur-highlights))
  10404. (while (let (case-fold-search)
  10405. (re-search-forward re nil t))
  10406. (setq org-map-continue-from nil)
  10407. (catch :skip
  10408. ;; Ignore closing parts of inline tasks.
  10409. (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  10410. (throw :skip t))
  10411. (setq todo (and (match-end 1) (match-string-no-properties 1)))
  10412. (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  10413. (goto-char (setq lspos (match-beginning 0)))
  10414. (setq level (org-reduced-level (org-outline-level))
  10415. category (org-get-category))
  10416. (when (eq action 'agenda)
  10417. (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  10418. ts-date (car ts-date-pair)
  10419. ts-date-type (cdr ts-date-pair)))
  10420. (setq i llast llast level)
  10421. ;; remove tag lists from same and sublevels
  10422. (while (>= i level)
  10423. (when (setq entry (assoc i tags-alist))
  10424. (setq tags-alist (delete entry tags-alist)))
  10425. (setq i (1- i)))
  10426. ;; add the next tags
  10427. (when tags
  10428. (setq tags (org-split-string tags ":")
  10429. tags-alist
  10430. (cons (cons level tags) tags-alist)))
  10431. ;; compile tags for current headline
  10432. (setq tags-list
  10433. (if org-use-tag-inheritance
  10434. (apply 'append (mapcar 'cdr (reverse tags-alist)))
  10435. tags)
  10436. org-scanner-tags tags-list)
  10437. (when org-use-tag-inheritance
  10438. (setcdr (car tags-alist)
  10439. (mapcar (lambda (x)
  10440. (setq x (copy-sequence x))
  10441. (org-add-prop-inherited x))
  10442. (cdar tags-alist))))
  10443. (when (and tags org-use-tag-inheritance
  10444. (or (not (eq t org-use-tag-inheritance))
  10445. org-tags-exclude-from-inheritance))
  10446. ;; Selective inheritance, remove uninherited ones.
  10447. (setcdr (car tags-alist)
  10448. (org-remove-uninherited-tags (cdar tags-alist))))
  10449. (when (and
  10450. ;; eval matcher only when the todo condition is OK
  10451. (and (or (not todo-only) (member todo org-todo-keywords-1))
  10452. (if (functionp matcher)
  10453. (let ((case-fold-search t) (org-trust-scanner-tags t))
  10454. (funcall matcher todo tags-list level))
  10455. matcher))
  10456. ;; Call the skipper, but return t if it does not
  10457. ;; skip, so that the `and' form continues evaluating.
  10458. (progn
  10459. (unless (eq action 'sparse-tree) (org-agenda-skip))
  10460. t)
  10461. ;; Check if timestamps are deselecting this entry
  10462. (or (not todo-only)
  10463. (and (member todo org-todo-keywords-1)
  10464. (or (not org-agenda-tags-todo-honor-ignore-options)
  10465. (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  10466. ;; select this headline
  10467. (cond
  10468. ((eq action 'sparse-tree)
  10469. (and org-highlight-sparse-tree-matches
  10470. (org-get-heading) (match-end 0)
  10471. (org-highlight-new-match
  10472. (match-beginning 1) (match-end 1)))
  10473. (org-show-context 'tags-tree))
  10474. ((eq action 'agenda)
  10475. (setq txt (org-agenda-format-item
  10476. ""
  10477. (concat
  10478. (if (eq org-tags-match-list-sublevels 'indented)
  10479. (make-string (1- level) ?.) "")
  10480. (org-get-heading))
  10481. (make-string level ?\s)
  10482. category
  10483. tags-list)
  10484. priority (org-get-priority txt))
  10485. (goto-char lspos)
  10486. (setq marker (org-agenda-new-marker))
  10487. (org-add-props txt props
  10488. 'org-marker marker 'org-hd-marker marker 'org-category category
  10489. 'todo-state todo
  10490. 'ts-date ts-date
  10491. 'priority priority
  10492. 'type (concat "tagsmatch" ts-date-type))
  10493. (push txt rtn))
  10494. ((functionp action)
  10495. (setq org-map-continue-from nil)
  10496. (save-excursion
  10497. (setq rtn1 (funcall action))
  10498. (push rtn1 rtn)))
  10499. (t (user-error "Invalid action")))
  10500. ;; if we are to skip sublevels, jump to end of subtree
  10501. (unless org-tags-match-list-sublevels
  10502. (org-end-of-subtree t)
  10503. (backward-char 1))))
  10504. ;; Get the correct position from where to continue
  10505. (if org-map-continue-from
  10506. (goto-char org-map-continue-from)
  10507. (and (= (point) lspos) (end-of-line 1)))))
  10508. (when (and (eq action 'sparse-tree)
  10509. (not org-sparse-tree-open-archived-trees))
  10510. (org-hide-archived-subtrees (point-min) (point-max)))
  10511. (nreverse rtn)))
  10512. (defun org-remove-uninherited-tags (tags)
  10513. "Remove all tags that are not inherited from the list TAGS."
  10514. (cond
  10515. ((eq org-use-tag-inheritance t)
  10516. (if org-tags-exclude-from-inheritance
  10517. (org-delete-all org-tags-exclude-from-inheritance tags)
  10518. tags))
  10519. ((not org-use-tag-inheritance) nil)
  10520. ((stringp org-use-tag-inheritance)
  10521. (delq nil (mapcar
  10522. (lambda (x)
  10523. (if (and (string-match org-use-tag-inheritance x)
  10524. (not (member x org-tags-exclude-from-inheritance)))
  10525. x nil))
  10526. tags)))
  10527. ((listp org-use-tag-inheritance)
  10528. (delq nil (mapcar
  10529. (lambda (x)
  10530. (if (member x org-use-tag-inheritance) x nil))
  10531. tags)))))
  10532. (defun org-match-sparse-tree (&optional todo-only match)
  10533. "Create a sparse tree according to tags string MATCH.
  10534. MATCH is a string with match syntax. It can contain a selection
  10535. of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  10536. TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  10537. those. See the manual for details.
  10538. If optional argument TODO-ONLY is non-nil, only select lines that
  10539. are also TODO tasks."
  10540. (interactive "P")
  10541. (org-agenda-prepare-buffers (list (current-buffer)))
  10542. (let ((org--matcher-tags-todo-only todo-only))
  10543. (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  10544. org--matcher-tags-todo-only)))
  10545. (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  10546. (defvar org-cached-props nil)
  10547. (defun org-cached-entry-get (pom property)
  10548. (if (or (eq t org-use-property-inheritance)
  10549. (and (stringp org-use-property-inheritance)
  10550. (let ((case-fold-search t))
  10551. (string-match-p org-use-property-inheritance property)))
  10552. (and (listp org-use-property-inheritance)
  10553. (member-ignore-case property org-use-property-inheritance)))
  10554. ;; Caching is not possible, check it directly.
  10555. (org-entry-get pom property 'inherit)
  10556. ;; Get all properties, so we can do complicated checks easily.
  10557. (cdr (assoc-string property
  10558. (or org-cached-props
  10559. (setq org-cached-props (org-entry-properties pom)))
  10560. t))))
  10561. (defun org-global-tags-completion-table (&optional files)
  10562. "Return the list of all tags in all agenda buffer/files.
  10563. Optional FILES argument is a list of files which can be used
  10564. instead of the agenda files."
  10565. (save-excursion
  10566. (org-uniquify
  10567. (delq nil
  10568. (apply #'append
  10569. (mapcar
  10570. (lambda (file)
  10571. (set-buffer (find-file-noselect file))
  10572. (org--tag-add-to-alist
  10573. (org-get-buffer-tags)
  10574. (mapcar (lambda (x)
  10575. (and (stringp (car-safe x))
  10576. (list (car-safe x))))
  10577. org-current-tag-alist)))
  10578. (if (car-safe files) files
  10579. (org-agenda-files))))))))
  10580. (defun org-make-tags-matcher (match &optional only-local-tags)
  10581. "Create the TAGS/TODO matcher form for the selection string MATCH.
  10582. Returns a cons of the selection string MATCH and a function
  10583. implementing the matcher.
  10584. The matcher is to be called at an Org entry, with point on the
  10585. headline, and returns non-nil if the entry matches the selection
  10586. string MATCH. It must be called with three arguments: the TODO
  10587. keyword at the entry (or nil if none), the list of all tags at
  10588. the entry including inherited ones and the reduced level of the
  10589. headline. Additionally, the category of the entry, if any, must
  10590. be specified as the text property `org-category' on the headline.
  10591. This function sets the variable `org--matcher-tags-todo-only' to
  10592. a non-nil value if the matcher restricts matching to TODO
  10593. entries, otherwise it is not touched.
  10594. When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  10595. table, only get buffer tags.
  10596. See also `org-scan-tags'."
  10597. (unless match
  10598. ;; Get a new match request, with completion against the global
  10599. ;; tags table and the local tags in current buffer.
  10600. (let ((org-last-tags-completion-table
  10601. (org--tag-add-to-alist
  10602. (org-get-buffer-tags)
  10603. (unless only-local-tags
  10604. (org-global-tags-completion-table)))))
  10605. (setq match
  10606. (completing-read
  10607. "Match: "
  10608. 'org-tags-completion-function nil nil nil 'org-tags-history))))
  10609. (let ((match0 match)
  10610. (re (concat
  10611. "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  10612. "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  10613. "\\([<>=]\\{1,2\\}\\)"
  10614. "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  10615. "\\|" org-tag-re "\\)"))
  10616. (start 0)
  10617. tagsmatch todomatch tagsmatcher todomatcher)
  10618. ;; Expand group tags.
  10619. (setq match (org-tags-expand match))
  10620. ;; Check if there is a TODO part of this match, which would be the
  10621. ;; part after a "/". To make sure that this slash is not part of
  10622. ;; a property value to be matched against, we also check that
  10623. ;; there is no / after that slash. First, find the last slash.
  10624. (let ((s 0))
  10625. (while (string-match "/+" match s)
  10626. (setq start (match-beginning 0))
  10627. (setq s (match-end 0))))
  10628. (if (and (string-match "/+" match start)
  10629. (not (string-match-p "\"" match start)))
  10630. ;; Match contains also a TODO-matching request.
  10631. (progn
  10632. (setq tagsmatch (substring match 0 (match-beginning 0)))
  10633. (setq todomatch (substring match (match-end 0)))
  10634. (when (string-prefix-p "!" todomatch)
  10635. (setq org--matcher-tags-todo-only t)
  10636. (setq todomatch (substring todomatch 1)))
  10637. (when (string-match "\\`\\s-*\\'" todomatch)
  10638. (setq todomatch nil)))
  10639. ;; Only matching tags.
  10640. (setq tagsmatch match)
  10641. (setq todomatch nil))
  10642. ;; Make the tags matcher.
  10643. (when (org-string-nw-p tagsmatch)
  10644. (let ((orlist nil)
  10645. (orterms (org-split-string tagsmatch "|"))
  10646. term)
  10647. (while (setq term (pop orterms))
  10648. (while (and (equal (substring term -1) "\\") orterms)
  10649. (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  10650. (while (string-match re term)
  10651. (let* ((rest (substring term (match-end 0)))
  10652. (minus (and (match-end 1)
  10653. (equal (match-string 1 term) "-")))
  10654. (tag (save-match-data
  10655. (replace-regexp-in-string
  10656. "\\\\-" "-" (match-string 2 term))))
  10657. (regexp (eq (string-to-char tag) ?{))
  10658. (levelp (match-end 4))
  10659. (propp (match-end 5))
  10660. (mm
  10661. (cond
  10662. (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  10663. (levelp
  10664. `(,(org-op-to-function (match-string 3 term))
  10665. level
  10666. ,(string-to-number (match-string 4 term))))
  10667. (propp
  10668. (let* ((gv (pcase (upcase (match-string 5 term))
  10669. ("CATEGORY"
  10670. '(get-text-property (point) 'org-category))
  10671. ("TODO" 'todo)
  10672. (p `(org-cached-entry-get nil ,p))))
  10673. (pv (match-string 7 term))
  10674. (regexp (eq (string-to-char pv) ?{))
  10675. (strp (eq (string-to-char pv) ?\"))
  10676. (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
  10677. (po (org-op-to-function (match-string 6 term)
  10678. (if timep 'time strp))))
  10679. (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  10680. (when timep (setq pv (org-matcher-time pv)))
  10681. (cond ((and regexp (eq po '/=))
  10682. `(not (string-match ,pv (or ,gv ""))))
  10683. (regexp `(string-match ,pv (or ,gv "")))
  10684. (strp `(,po (or ,gv "") ,pv))
  10685. (t
  10686. `(,po
  10687. (string-to-number (or ,gv ""))
  10688. ,(string-to-number pv))))))
  10689. (t `(member ,tag tags-list)))))
  10690. (push (if minus `(not ,mm) mm) tagsmatcher)
  10691. (setq term rest)))
  10692. (push `(and ,@tagsmatcher) orlist)
  10693. (setq tagsmatcher nil))
  10694. (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  10695. ;; Make the TODO matcher.
  10696. (when (org-string-nw-p todomatch)
  10697. (let ((orlist nil))
  10698. (dolist (term (org-split-string todomatch "|"))
  10699. (while (string-match re term)
  10700. (let* ((minus (and (match-end 1)
  10701. (equal (match-string 1 term) "-")))
  10702. (kwd (match-string 2 term))
  10703. (regexp (eq (string-to-char kwd) ?{))
  10704. (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  10705. `(equal todo ,kwd))))
  10706. (push (if minus `(not ,mm) mm) todomatcher))
  10707. (setq term (substring term (match-end 0))))
  10708. (push (if (> (length todomatcher) 1)
  10709. (cons 'and todomatcher)
  10710. (car todomatcher))
  10711. orlist)
  10712. (setq todomatcher nil))
  10713. (setq todomatcher (cons 'or orlist))))
  10714. ;; Return the string and function of the matcher. If no
  10715. ;; tags-specific or todo-specific matcher exists, match
  10716. ;; everything.
  10717. (let ((matcher (if (and tagsmatcher todomatcher)
  10718. `(and ,tagsmatcher ,todomatcher)
  10719. (or tagsmatcher todomatcher t))))
  10720. (when org--matcher-tags-todo-only
  10721. (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  10722. (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  10723. (defun org--tags-expand-group (group tag-groups expanded)
  10724. "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  10725. TAG-GROUPS is the list of groups used for expansion. EXPANDED is
  10726. an accumulator used in recursive calls."
  10727. (dolist (tag group)
  10728. (unless (member tag expanded)
  10729. (let ((group (assoc tag tag-groups)))
  10730. (push tag expanded)
  10731. (when group
  10732. (setq expanded
  10733. (org--tags-expand-group (cdr group) tag-groups expanded))))))
  10734. expanded)
  10735. (defun org-tags-expand (match &optional single-as-list)
  10736. "Expand group tags in MATCH.
  10737. This replaces every group tag in MATCH with a regexp tag search.
  10738. For example, a group tag \"Work\" defined as { Work : Lab Conf }
  10739. will be replaced like this:
  10740. Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10741. +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10742. -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  10743. Replacing by a regexp preserves the structure of the match.
  10744. E.g., this expansion
  10745. Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  10746. will match anything tagged with \"Lab\" and \"Home\", or tagged
  10747. with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  10748. A group tag in MATCH can contain regular expressions of its own.
  10749. For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  10750. will be replaced like this:
  10751. Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  10752. When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  10753. assumed to be a single group tag, and the function will return
  10754. the list of tags in this group."
  10755. (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  10756. (let ((tag-groups
  10757. (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  10758. (cond
  10759. (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  10760. (org-group-tags
  10761. (let* ((case-fold-search t)
  10762. (tag-syntax org-mode-syntax-table)
  10763. (group-keys (mapcar #'car tag-groups))
  10764. (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  10765. (return-match match))
  10766. ;; Mark regexp-expressions in the match-expression so that we
  10767. ;; do not replace them later on.
  10768. (let ((s 0))
  10769. (while (string-match "{.+?}" return-match s)
  10770. (setq s (match-end 0))
  10771. (add-text-properties
  10772. (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  10773. ;; @ and _ are allowed as word-components in tags.
  10774. (modify-syntax-entry ?@ "w" tag-syntax)
  10775. (modify-syntax-entry ?_ "w" tag-syntax)
  10776. ;; For each tag token found in MATCH, compute a regexp and it
  10777. (with-syntax-table tag-syntax
  10778. (replace-regexp-in-string
  10779. key-regexp
  10780. (lambda (m)
  10781. (if (get-text-property (match-beginning 2) 'regexp m)
  10782. m ;regexp tag: ignore
  10783. (let* ((operator (match-string 1 m))
  10784. (tag-token (let ((tag (match-string 2 m)))
  10785. (list tag)))
  10786. regexp-tags regular-tags)
  10787. ;; Partition tags between regexp and regular tags.
  10788. ;; Remove curly bracket syntax from regexp tags.
  10789. (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  10790. (save-match-data
  10791. (if (string-match "{\\(.+?\\)}" tag)
  10792. (push (match-string 1 tag) regexp-tags)
  10793. (push tag regular-tags))))
  10794. ;; Replace tag token by the appropriate regexp.
  10795. ;; Regular tags need to be regexp-quoted, whereas
  10796. ;; regexp-tags are inserted as-is.
  10797. (let ((regular (regexp-opt regular-tags))
  10798. (regexp (mapconcat #'identity regexp-tags "\\|")))
  10799. (concat operator
  10800. (cond
  10801. ((null regular-tags) (format "{%s}" regexp))
  10802. ((null regexp-tags) (format "{\\<%s\\>}" regular))
  10803. (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  10804. return-match
  10805. t t))))
  10806. (t match))))
  10807. (defun org-op-to-function (op &optional stringp)
  10808. "Turn an operator into the appropriate function."
  10809. (setq op
  10810. (cond
  10811. ((equal op "<" ) '(< org-string< org-time<))
  10812. ((equal op ">" ) '(> org-string> org-time>))
  10813. ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
  10814. ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
  10815. ((member op '("=" "==")) '(= string= org-time=))
  10816. ((member op '("<>" "!=")) '(/= org-string<> org-time<>))))
  10817. (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  10818. (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
  10819. (defvar org-tags-overlay (make-overlay 1 1))
  10820. (delete-overlay org-tags-overlay)
  10821. (defun org-add-prop-inherited (s)
  10822. (add-text-properties 0 (length s) '(inherited t) s)
  10823. s)
  10824. (defun org-toggle-tag (tag &optional onoff)
  10825. "Toggle the tag TAG for the current line.
  10826. If ONOFF is `on' or `off', don't toggle but set to this state."
  10827. (save-excursion
  10828. (org-back-to-heading t)
  10829. (let ((current
  10830. ;; Reverse the tags list so any new tag is appended to the
  10831. ;; current list of tags.
  10832. (nreverse (org-get-tags nil t)))
  10833. res)
  10834. (pcase onoff
  10835. (`off (setq current (delete tag current)))
  10836. ((or `on (guard (not (member tag current))))
  10837. (setq res t)
  10838. (cl-pushnew tag current :test #'equal))
  10839. (_ (setq current (delete tag current))))
  10840. (org-set-tags (nreverse current))
  10841. res)))
  10842. (defun org--align-tags-here (to-col)
  10843. "Align tags on the current headline to TO-COL.
  10844. Assume point is on a headline. Preserve point when aligning
  10845. tags."
  10846. (when (org-match-line org-tag-line-re)
  10847. (let* ((tags-start (match-beginning 1))
  10848. (blank-start (save-excursion
  10849. (goto-char tags-start)
  10850. (skip-chars-backward " \t")
  10851. (point)))
  10852. (new (max (if (>= to-col 0) to-col
  10853. (- (abs to-col) (string-width (match-string 1))))
  10854. ;; Introduce at least one space after the heading
  10855. ;; or the stars.
  10856. (save-excursion
  10857. (goto-char blank-start)
  10858. (1+ (current-column)))))
  10859. (current
  10860. (save-excursion (goto-char tags-start) (current-column)))
  10861. (origin (point-marker))
  10862. (column (current-column))
  10863. (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  10864. (when (/= new current)
  10865. (delete-region blank-start tags-start)
  10866. (goto-char blank-start)
  10867. (let ((indent-tabs-mode nil)) (indent-to new))
  10868. ;; Try to move back to original position. If point was in the
  10869. ;; blanks before the tags, ORIGIN marker is of no use because
  10870. ;; it now points to BLANK-START. Use COLUMN instead.
  10871. (if in-blank? (org-move-to-column column) (goto-char origin))))))
  10872. (defun org-set-tags-command (&optional arg)
  10873. "Set the tags for the current visible entry.
  10874. When called with `\\[universal-argument]' prefix argument ARG, \
  10875. realign all tags
  10876. in the current buffer.
  10877. When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  10878. unconditionally do not
  10879. offer the fast tag selection interface.
  10880. If a region is active, set tags in the region according to the
  10881. setting of `org-loop-over-headlines-in-active-region'.
  10882. This function is for interactive use only;
  10883. in Lisp code use `org-set-tags' instead."
  10884. (interactive "P")
  10885. (let ((org-use-fast-tag-selection
  10886. (unless (equal '(16) arg) org-use-fast-tag-selection)))
  10887. (cond
  10888. ((equal '(4) arg) (org-align-tags t))
  10889. ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10890. (let (org-loop-over-headlines-in-active-region) ; hint: infinite recursion.
  10891. (org-map-entries
  10892. #'org-set-tags-command
  10893. nil
  10894. (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10895. 'region-start-level
  10896. 'region)
  10897. (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  10898. (t
  10899. (save-excursion
  10900. (org-back-to-heading)
  10901. (let* ((all-tags (org-get-tags))
  10902. (table (setq org-last-tags-completion-table
  10903. (org--tag-add-to-alist
  10904. (and org-complete-tags-always-offer-all-agenda-tags
  10905. (org-global-tags-completion-table
  10906. (org-agenda-files)))
  10907. (or org-current-tag-alist (org-get-buffer-tags)))))
  10908. (current-tags
  10909. (cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  10910. all-tags))
  10911. (inherited-tags
  10912. (cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  10913. all-tags))
  10914. (tags
  10915. (replace-regexp-in-string
  10916. ;; Ignore all forbidden characters in tags.
  10917. "[^[:alnum:]_@#%]+" ":"
  10918. (if (or (eq t org-use-fast-tag-selection)
  10919. (and org-use-fast-tag-selection
  10920. (delq nil (mapcar #'cdr table))))
  10921. (org-fast-tag-selection
  10922. current-tags
  10923. inherited-tags
  10924. table
  10925. (and org-fast-tag-selection-include-todo org-todo-key-alist))
  10926. (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  10927. (crm-separator "[ \t]*:[ \t]*"))
  10928. (mapconcat #'identity
  10929. (completing-read-multiple
  10930. "Tags: "
  10931. org-last-tags-completion-table
  10932. nil nil (org-make-tag-string current-tags)
  10933. 'org-tags-history)
  10934. ":"))))))
  10935. (org-set-tags tags)))))
  10936. ;; `save-excursion' may not replace the point at the right
  10937. ;; position.
  10938. (when (and (save-excursion (skip-chars-backward "*") (bolp))
  10939. (looking-at-p " "))
  10940. (forward-char))))
  10941. (defun org-align-tags (&optional all)
  10942. "Align tags in current entry.
  10943. When optional argument ALL is non-nil, align all tags in the
  10944. visible part of the buffer."
  10945. (let ((get-indent-column
  10946. (lambda ()
  10947. (let ((offset (if (bound-and-true-p org-indent-mode)
  10948. (* (1- org-indent-indentation-per-level)
  10949. (1- (org-current-level)))
  10950. 0)))
  10951. (+ org-tags-column
  10952. (if (> org-tags-column 0) (- offset) offset))))))
  10953. (if (and (not all) (org-at-heading-p))
  10954. (org--align-tags-here (funcall get-indent-column))
  10955. (save-excursion
  10956. (if all
  10957. (progn
  10958. (goto-char (point-min))
  10959. (while (re-search-forward org-tag-line-re nil t)
  10960. (org--align-tags-here (funcall get-indent-column))))
  10961. (org-back-to-heading t)
  10962. (org--align-tags-here (funcall get-indent-column)))))))
  10963. (defun org-set-tags (tags)
  10964. "Set the tags of the current entry to TAGS, replacing current tags.
  10965. TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  10966. If TAGS is nil or the empty string, all tags are removed.
  10967. This function assumes point is on a headline."
  10968. (org-with-wide-buffer
  10969. (let ((tags (pcase tags
  10970. ((pred listp) tags)
  10971. ((pred stringp) (split-string (org-trim tags) ":" t))
  10972. (_ (error "Invalid tag specification: %S" tags))))
  10973. (old-tags (org-get-tags nil t))
  10974. (tags-change? nil))
  10975. (when (functionp org-tags-sort-function)
  10976. (setq tags (sort tags org-tags-sort-function)))
  10977. (setq tags-change? (not (equal tags old-tags)))
  10978. (when tags-change?
  10979. ;; Delete previous tags and any trailing white space.
  10980. (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  10981. (line-end-position)))
  10982. (skip-chars-backward " \t")
  10983. (delete-region (point) (line-end-position))
  10984. ;; Deleting white spaces may break an otherwise empty headline.
  10985. ;; Re-introduce one space in this case.
  10986. (unless (org-at-heading-p) (insert " "))
  10987. (when tags
  10988. (save-excursion (insert " " (org-make-tag-string tags)))
  10989. ;; When text is being inserted on an invisible region
  10990. ;; boundary, it can be inadvertently sucked into
  10991. ;; invisibility.
  10992. (unless (org-invisible-p (line-beginning-position))
  10993. (org-flag-region (point) (line-end-position) nil 'outline))))
  10994. ;; Align tags, if any.
  10995. (when tags (org-align-tags))
  10996. (when tags-change? (run-hooks 'org-after-tags-change-hook)))))
  10997. (defun org-change-tag-in-region (beg end tag off)
  10998. "Add or remove TAG for each entry in the region.
  10999. This works in the agenda, and also in an Org buffer."
  11000. (interactive
  11001. (list (region-beginning) (region-end)
  11002. (let ((org-last-tags-completion-table
  11003. (if (derived-mode-p 'org-mode)
  11004. (org--tag-add-to-alist
  11005. (org-get-buffer-tags)
  11006. (org-global-tags-completion-table))
  11007. (org-global-tags-completion-table))))
  11008. (completing-read
  11009. "Tag: " org-last-tags-completion-table nil nil nil
  11010. 'org-tags-history))
  11011. (progn
  11012. (message "[s]et or [r]emove? ")
  11013. (equal (read-char-exclusive) ?r))))
  11014. (when (fboundp 'deactivate-mark) (deactivate-mark))
  11015. (let ((agendap (equal major-mode 'org-agenda-mode))
  11016. l1 l2 m buf pos newhead (cnt 0))
  11017. (goto-char end)
  11018. (setq l2 (1- (org-current-line)))
  11019. (goto-char beg)
  11020. (setq l1 (org-current-line))
  11021. (cl-loop for l from l1 to l2 do
  11022. (org-goto-line l)
  11023. (setq m (get-text-property (point) 'org-hd-marker))
  11024. (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11025. (and agendap m))
  11026. (setq buf (if agendap (marker-buffer m) (current-buffer))
  11027. pos (if agendap m (point)))
  11028. (with-current-buffer buf
  11029. (save-excursion
  11030. (save-restriction
  11031. (goto-char pos)
  11032. (setq cnt (1+ cnt))
  11033. (org-toggle-tag tag (if off 'off 'on))
  11034. (setq newhead (org-get-heading)))))
  11035. (and agendap (org-agenda-change-all-lines newhead m))))
  11036. (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11037. (defun org-tags-completion-function (string _predicate &optional flag)
  11038. "Complete tag STRING.
  11039. FLAG specifies the type of completion operation to perform. This
  11040. function is passed as a collection function to `completing-read',
  11041. which see."
  11042. (let ((completion-ignore-case nil) ;tags are case-sensitive
  11043. (confirm (lambda (x) (stringp (car x))))
  11044. (prefix ""))
  11045. (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11046. (setq prefix (match-string 1 string))
  11047. (setq string (match-string 2 string)))
  11048. (pcase flag
  11049. (`t (all-completions string org-last-tags-completion-table confirm))
  11050. (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11051. (`nil
  11052. (pcase (try-completion string org-last-tags-completion-table confirm)
  11053. ((and completion (pred stringp))
  11054. (concat prefix
  11055. completion
  11056. (if (and org-add-colon-after-tag-completion
  11057. (assoc completion org-last-tags-completion-table))
  11058. ":"
  11059. "")))
  11060. (completion completion)))
  11061. (_ nil))))
  11062. (defun org-fast-tag-insert (kwd tags face &optional end)
  11063. "Insert KWD, and the TAGS, the latter with face FACE.
  11064. Also insert END."
  11065. (insert (format "%-12s" (concat kwd ":"))
  11066. (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11067. (or end "")))
  11068. (defun org-fast-tag-show-exit (flag)
  11069. (save-excursion
  11070. (org-goto-line 3)
  11071. (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
  11072. (replace-match ""))
  11073. (when flag
  11074. (end-of-line 1)
  11075. (org-move-to-column (- (window-width) 19) t)
  11076. (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11077. (defun org-set-current-tags-overlay (current prefix)
  11078. "Add an overlay to CURRENT tag with PREFIX."
  11079. (let ((s (org-make-tag-string current)))
  11080. (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11081. (org-overlay-display org-tags-overlay (concat prefix s))))
  11082. (defvar org-last-tag-selection-key nil)
  11083. (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11084. "Fast tag selection with single keys.
  11085. CURRENT is the current list of tags in the headline, INHERITED is the
  11086. list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11087. possibly with grouping information. TODO-TABLE is a similar table with
  11088. TODO keywords, should these have keys assigned to them.
  11089. If the keys are nil, a-z are automatically assigned.
  11090. Returns the new tags string, or nil to not change the current settings."
  11091. (let* ((fulltable (append table todo-table))
  11092. (maxlen (if (null fulltable) 0
  11093. (apply #'max
  11094. (mapcar (lambda (x)
  11095. (if (stringp (car x)) (string-width (car x))
  11096. 0))
  11097. fulltable))))
  11098. (buf (current-buffer))
  11099. (expert (eq org-fast-tag-selection-single-key 'expert))
  11100. (tab-tags nil)
  11101. (fwidth (+ maxlen 3 1 3))
  11102. (ncol (/ (- (window-width) 4) fwidth))
  11103. (i-face 'org-done)
  11104. (c-face 'org-todo)
  11105. tg cnt e c char c1 c2 ntable tbl rtn
  11106. ov-start ov-end ov-prefix
  11107. (exit-after-next org-fast-tag-selection-single-key)
  11108. (done-keywords org-done-keywords)
  11109. groups ingroup intaggroup)
  11110. (save-excursion
  11111. (beginning-of-line)
  11112. (if (looking-at org-tag-line-re)
  11113. (setq ov-start (match-beginning 1)
  11114. ov-end (match-end 1)
  11115. ov-prefix "")
  11116. (setq ov-start (1- (point-at-eol))
  11117. ov-end (1+ ov-start))
  11118. (skip-chars-forward "^\n\r")
  11119. (setq ov-prefix
  11120. (concat
  11121. (buffer-substring (1- (point)) (point))
  11122. (if (> (current-column) org-tags-column)
  11123. " "
  11124. (make-string (- org-tags-column (current-column)) ?\ ))))))
  11125. (move-overlay org-tags-overlay ov-start ov-end)
  11126. (save-excursion
  11127. (save-window-excursion
  11128. (if expert
  11129. (set-buffer (get-buffer-create " *Org tags*"))
  11130. (delete-other-windows)
  11131. (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11132. (org-switch-to-buffer-other-window " *Org tags*"))
  11133. (erase-buffer)
  11134. (setq-local org-done-keywords done-keywords)
  11135. (org-fast-tag-insert "Inherited" inherited i-face "\n")
  11136. (org-fast-tag-insert "Current" current c-face "\n\n")
  11137. (org-fast-tag-show-exit exit-after-next)
  11138. (org-set-current-tags-overlay current ov-prefix)
  11139. (setq tbl fulltable char ?a cnt 0)
  11140. (while (setq e (pop tbl))
  11141. (cond
  11142. ((eq (car e) :startgroup)
  11143. (push '() groups) (setq ingroup t)
  11144. (unless (zerop cnt)
  11145. (setq cnt 0)
  11146. (insert "\n"))
  11147. (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11148. ((eq (car e) :endgroup)
  11149. (setq ingroup nil cnt 0)
  11150. (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11151. ((eq (car e) :startgrouptag)
  11152. (setq intaggroup t)
  11153. (unless (zerop cnt)
  11154. (setq cnt 0)
  11155. (insert "\n"))
  11156. (insert "[ "))
  11157. ((eq (car e) :endgrouptag)
  11158. (setq intaggroup nil cnt 0)
  11159. (insert "]\n"))
  11160. ((equal e '(:newline))
  11161. (unless (zerop cnt)
  11162. (setq cnt 0)
  11163. (insert "\n")
  11164. (setq e (car tbl))
  11165. (while (equal (car tbl) '(:newline))
  11166. (insert "\n")
  11167. (setq tbl (cdr tbl)))))
  11168. ((equal e '(:grouptags)) (insert " : "))
  11169. (t
  11170. (setq tg (copy-sequence (car e)) c2 nil)
  11171. (if (cdr e)
  11172. (setq c (cdr e))
  11173. ;; automatically assign a character.
  11174. (setq c1 (string-to-char
  11175. (downcase (substring
  11176. tg (if (= (string-to-char tg) ?@) 1 0)))))
  11177. (if (or (rassoc c1 ntable) (rassoc c1 table))
  11178. (while (or (rassoc char ntable) (rassoc char table))
  11179. (setq char (1+ char)))
  11180. (setq c2 c1))
  11181. (setq c (or c2 char)))
  11182. (when ingroup (push tg (car groups)))
  11183. (setq tg (org-add-props tg nil 'face
  11184. (cond
  11185. ((not (assoc tg table))
  11186. (org-get-todo-face tg))
  11187. ((member tg current) c-face)
  11188. ((member tg inherited) i-face))))
  11189. (when (equal (caar tbl) :grouptags)
  11190. (org-add-props tg nil 'face 'org-tag-group))
  11191. (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
  11192. (insert "[" c "] " tg (make-string
  11193. (- fwidth 4 (length tg)) ?\ ))
  11194. (push (cons tg c) ntable)
  11195. (when (= (cl-incf cnt) ncol)
  11196. (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11197. (insert "\n")
  11198. (when (or ingroup intaggroup) (insert " ")))
  11199. (setq cnt 0)))))
  11200. (setq ntable (nreverse ntable))
  11201. (insert "\n")
  11202. (goto-char (point-min))
  11203. (unless expert (org-fit-window-to-buffer))
  11204. (setq rtn
  11205. (catch 'exit
  11206. (while t
  11207. (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11208. (if (not groups) "no " "")
  11209. (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11210. (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11211. (setq org-last-tag-selection-key c)
  11212. (cond
  11213. ((= c ?\r) (throw 'exit t))
  11214. ((= c ?!)
  11215. (setq groups (not groups))
  11216. (goto-char (point-min))
  11217. (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11218. ((= c ?\C-c)
  11219. (if (not expert)
  11220. (org-fast-tag-show-exit
  11221. (setq exit-after-next (not exit-after-next)))
  11222. (setq expert nil)
  11223. (delete-other-windows)
  11224. (set-window-buffer (split-window-vertically) " *Org tags*")
  11225. (org-switch-to-buffer-other-window " *Org tags*")
  11226. (org-fit-window-to-buffer)))
  11227. ((or (= c ?\C-g)
  11228. (and (= c ?q) (not (rassoc c ntable))))
  11229. (delete-overlay org-tags-overlay)
  11230. (setq quit-flag t))
  11231. ((= c ?\ )
  11232. (setq current nil)
  11233. (when exit-after-next (setq exit-after-next 'now)))
  11234. ((= c ?\t)
  11235. (condition-case nil
  11236. (unless tab-tags
  11237. (setq tab-tags
  11238. (delq nil
  11239. (mapcar (lambda (x)
  11240. (let ((item (car-safe x)))
  11241. (and (stringp item)
  11242. (list item))))
  11243. (org--tag-add-to-alist
  11244. (with-current-buffer buf
  11245. (org-get-buffer-tags))
  11246. table))))))
  11247. (setq tg (completing-read "Tag: " tab-tags))
  11248. (when (string-match "\\S-" tg)
  11249. (cl-pushnew (list tg) tab-tags :test #'equal)
  11250. (if (member tg current)
  11251. (setq current (delete tg current))
  11252. (push tg current)))
  11253. (when exit-after-next (setq exit-after-next 'now)))
  11254. ((setq e (rassoc c todo-table) tg (car e))
  11255. (with-current-buffer buf
  11256. (save-excursion (org-todo tg)))
  11257. (when exit-after-next (setq exit-after-next 'now)))
  11258. ((setq e (rassoc c ntable) tg (car e))
  11259. (if (member tg current)
  11260. (setq current (delete tg current))
  11261. (cl-loop for g in groups do
  11262. (when (member tg g)
  11263. (dolist (x g) (setq current (delete x current)))))
  11264. (push tg current))
  11265. (when exit-after-next (setq exit-after-next 'now))))
  11266. ;; Create a sorted list
  11267. (setq current
  11268. (sort current
  11269. (lambda (a b)
  11270. (assoc b (cdr (memq (assoc a ntable) ntable))))))
  11271. (when (eq exit-after-next 'now) (throw 'exit t))
  11272. (goto-char (point-min))
  11273. (beginning-of-line 2)
  11274. (delete-region (point) (point-at-eol))
  11275. (org-fast-tag-insert "Current" current c-face)
  11276. (org-set-current-tags-overlay current ov-prefix)
  11277. (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  11278. (while (re-search-forward tag-re nil t)
  11279. (let ((tag (match-string 1)))
  11280. (add-text-properties
  11281. (match-beginning 1) (match-end 1)
  11282. (list 'face
  11283. (cond
  11284. ((member tag current) c-face)
  11285. ((member tag inherited) i-face)
  11286. (t (get-text-property (match-beginning 1) '
  11287. face))))))))
  11288. (goto-char (point-min)))))
  11289. (delete-overlay org-tags-overlay)
  11290. (if rtn
  11291. (mapconcat 'identity current ":")
  11292. nil)))))
  11293. (defun org-make-tag-string (tags)
  11294. "Return string associated to TAGS.
  11295. TAGS is a list of strings."
  11296. (if (null tags) ""
  11297. (format ":%s:" (mapconcat #'identity tags ":"))))
  11298. (defun org--get-local-tags ()
  11299. "Return list of tags for the current headline.
  11300. Assume point is at the beginning of the headline."
  11301. (and (looking-at org-tag-line-re)
  11302. (split-string (match-string-no-properties 2) ":" t)))
  11303. (defun org-get-tags (&optional pos local)
  11304. "Get the list of tags specified in the current headline.
  11305. When argument POS is non-nil, retrieve tags for headline at POS.
  11306. According to `org-use-tag-inheritance', tags may be inherited
  11307. from parent headlines, and from the whole document, through
  11308. `org-file-tags'. In this case, the returned list of tags
  11309. contains tags in this order: file tags, tags inherited from
  11310. parent headlines, local tags. If a tag appears multiple times,
  11311. only the most local tag is returned.
  11312. However, when optional argument LOCAL is non-nil, only return
  11313. tags specified at the headline.
  11314. Inherited tags have the `inherited' text property."
  11315. (if (and org-trust-scanner-tags
  11316. (or (not pos) (eq pos (point)))
  11317. (not local))
  11318. org-scanner-tags
  11319. (org-with-point-at (or pos (point))
  11320. (unless (org-before-first-heading-p)
  11321. (org-back-to-heading t)
  11322. (let ((ltags (org--get-local-tags)) itags)
  11323. (if (or local (not org-use-tag-inheritance)) ltags
  11324. (while (org-up-heading-safe)
  11325. (setq itags (nconc (mapcar #'org-add-prop-inherited
  11326. (org--get-local-tags))
  11327. itags)))
  11328. (setq itags (append org-file-tags itags))
  11329. (nreverse
  11330. (delete-dups
  11331. (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  11332. (defun org-get-buffer-tags ()
  11333. "Get a table of all tags used in the buffer, for completion."
  11334. (org-with-point-at 1
  11335. (let (tags)
  11336. (while (re-search-forward org-tag-line-re nil t)
  11337. (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  11338. tags)))
  11339. (mapcar #'list (delete-dups (append org-file-tags tags))))))
  11340. ;;;; The mapping API
  11341. (defvar org-agenda-skip-comment-trees)
  11342. (defvar org-agenda-skip-function)
  11343. (defun org-map-entries (func &optional match scope &rest skip)
  11344. "Call FUNC at each headline selected by MATCH in SCOPE.
  11345. FUNC is a function or a Lisp form. The function will be called without
  11346. arguments, with the cursor positioned at the beginning of the headline.
  11347. The return values of all calls to the function will be collected and
  11348. returned as a list.
  11349. The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  11350. does not need to preserve point. After evaluation, the cursor will be
  11351. moved to the end of the line (presumably of the headline of the
  11352. processed entry) and search continues from there. Under some
  11353. circumstances, this may not produce the wanted results. For example,
  11354. if you have removed (e.g. archived) the current (sub)tree it could
  11355. mean that the next entry will be skipped entirely. In such cases, you
  11356. can specify the position from where search should continue by making
  11357. FUNC set the variable `org-map-continue-from' to the desired buffer
  11358. position.
  11359. MATCH is a tags/property/todo match as it is used in the agenda tags view.
  11360. Only headlines that are matched by this query will be considered during
  11361. the iteration. When MATCH is nil or t, all headlines will be
  11362. visited by the iteration.
  11363. SCOPE determines the scope of this command. It can be any of:
  11364. nil The current buffer, respecting the restriction if any
  11365. tree The subtree started with the entry at point
  11366. region The entries within the active region, if any
  11367. region-start-level
  11368. The entries within the active region, but only those at
  11369. the same level than the first one.
  11370. file The current buffer, without restriction
  11371. file-with-archives
  11372. The current buffer, and any archives associated with it
  11373. agenda All agenda files
  11374. agenda-with-archives
  11375. All agenda files with any archive files associated with them
  11376. \(file1 file2 ...)
  11377. If this is a list, all files in the list will be scanned
  11378. The remaining args are treated as settings for the skipping facilities of
  11379. the scanner. The following items can be given here:
  11380. archive skip trees with the archive tag
  11381. comment skip trees with the COMMENT keyword
  11382. function or Emacs Lisp form:
  11383. will be used as value for `org-agenda-skip-function', so
  11384. whenever the function returns a position, FUNC will not be
  11385. called for that entry and search will continue from the
  11386. position returned
  11387. If your function needs to retrieve the tags including inherited tags
  11388. at the *current* entry, you can use the value of the variable
  11389. `org-scanner-tags' which will be much faster than getting the value
  11390. with `org-get-tags'. If your function gets properties with
  11391. `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  11392. to t around the call to `org-entry-properties' to get the same speedup.
  11393. Note that if your function moves around to retrieve tags and properties at
  11394. a *different* entry, you cannot use these techniques."
  11395. (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  11396. (not (org-region-active-p)))
  11397. (let* ((org-agenda-archives-mode nil) ; just to make sure
  11398. (org-agenda-skip-archived-trees (memq 'archive skip))
  11399. (org-agenda-skip-comment-trees (memq 'comment skip))
  11400. (org-agenda-skip-function
  11401. (car (org-delete-all '(comment archive) skip)))
  11402. (org-tags-match-list-sublevels t)
  11403. (start-level (eq scope 'region-start-level))
  11404. matcher res
  11405. org-todo-keywords-for-agenda
  11406. org-done-keywords-for-agenda
  11407. org-todo-keyword-alist-for-agenda
  11408. org-tag-alist-for-agenda
  11409. org--matcher-tags-todo-only)
  11410. (cond
  11411. ((eq match t) (setq matcher t))
  11412. ((eq match nil) (setq matcher t))
  11413. (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  11414. (save-excursion
  11415. (save-restriction
  11416. (cond ((eq scope 'tree)
  11417. (org-back-to-heading t)
  11418. (org-narrow-to-subtree)
  11419. (setq scope nil))
  11420. ((and (or (eq scope 'region) (eq scope 'region-start-level))
  11421. (org-region-active-p))
  11422. ;; If needed, set start-level to a string like "2"
  11423. (when start-level
  11424. (save-excursion
  11425. (goto-char (region-beginning))
  11426. (unless (org-at-heading-p) (outline-next-heading))
  11427. (setq start-level (org-current-level))))
  11428. (narrow-to-region (region-beginning)
  11429. (save-excursion
  11430. (goto-char (region-end))
  11431. (unless (and (bolp) (org-at-heading-p))
  11432. (outline-next-heading))
  11433. (point)))
  11434. (setq scope nil)))
  11435. (if (not scope)
  11436. (progn
  11437. (org-agenda-prepare-buffers
  11438. (and buffer-file-name (list buffer-file-name)))
  11439. (setq res
  11440. (org-scan-tags
  11441. func matcher org--matcher-tags-todo-only start-level)))
  11442. ;; Get the right scope
  11443. (cond
  11444. ((and scope (listp scope) (symbolp (car scope)))
  11445. (setq scope (eval scope)))
  11446. ((eq scope 'agenda)
  11447. (setq scope (org-agenda-files t)))
  11448. ((eq scope 'agenda-with-archives)
  11449. (setq scope (org-agenda-files t))
  11450. (setq scope (org-add-archive-files scope)))
  11451. ((eq scope 'file)
  11452. (setq scope (and buffer-file-name (list buffer-file-name))))
  11453. ((eq scope 'file-with-archives)
  11454. (setq scope (org-add-archive-files (list (buffer-file-name))))))
  11455. (org-agenda-prepare-buffers scope)
  11456. (dolist (file scope)
  11457. (with-current-buffer (org-find-base-buffer-visiting file)
  11458. (org-with-wide-buffer
  11459. (goto-char (point-min))
  11460. (setq res
  11461. (append
  11462. res
  11463. (org-scan-tags
  11464. func matcher org--matcher-tags-todo-only)))))))))
  11465. res)))
  11466. ;;; Properties API
  11467. (defconst org-special-properties
  11468. '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  11469. "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  11470. "The special properties valid in Org mode.
  11471. These are properties that are not defined in the property drawer,
  11472. but in some other way.")
  11473. (defconst org-default-properties
  11474. '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  11475. "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  11476. "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  11477. "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  11478. "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  11479. "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  11480. "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
  11481. "Some properties that are used by Org mode for various purposes.
  11482. Being in this list makes sure that they are offered for completion.")
  11483. (defun org--valid-property-p (property)
  11484. "Non-nil when string PROPERTY is a valid property name."
  11485. (not
  11486. (or (equal property "")
  11487. (string-match-p "\\s-" property))))
  11488. (defun org--update-property-plist (key val props)
  11489. "Associate KEY to VAL in alist PROPS.
  11490. Modifications are made by side-effect. Return new alist."
  11491. (let* ((appending (string= (substring key -1) "+"))
  11492. (key (if appending (substring key 0 -1) key))
  11493. (old (assoc-string key props t)))
  11494. (if (not old) (cons (cons key val) props)
  11495. (setcdr old (if appending (concat (cdr old) " " val) val))
  11496. props)))
  11497. (defun org-get-property-block (&optional beg force)
  11498. "Return the (beg . end) range of the body of the property drawer.
  11499. BEG is the beginning of the current subtree or the beginning of
  11500. the document if before the first headline. If it is not given,
  11501. it will be found. If the drawer does not exist, create it if
  11502. FORCE is non-nil, or return nil."
  11503. (org-with-wide-buffer
  11504. (let ((beg (cond (beg (goto-char beg))
  11505. ((or (not (featurep 'org-inlinetask))
  11506. (org-inlinetask-in-task-p))
  11507. (org-back-to-heading-or-point-min t) (point))
  11508. (t (org-with-limited-levels
  11509. (org-back-to-heading-or-point-min t))
  11510. (point)))))
  11511. ;; Move point to its position according to its positional rules.
  11512. (cond ((org-before-first-heading-p)
  11513. (while (and (org-at-comment-p) (bolp)) (forward-line)))
  11514. (t (forward-line)
  11515. (when (looking-at-p org-planning-line-re) (forward-line))))
  11516. (cond ((looking-at org-property-drawer-re)
  11517. (forward-line)
  11518. (cons (point) (progn (goto-char (match-end 0))
  11519. (line-beginning-position))))
  11520. (force
  11521. (goto-char beg)
  11522. (org-insert-property-drawer)
  11523. (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  11524. (line-beginning-position))))
  11525. (cons pos pos)))))))
  11526. (defun org-at-property-drawer-p ()
  11527. "Non-nil when point is at the first line of a property drawer."
  11528. (org-with-wide-buffer
  11529. (beginning-of-line)
  11530. (and (looking-at org-property-drawer-re)
  11531. (or (bobp)
  11532. (progn
  11533. (forward-line -1)
  11534. (cond ((org-at-heading-p))
  11535. ((looking-at org-planning-line-re)
  11536. (forward-line -1)
  11537. (org-at-heading-p))
  11538. ((looking-at org-comment-regexp)
  11539. (forward-line -1)
  11540. (while (and (not (bobp)) (looking-at org-comment-regexp))
  11541. (forward-line -1))
  11542. (looking-at org-comment-regexp))
  11543. (t nil)))))))
  11544. (defun org-at-property-p ()
  11545. "Non-nil when point is inside a property drawer.
  11546. See `org-property-re' for match data, if applicable."
  11547. (save-excursion
  11548. (beginning-of-line)
  11549. (and (looking-at org-property-re)
  11550. (let ((property-drawer (save-match-data (org-get-property-block))))
  11551. (and property-drawer
  11552. (>= (point) (car property-drawer))
  11553. (< (point) (cdr property-drawer)))))))
  11554. (defun org-property-action ()
  11555. "Do an action on properties."
  11556. (interactive)
  11557. (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
  11558. (let ((c (read-char-exclusive)))
  11559. (cl-case c
  11560. (?s (call-interactively #'org-set-property))
  11561. (?d (call-interactively #'org-delete-property))
  11562. (?D (call-interactively #'org-delete-property-globally))
  11563. (?c (call-interactively #'org-compute-property-at-point))
  11564. (otherwise (user-error "No such property action %c" c)))))
  11565. (defun org-inc-effort ()
  11566. "Increment the value of the effort property in the current entry."
  11567. (interactive)
  11568. (org-set-effort t))
  11569. (defvar org-clock-effort) ; Defined in org-clock.el.
  11570. (defvar org-clock-current-task) ; Defined in org-clock.el.
  11571. (defun org-set-effort (&optional increment value)
  11572. "Set the effort property of the current entry.
  11573. If INCREMENT is non-nil, set the property to the next allowed
  11574. value. Otherwise, if optional argument VALUE is provided, use
  11575. it. Eventually, prompt for the new value if none of the previous
  11576. variables is set."
  11577. (interactive "P")
  11578. (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  11579. (current (org-entry-get nil org-effort-property))
  11580. (value
  11581. (cond
  11582. (increment
  11583. (unless allowed (user-error "Allowed effort values are not set"))
  11584. (or (cl-caadr (member (list current) allowed))
  11585. (user-error "Unknown value %S among allowed values" current)))
  11586. (value
  11587. (if (stringp value) value
  11588. (error "Invalid effort value: %S" value)))
  11589. (t
  11590. (let ((must-match
  11591. (and allowed
  11592. (not (get-text-property 0 'org-unrestricted
  11593. (caar allowed))))))
  11594. (completing-read "Effort: " allowed nil must-match))))))
  11595. ;; Test whether the value can be interpreted as a duration before
  11596. ;; inserting it in the buffer:
  11597. (org-duration-to-minutes value)
  11598. ;; Maybe update the effort value:
  11599. (unless (equal current value)
  11600. (org-entry-put nil org-effort-property value))
  11601. (org-refresh-property '((effort . identity)
  11602. (effort-minutes . org-duration-to-minutes))
  11603. value)
  11604. (when (equal (org-get-heading t t t t)
  11605. (bound-and-true-p org-clock-current-task))
  11606. (setq org-clock-effort value)
  11607. (org-clock-update-mode-line))
  11608. (message "%s is now %s" org-effort-property value)))
  11609. (defun org-entry-properties (&optional pom which)
  11610. "Get all properties of the current entry.
  11611. When POM is a buffer position, get all properties from the entry
  11612. there instead.
  11613. This includes the TODO keyword, the tags, time strings for
  11614. deadline, scheduled, and clocking, and any additional properties
  11615. defined in the entry.
  11616. If WHICH is nil or `all', get all properties. If WHICH is
  11617. `special' or `standard', only get that subclass. If WHICH is
  11618. a string, only get that property.
  11619. Return value is an alist. Keys are properties, as upcased
  11620. strings."
  11621. (org-with-point-at pom
  11622. (when (and (derived-mode-p 'org-mode)
  11623. (org-back-to-heading-or-point-min t))
  11624. (catch 'exit
  11625. (let* ((beg (point))
  11626. (specific (and (stringp which) (upcase which)))
  11627. (which (cond ((not specific) which)
  11628. ((member specific org-special-properties) 'special)
  11629. (t 'standard)))
  11630. props)
  11631. ;; Get the special properties, like TODO and TAGS.
  11632. (when (memq which '(nil all special))
  11633. (when (or (not specific) (string= specific "CLOCKSUM"))
  11634. (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  11635. (when clocksum
  11636. (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  11637. props)))
  11638. (when specific (throw 'exit props)))
  11639. (when (or (not specific) (string= specific "CLOCKSUM_T"))
  11640. (let ((clocksumt (get-text-property (point)
  11641. :org-clock-minutes-today)))
  11642. (when clocksumt
  11643. (push (cons "CLOCKSUM_T"
  11644. (org-duration-from-minutes clocksumt))
  11645. props)))
  11646. (when specific (throw 'exit props)))
  11647. (when (or (not specific) (string= specific "ITEM"))
  11648. (let ((case-fold-search nil))
  11649. (when (looking-at org-complex-heading-regexp)
  11650. (push (cons "ITEM"
  11651. (let ((title (match-string-no-properties 4)))
  11652. (if (org-string-nw-p title)
  11653. (org-remove-tabs title)
  11654. "")))
  11655. props)))
  11656. (when specific (throw 'exit props)))
  11657. (when (or (not specific) (string= specific "TODO"))
  11658. (let ((case-fold-search nil))
  11659. (when (and (looking-at org-todo-line-regexp) (match-end 2))
  11660. (push (cons "TODO" (match-string-no-properties 2)) props)))
  11661. (when specific (throw 'exit props)))
  11662. (when (or (not specific) (string= specific "PRIORITY"))
  11663. (push (cons "PRIORITY"
  11664. (if (looking-at org-priority-regexp)
  11665. (match-string-no-properties 2)
  11666. (char-to-string org-priority-default)))
  11667. props)
  11668. (when specific (throw 'exit props)))
  11669. (when (or (not specific) (string= specific "FILE"))
  11670. (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  11671. props)
  11672. (when specific (throw 'exit props)))
  11673. (when (or (not specific) (string= specific "TAGS"))
  11674. (let ((tags (org-get-tags nil t)))
  11675. (when tags
  11676. (push (cons "TAGS" (org-make-tag-string tags))
  11677. props)))
  11678. (when specific (throw 'exit props)))
  11679. (when (or (not specific) (string= specific "ALLTAGS"))
  11680. (let ((tags (org-get-tags)))
  11681. (when tags
  11682. (push (cons "ALLTAGS" (org-make-tag-string tags))
  11683. props)))
  11684. (when specific (throw 'exit props)))
  11685. (when (or (not specific) (string= specific "BLOCKED"))
  11686. (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  11687. (when specific (throw 'exit props)))
  11688. (when (or (not specific)
  11689. (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  11690. (forward-line)
  11691. (when (looking-at-p org-planning-line-re)
  11692. (end-of-line)
  11693. (let ((bol (line-beginning-position))
  11694. ;; Backward compatibility: time keywords used to
  11695. ;; be configurable (before 8.3). Make sure we
  11696. ;; get the correct keyword.
  11697. (key-assoc `(("CLOSED" . ,org-closed-string)
  11698. ("DEADLINE" . ,org-deadline-string)
  11699. ("SCHEDULED" . ,org-scheduled-string))))
  11700. (dolist (pair (if specific (list (assoc specific key-assoc))
  11701. key-assoc))
  11702. (save-excursion
  11703. (when (search-backward (cdr pair) bol t)
  11704. (goto-char (match-end 0))
  11705. (skip-chars-forward " \t")
  11706. (and (looking-at org-ts-regexp-both)
  11707. (push (cons (car pair)
  11708. (match-string-no-properties 0))
  11709. props)))))))
  11710. (when specific (throw 'exit props)))
  11711. (when (or (not specific)
  11712. (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  11713. (let ((find-ts
  11714. (lambda (end ts)
  11715. ;; Fix next time-stamp before END. TS is the
  11716. ;; list of time-stamps found so far.
  11717. (let ((ts ts)
  11718. (regexp (cond
  11719. ((string= specific "TIMESTAMP")
  11720. org-ts-regexp)
  11721. ((string= specific "TIMESTAMP_IA")
  11722. org-ts-regexp-inactive)
  11723. ((assoc "TIMESTAMP_IA" ts)
  11724. org-ts-regexp)
  11725. ((assoc "TIMESTAMP" ts)
  11726. org-ts-regexp-inactive)
  11727. (t org-ts-regexp-both))))
  11728. (catch 'next
  11729. (while (re-search-forward regexp end t)
  11730. (backward-char)
  11731. (let ((object (org-element-context)))
  11732. ;; Accept to match timestamps in node
  11733. ;; properties, too.
  11734. (when (memq (org-element-type object)
  11735. '(node-property timestamp))
  11736. (let ((type
  11737. (org-element-property :type object)))
  11738. (cond
  11739. ((and (memq type '(active active-range))
  11740. (not (equal specific "TIMESTAMP_IA")))
  11741. (unless (assoc "TIMESTAMP" ts)
  11742. (push (cons "TIMESTAMP"
  11743. (org-element-property
  11744. :raw-value object))
  11745. ts)
  11746. (when specific (throw 'exit ts))))
  11747. ((and (memq type '(inactive inactive-range))
  11748. (not (string= specific "TIMESTAMP")))
  11749. (unless (assoc "TIMESTAMP_IA" ts)
  11750. (push (cons "TIMESTAMP_IA"
  11751. (org-element-property
  11752. :raw-value object))
  11753. ts)
  11754. (when specific (throw 'exit ts))))))
  11755. ;; Both timestamp types are found,
  11756. ;; move to next part.
  11757. (when (= (length ts) 2) (throw 'next ts)))))
  11758. ts)))))
  11759. (goto-char beg)
  11760. ;; First look for timestamps within headline.
  11761. (let ((ts (funcall find-ts (line-end-position) nil)))
  11762. (if (= (length ts) 2) (setq props (nconc ts props))
  11763. ;; Then find timestamps in the section, skipping
  11764. ;; planning line.
  11765. (let ((end (save-excursion (outline-next-heading))))
  11766. (forward-line)
  11767. (when (looking-at-p org-planning-line-re) (forward-line))
  11768. (setq props (nconc (funcall find-ts end ts) props))))))))
  11769. ;; Get the standard properties, like :PROP:.
  11770. (when (memq which '(nil all standard))
  11771. ;; If we are looking after a specific property, delegate
  11772. ;; to `org-entry-get', which is faster. However, make an
  11773. ;; exception for "CATEGORY", since it can be also set
  11774. ;; through keywords (i.e. #+CATEGORY).
  11775. (if (and specific (not (equal specific "CATEGORY")))
  11776. (let ((value (org-entry-get beg specific nil t)))
  11777. (throw 'exit (and value (list (cons specific value)))))
  11778. (let ((range (org-get-property-block beg)))
  11779. (when range
  11780. (let ((end (cdr range)) seen-base)
  11781. (goto-char (car range))
  11782. ;; Unlike to `org--update-property-plist', we
  11783. ;; handle the case where base values is found
  11784. ;; after its extension. We also forbid standard
  11785. ;; properties to be named as special properties.
  11786. (while (re-search-forward org-property-re end t)
  11787. (let* ((key (upcase (match-string-no-properties 2)))
  11788. (extendp (string-match-p "\\+\\'" key))
  11789. (key-base (if extendp (substring key 0 -1) key))
  11790. (value (match-string-no-properties 3)))
  11791. (cond
  11792. ((member-ignore-case key-base org-special-properties))
  11793. (extendp
  11794. (setq props
  11795. (org--update-property-plist key value props)))
  11796. ((member key seen-base))
  11797. (t (push key seen-base)
  11798. (let ((p (assoc-string key props t)))
  11799. (if p (setcdr p (concat value " " (cdr p)))
  11800. (push (cons key value) props))))))))))))
  11801. (unless (assoc "CATEGORY" props)
  11802. (push (cons "CATEGORY" (org-get-category beg)) props)
  11803. (when (string= specific "CATEGORY") (throw 'exit props)))
  11804. ;; Return value.
  11805. props)))))
  11806. (defun org--property-local-values (property literal-nil)
  11807. "Return value for PROPERTY in current entry.
  11808. Value is a list whose car is the base value for PROPERTY and cdr
  11809. a list of accumulated values. Return nil if neither is found in
  11810. the entry. Also return nil when PROPERTY is set to \"nil\",
  11811. unless LITERAL-NIL is non-nil."
  11812. (let ((range (org-get-property-block)))
  11813. (when range
  11814. (goto-char (car range))
  11815. (let* ((case-fold-search t)
  11816. (end (cdr range))
  11817. (value
  11818. ;; Base value.
  11819. (save-excursion
  11820. (let ((v (and (re-search-forward
  11821. (org-re-property property nil t) end t)
  11822. (match-string-no-properties 3))))
  11823. (list (if literal-nil v (org-not-nil v)))))))
  11824. ;; Find additional values.
  11825. (let* ((property+ (org-re-property (concat property "+") nil t)))
  11826. (while (re-search-forward property+ end t)
  11827. (push (match-string-no-properties 3) value)))
  11828. ;; Return final values.
  11829. (and (not (equal value '(nil))) (nreverse value))))))
  11830. (defun org--property-global-or-keyword-value (property literal-nil)
  11831. "Return value for PROPERTY as defined by global properties or by keyword.
  11832. Return value is a string. Return nil if property is not set
  11833. globally or by keyword. Also return nil when PROPERTY is set to
  11834. \"nil\", unless LITERAL-NIL is non-nil."
  11835. (let ((global
  11836. (cdr (or (assoc-string property org-keyword-properties t)
  11837. (assoc-string property org-global-properties t)
  11838. (assoc-string property org-global-properties-fixed t)))))
  11839. (if literal-nil global (org-not-nil global))))
  11840. (defun org-entry-get (pom property &optional inherit literal-nil)
  11841. "Get value of PROPERTY for entry or content at point-or-marker POM.
  11842. If INHERIT is non-nil and the entry does not have the property,
  11843. then also check higher levels of the hierarchy. If INHERIT is
  11844. the symbol `selective', use inheritance only if the setting in
  11845. `org-use-property-inheritance' selects PROPERTY for inheritance.
  11846. If the property is present but empty, the return value is the
  11847. empty string. If the property is not present at all, nil is
  11848. returned. In any other case, return the value as a string.
  11849. Search is case-insensitive.
  11850. If LITERAL-NIL is set, return the string value \"nil\" as
  11851. a string, do not interpret it as the list atom nil. This is used
  11852. for inheritance when a \"nil\" value can supersede a non-nil
  11853. value higher up the hierarchy."
  11854. (org-with-point-at pom
  11855. (cond
  11856. ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  11857. ;; We need a special property. Use `org-entry-properties' to
  11858. ;; retrieve it, but specify the wanted property.
  11859. (cdr (assoc-string property (org-entry-properties nil property))))
  11860. ((and inherit
  11861. (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  11862. (org-entry-get-with-inheritance property literal-nil))
  11863. (t
  11864. (let* ((local (org--property-local-values property literal-nil))
  11865. (value (and local (mapconcat #'identity (delq nil local) " "))))
  11866. (if literal-nil value (org-not-nil value)))))))
  11867. (defun org-property-or-variable-value (var &optional inherit)
  11868. "Check if there is a property fixing the value of VAR.
  11869. If yes, return this value. If not, return the current value of the variable."
  11870. (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  11871. (if (and prop (stringp prop) (string-match "\\S-" prop))
  11872. (read prop)
  11873. (symbol-value var))))
  11874. (defun org-entry-delete (pom property)
  11875. "Delete PROPERTY from entry at point-or-marker POM.
  11876. Accumulated properties, i.e. PROPERTY+, are also removed. Return
  11877. non-nil when a property was removed."
  11878. (org-with-point-at pom
  11879. (pcase (org-get-property-block)
  11880. (`(,begin . ,origin)
  11881. (let* ((end (copy-marker origin))
  11882. (re (org-re-property
  11883. (concat (regexp-quote property) "\\+?") t t)))
  11884. (goto-char begin)
  11885. (while (re-search-forward re end t)
  11886. (delete-region (match-beginning 0) (line-beginning-position 2)))
  11887. ;; If drawer is empty, remove it altogether.
  11888. (when (= begin end)
  11889. (delete-region (line-beginning-position 0)
  11890. (line-beginning-position 2)))
  11891. ;; Return non-nil if some property was removed.
  11892. (prog1 (/= end origin) (set-marker end nil))))
  11893. (_ nil))))
  11894. ;; Multi-values properties are properties that contain multiple values
  11895. ;; These values are assumed to be single words, separated by whitespace.
  11896. (defun org-entry-add-to-multivalued-property (pom property value)
  11897. "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  11898. (let* ((old (org-entry-get pom property))
  11899. (values (and old (split-string old))))
  11900. (setq value (org-entry-protect-space value))
  11901. (unless (member value values)
  11902. (setq values (append values (list value)))
  11903. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11904. (defun org-entry-remove-from-multivalued-property (pom property value)
  11905. "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  11906. (let* ((old (org-entry-get pom property))
  11907. (values (and old (split-string old))))
  11908. (setq value (org-entry-protect-space value))
  11909. (when (member value values)
  11910. (setq values (delete value values))
  11911. (org-entry-put pom property (mapconcat #'identity values " ")))))
  11912. (defun org-entry-member-in-multivalued-property (pom property value)
  11913. "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  11914. (let* ((old (org-entry-get pom property))
  11915. (values (and old (split-string old))))
  11916. (setq value (org-entry-protect-space value))
  11917. (member value values)))
  11918. (defun org-entry-get-multivalued-property (pom property)
  11919. "Return a list of values in a multivalued property."
  11920. (let* ((value (org-entry-get pom property))
  11921. (values (and value (split-string value))))
  11922. (mapcar #'org-entry-restore-space values)))
  11923. (defun org-entry-put-multivalued-property (pom property &rest values)
  11924. "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  11925. VALUES should be a list of strings. Spaces will be protected."
  11926. (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  11927. (let* ((value (org-entry-get pom property))
  11928. (values (and value (split-string value))))
  11929. (mapcar #'org-entry-restore-space values)))
  11930. (defun org-entry-protect-space (s)
  11931. "Protect spaces and newline in string S."
  11932. (while (string-match " " s)
  11933. (setq s (replace-match "%20" t t s)))
  11934. (while (string-match "\n" s)
  11935. (setq s (replace-match "%0A" t t s)))
  11936. s)
  11937. (defun org-entry-restore-space (s)
  11938. "Restore spaces and newline in string S."
  11939. (while (string-match "%20" s)
  11940. (setq s (replace-match " " t t s)))
  11941. (while (string-match "%0A" s)
  11942. (setq s (replace-match "\n" t t s)))
  11943. s)
  11944. (defvar org-entry-property-inherited-from (make-marker)
  11945. "Marker pointing to the entry from where a property was inherited.
  11946. Each call to `org-entry-get-with-inheritance' will set this marker to the
  11947. location of the entry where the inheritance search matched. If there was
  11948. no match, the marker will point nowhere.
  11949. Note that also `org-entry-get' calls this function, if the INHERIT flag
  11950. is set.")
  11951. (defun org-entry-get-with-inheritance (property &optional literal-nil)
  11952. "Get PROPERTY of entry or content at point, search higher levels if needed.
  11953. The search will stop at the first ancestor which has the property defined.
  11954. If the value found is \"nil\", return nil to show that the property
  11955. should be considered as undefined (this is the meaning of nil here).
  11956. However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  11957. (move-marker org-entry-property-inherited-from nil)
  11958. (org-with-wide-buffer
  11959. (let (value)
  11960. (catch 'exit
  11961. (while t
  11962. (let ((v (org--property-local-values property literal-nil)))
  11963. (when v
  11964. (setq value
  11965. (concat (mapconcat #'identity (delq nil v) " ")
  11966. (and value " ")
  11967. value)))
  11968. (cond
  11969. ((car v)
  11970. (org-back-to-heading-or-point-min t)
  11971. (move-marker org-entry-property-inherited-from (point))
  11972. (throw 'exit nil))
  11973. ((org-up-heading-or-point-min))
  11974. (t
  11975. (let ((global (org--property-global-or-keyword-value property literal-nil)))
  11976. (cond ((not global))
  11977. (value (setq value (concat global " " value)))
  11978. (t (setq value global))))
  11979. (throw 'exit nil))))))
  11980. (if literal-nil value (org-not-nil value)))))
  11981. (defvar org-property-changed-functions nil
  11982. "Hook called when the value of a property has changed.
  11983. Each hook function should accept two arguments, the name of the property
  11984. and the new value.")
  11985. (defun org-entry-put (pom property value)
  11986. "Set PROPERTY to VALUE for entry at point-or-marker POM.
  11987. If the value is nil, it is converted to the empty string. If it
  11988. is not a string, an error is raised. Also raise an error on
  11989. invalid property names.
  11990. PROPERTY can be any regular property (see
  11991. `org-special-properties'). It can also be \"TODO\",
  11992. \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  11993. For the last two properties, VALUE may have any of the special
  11994. values \"earlier\" and \"later\". The function then increases or
  11995. decreases scheduled or deadline date by one day."
  11996. (cond ((null value) (setq value ""))
  11997. ((not (stringp value)) (error "Properties values should be strings"))
  11998. ((not (org--valid-property-p property))
  11999. (user-error "Invalid property name: \"%s\"" property)))
  12000. (org-no-read-only
  12001. (org-with-point-at pom
  12002. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12003. (org-back-to-heading-or-point-min t)
  12004. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12005. (let ((beg (point)))
  12006. (cond
  12007. ((equal property "TODO")
  12008. (cond ((not (org-string-nw-p value)) (setq value 'none))
  12009. ((not (member value org-todo-keywords-1))
  12010. (user-error "\"%s\" is not a valid TODO state" value)))
  12011. (org-todo value)
  12012. (org-align-tags))
  12013. ((equal property "PRIORITY")
  12014. (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12015. (org-align-tags))
  12016. ((equal property "SCHEDULED")
  12017. (forward-line)
  12018. (if (and (looking-at-p org-planning-line-re)
  12019. (re-search-forward
  12020. org-scheduled-time-regexp (line-end-position) t))
  12021. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12022. ((string= value "later") (org-timestamp-change 1 'day))
  12023. ((string= value "") (org-schedule '(4)))
  12024. (t (org-schedule nil value)))
  12025. (if (member value '("earlier" "later" ""))
  12026. (call-interactively #'org-schedule)
  12027. (org-schedule nil value))))
  12028. ((equal property "DEADLINE")
  12029. (forward-line)
  12030. (if (and (looking-at-p org-planning-line-re)
  12031. (re-search-forward
  12032. org-deadline-time-regexp (line-end-position) t))
  12033. (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12034. ((string= value "later") (org-timestamp-change 1 'day))
  12035. ((string= value "") (org-deadline '(4)))
  12036. (t (org-deadline nil value)))
  12037. (if (member value '("earlier" "later" ""))
  12038. (call-interactively #'org-deadline)
  12039. (org-deadline nil value))))
  12040. ((member property org-special-properties)
  12041. (error "The %s property cannot be set with `org-entry-put'" property))
  12042. (t
  12043. (let* ((range (org-get-property-block beg 'force))
  12044. (end (cdr range))
  12045. (case-fold-search t))
  12046. (goto-char (car range))
  12047. (if (re-search-forward (org-re-property property nil t) end t)
  12048. (progn (delete-region (match-beginning 0) (match-end 0))
  12049. (goto-char (match-beginning 0)))
  12050. (goto-char end)
  12051. (insert "\n")
  12052. (backward-char))
  12053. (insert ":" property ":")
  12054. (when value (insert " " value))
  12055. (org-indent-line)))))
  12056. (run-hook-with-args 'org-property-changed-functions property value))))
  12057. (defun org-buffer-property-keys (&optional specials defaults columns)
  12058. "Get all property keys in the current buffer.
  12059. When SPECIALS is non-nil, also list the special properties that
  12060. reflect things like tags and TODO state.
  12061. When DEFAULTS is non-nil, also include properties that has
  12062. special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12063. DESCRIPTION, LOCATION, and LOGGING and others.
  12064. When COLUMNS in non-nil, also include property names given in
  12065. COLUMN formats in the current buffer."
  12066. (let ((case-fold-search t)
  12067. (props (append
  12068. (and specials org-special-properties)
  12069. (and defaults (cons org-effort-property org-default-properties))
  12070. ;; Get property names from #+PROPERTY keywords as well
  12071. (mapcar (lambda (s)
  12072. (nth 0 (split-string s)))
  12073. (cdar (org-collect-keywords '("PROPERTY")))))))
  12074. (org-with-wide-buffer
  12075. (goto-char (point-min))
  12076. (while (re-search-forward org-property-start-re nil t)
  12077. (catch :skip
  12078. (let ((range (org-get-property-block)))
  12079. (unless range (throw :skip nil))
  12080. (goto-char (car range))
  12081. (let ((begin (car range))
  12082. (end (cdr range)))
  12083. ;; Make sure that found property block is not located
  12084. ;; before current point, as it would generate an infloop.
  12085. ;; It can happen, for example, in the following
  12086. ;; situation:
  12087. ;;
  12088. ;; * Headline
  12089. ;; :PROPERTIES:
  12090. ;; ...
  12091. ;; :END:
  12092. ;; *************** Inlinetask
  12093. ;; #+BEGIN_EXAMPLE
  12094. ;; :PROPERTIES:
  12095. ;; #+END_EXAMPLE
  12096. ;;
  12097. (if (< begin (point)) (throw :skip nil) (goto-char begin))
  12098. (while (< (point) end)
  12099. (let ((p (progn (looking-at org-property-re)
  12100. (match-string-no-properties 2))))
  12101. ;; Only add true property name, not extension symbol.
  12102. (push (if (not (string-match-p "\\+\\'" p)) p
  12103. (substring p 0 -1))
  12104. props))
  12105. (forward-line))))
  12106. (outline-next-heading)))
  12107. (when columns
  12108. (goto-char (point-min))
  12109. (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  12110. (let ((element (org-element-at-point)))
  12111. (when (memq (org-element-type element) '(keyword node-property))
  12112. (let ((value (org-element-property :value element))
  12113. (start 0))
  12114. (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  12115. \\(?:{[^}]+}\\)?"
  12116. value start)
  12117. (setq start (match-end 0))
  12118. (let ((p (match-string-no-properties 1 value)))
  12119. (unless (member-ignore-case p org-special-properties)
  12120. (push p props))))))))))
  12121. (sort (delete-dups
  12122. (append props
  12123. ;; for each xxx_ALL property, make sure the bare
  12124. ;; xxx property is also included
  12125. (delq nil (mapcar (lambda (p)
  12126. (and (string-match-p "._ALL\\'" p)
  12127. (substring p 0 -4)))
  12128. props))))
  12129. (lambda (a b) (string< (upcase a) (upcase b))))))
  12130. (defun org-property-values (key)
  12131. "List all non-nil values of property KEY in current buffer."
  12132. (org-with-wide-buffer
  12133. (goto-char (point-min))
  12134. (let ((case-fold-search t)
  12135. (re (org-re-property key))
  12136. values)
  12137. (while (re-search-forward re nil t)
  12138. (push (org-entry-get (point) key) values))
  12139. (delete-dups values))))
  12140. (defun org-insert-property-drawer ()
  12141. "Insert a property drawer into the current entry.
  12142. Do nothing if the drawer already exists. The newly created
  12143. drawer is immediately hidden."
  12144. (org-with-wide-buffer
  12145. ;; Set point to the position where the drawer should be inserted.
  12146. (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12147. (org-back-to-heading-or-point-min t)
  12148. (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12149. (if (org-before-first-heading-p)
  12150. (while (and (org-at-comment-p) (bolp)) (forward-line))
  12151. (progn
  12152. (forward-line)
  12153. (when (looking-at-p org-planning-line-re) (forward-line))))
  12154. (unless (looking-at-p org-property-drawer-re)
  12155. ;; Make sure we start editing a line from current entry, not from
  12156. ;; next one. It prevents extending text properties or overlays
  12157. ;; belonging to the latter.
  12158. (when (and (bolp) (> (point) (point-min))) (backward-char))
  12159. (let ((begin (if (bobp) (point) (1+ (point))))
  12160. (inhibit-read-only t))
  12161. (unless (bobp) (insert "\n"))
  12162. (insert ":PROPERTIES:\n:END:")
  12163. (org-flag-region (line-end-position 0) (point) t 'outline)
  12164. (when (or (eobp) (= begin (point-min))) (insert "\n"))
  12165. (org-indent-region begin (point))))))
  12166. (defun org-insert-drawer (&optional arg drawer)
  12167. "Insert a drawer at point.
  12168. When optional argument ARG is non-nil, insert a property drawer.
  12169. Optional argument DRAWER, when non-nil, is a string representing
  12170. drawer's name. Otherwise, the user is prompted for a name.
  12171. If a region is active, insert the drawer around that region
  12172. instead.
  12173. Point is left between drawer's boundaries."
  12174. (interactive "P")
  12175. (let* ((drawer (if arg "PROPERTIES"
  12176. (or drawer (read-from-minibuffer "Drawer: ")))))
  12177. (cond
  12178. ;; With C-u, fall back on `org-insert-property-drawer'
  12179. (arg (org-insert-property-drawer))
  12180. ;; Check validity of suggested drawer's name.
  12181. ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  12182. (user-error "Invalid drawer name"))
  12183. ;; With an active region, insert a drawer at point.
  12184. ((not (org-region-active-p))
  12185. (progn
  12186. (unless (bolp) (insert "\n"))
  12187. (insert (format ":%s:\n\n:END:\n" drawer))
  12188. (forward-line -2)))
  12189. ;; Otherwise, insert the drawer at point
  12190. (t
  12191. (let ((rbeg (region-beginning))
  12192. (rend (copy-marker (region-end))))
  12193. (unwind-protect
  12194. (progn
  12195. (goto-char rbeg)
  12196. (beginning-of-line)
  12197. (when (save-excursion
  12198. (re-search-forward org-outline-regexp-bol rend t))
  12199. (user-error "Drawers cannot contain headlines"))
  12200. ;; Position point at the beginning of the first
  12201. ;; non-blank line in region. Insert drawer's opening
  12202. ;; there, then indent it.
  12203. (org-skip-whitespace)
  12204. (beginning-of-line)
  12205. (insert ":" drawer ":\n")
  12206. (forward-line -1)
  12207. (indent-for-tab-command)
  12208. ;; Move point to the beginning of the first blank line
  12209. ;; after the last non-blank line in region. Insert
  12210. ;; drawer's closing, then indent it.
  12211. (goto-char rend)
  12212. (skip-chars-backward " \r\t\n")
  12213. (insert "\n:END:")
  12214. (deactivate-mark t)
  12215. (indent-for-tab-command)
  12216. (unless (eolp) (insert "\n")))
  12217. ;; Clear marker, whatever the outcome of insertion is.
  12218. (set-marker rend nil)))))))
  12219. (defvar org-property-set-functions-alist nil
  12220. "Property set function alist.
  12221. Each entry should have the following format:
  12222. (PROPERTY . READ-FUNCTION)
  12223. The read function will be called with the same argument as
  12224. `org-completing-read'.")
  12225. (defun org-set-property-function (property)
  12226. "Get the function that should be used to set PROPERTY.
  12227. This is computed according to `org-property-set-functions-alist'."
  12228. (or (cdr (assoc property org-property-set-functions-alist))
  12229. 'org-completing-read))
  12230. (defun org-read-property-value (property &optional pom default)
  12231. "Read value for PROPERTY, as a string.
  12232. When optional argument POM is non-nil, completion uses additional
  12233. information, i.e., allowed or existing values at point or marker
  12234. POM.
  12235. Optional argument DEFAULT provides a default value for PROPERTY."
  12236. (let* ((completion-ignore-case t)
  12237. (allowed
  12238. (or (org-property-get-allowed-values nil property 'table)
  12239. (and pom (org-property-get-allowed-values pom property 'table))))
  12240. (current (org-entry-get nil property))
  12241. (prompt (format "%s value%s: "
  12242. property
  12243. (if (org-string-nw-p current)
  12244. (format " [%s]" current)
  12245. "")))
  12246. (set-function (org-set-property-function property)))
  12247. (org-trim
  12248. (if allowed
  12249. (funcall set-function
  12250. prompt allowed nil
  12251. (not (get-text-property 0 'org-unrestricted (caar allowed)))
  12252. default nil default)
  12253. (let ((all (mapcar #'list
  12254. (append (org-property-values property)
  12255. (and pom
  12256. (org-with-point-at pom
  12257. (org-property-values property)))))))
  12258. (funcall set-function prompt all nil nil "" nil current))))))
  12259. (defvar org-last-set-property nil)
  12260. (defvar org-last-set-property-value nil)
  12261. (defun org-read-property-name ()
  12262. "Read a property name."
  12263. (let ((completion-ignore-case t)
  12264. (default-prop (or (and (org-at-property-p)
  12265. (match-string-no-properties 2))
  12266. org-last-set-property)))
  12267. (org-completing-read
  12268. (concat "Property"
  12269. (if default-prop (concat " [" default-prop "]") "")
  12270. ": ")
  12271. (mapcar #'list (org-buffer-property-keys nil t t))
  12272. nil nil nil nil default-prop)))
  12273. (defun org-set-property-and-value (use-last)
  12274. "Allow to set [PROPERTY]: [value] direction from prompt.
  12275. When use-default, don't even ask, just use the last
  12276. \"[PROPERTY]: [value]\" string from the history."
  12277. (interactive "P")
  12278. (let* ((completion-ignore-case t)
  12279. (pv (or (and use-last org-last-set-property-value)
  12280. (org-completing-read
  12281. "Enter a \"[Property]: [value]\" pair: "
  12282. nil nil nil nil nil
  12283. org-last-set-property-value)))
  12284. prop val)
  12285. (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  12286. (setq prop (match-string 1 pv)
  12287. val (match-string 2 pv))
  12288. (org-set-property prop val))))
  12289. (defun org-set-property (property value)
  12290. "In the current entry, set PROPERTY to VALUE.
  12291. When called interactively, this will prompt for a property name, offering
  12292. completion on existing and default properties. And then it will prompt
  12293. for a value, offering completion either on allowed values (via an inherited
  12294. xxx_ALL property) or on existing values in other instances of this property
  12295. in the current file.
  12296. Throw an error when trying to set a property with an invalid name."
  12297. (interactive (list nil nil))
  12298. (let ((property (or property (org-read-property-name))))
  12299. ;; `org-entry-put' also makes the following check, but this one
  12300. ;; avoids polluting `org-last-set-property' and
  12301. ;; `org-last-set-property-value' needlessly.
  12302. (unless (org--valid-property-p property)
  12303. (user-error "Invalid property name: \"%s\"" property))
  12304. (let ((value (or value (org-read-property-value property)))
  12305. (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  12306. (setq org-last-set-property property)
  12307. (setq org-last-set-property-value (concat property ": " value))
  12308. ;; Possibly postprocess the inserted value:
  12309. (when fn (setq value (funcall fn value)))
  12310. (unless (equal (org-entry-get nil property) value)
  12311. (org-entry-put nil property value)))))
  12312. (defun org-find-property (property &optional value)
  12313. "Find first entry in buffer that sets PROPERTY.
  12314. When optional argument VALUE is non-nil, only consider an entry
  12315. if it contains PROPERTY set to this value. If PROPERTY should be
  12316. explicitly set to nil, use string \"nil\" for VALUE.
  12317. Return position where the entry begins, or nil if there is no
  12318. such entry. If narrowing is in effect, only search the visible
  12319. part of the buffer."
  12320. (save-excursion
  12321. (goto-char (point-min))
  12322. (let ((case-fold-search t)
  12323. (re (org-re-property property nil (not value) value)))
  12324. (catch 'exit
  12325. (while (re-search-forward re nil t)
  12326. (when (if value (org-at-property-p)
  12327. (org-entry-get (point) property nil t))
  12328. (throw 'exit (progn (org-back-to-heading-or-point-min t)
  12329. (point)))))))))
  12330. (defun org-delete-property (property)
  12331. "In the current entry, delete PROPERTY."
  12332. (interactive
  12333. (let* ((completion-ignore-case t)
  12334. (cat (org-entry-get (point) "CATEGORY"))
  12335. (props0 (org-entry-properties nil 'standard))
  12336. (props (if cat props0
  12337. (delete `("CATEGORY" . ,(org-get-category)) props0)))
  12338. (prop (if (< 1 (length props))
  12339. (completing-read "Property: " props nil t)
  12340. (caar props))))
  12341. (list prop)))
  12342. (if (not property)
  12343. (message "No property to delete in this entry")
  12344. (org-entry-delete nil property)
  12345. (message "Property \"%s\" deleted" property)))
  12346. (defun org-delete-property-globally (property)
  12347. "Remove PROPERTY globally, from all entries.
  12348. This function ignores narrowing, if any."
  12349. (interactive
  12350. (let* ((completion-ignore-case t)
  12351. (prop (completing-read
  12352. "Globally remove property: "
  12353. (mapcar #'list (org-buffer-property-keys)))))
  12354. (list prop)))
  12355. (org-with-wide-buffer
  12356. (goto-char (point-min))
  12357. (let ((count 0)
  12358. (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  12359. (while (re-search-forward re nil t)
  12360. (when (org-entry-delete (point) property) (cl-incf count)))
  12361. (message "Property \"%s\" removed from %d entries" property count))))
  12362. (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  12363. (defun org-compute-property-at-point ()
  12364. "Compute the property at point.
  12365. This looks for an enclosing column format, extracts the operator and
  12366. then applies it to the property in the column format's scope."
  12367. (interactive)
  12368. (unless (org-at-property-p)
  12369. (user-error "Not at a property"))
  12370. (let ((prop (match-string-no-properties 2)))
  12371. (org-columns-get-format-and-top-level)
  12372. (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  12373. (user-error "No operator defined for property %s" prop))
  12374. (org-columns-compute prop)))
  12375. (defvar org-property-allowed-value-functions nil
  12376. "Hook for functions supplying allowed values for a specific property.
  12377. The functions must take a single argument, the name of the property, and
  12378. return a flat list of allowed values. If \":ETC\" is one of
  12379. the values, this means that these values are intended as defaults for
  12380. completion, but that other values should be allowed too.
  12381. The functions must return nil if they are not responsible for this
  12382. property.")
  12383. (defun org-property-get-allowed-values (pom property &optional table)
  12384. "Get allowed values for the property PROPERTY.
  12385. When TABLE is non-nil, return an alist that can directly be used for
  12386. completion."
  12387. (let (vals)
  12388. (cond
  12389. ((equal property "TODO")
  12390. (setq vals (org-with-point-at pom
  12391. (append org-todo-keywords-1 '("")))))
  12392. ((equal property "PRIORITY")
  12393. (let ((n org-priority-lowest))
  12394. (while (>= n org-priority-highest)
  12395. (push (char-to-string n) vals)
  12396. (setq n (1- n)))))
  12397. ((equal property "CATEGORY"))
  12398. ((member property org-special-properties))
  12399. ((setq vals (run-hook-with-args-until-success
  12400. 'org-property-allowed-value-functions property)))
  12401. (t
  12402. (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  12403. (when (and vals (string-match "\\S-" vals))
  12404. (setq vals (car (read-from-string (concat "(" vals ")"))))
  12405. (setq vals (mapcar (lambda (x)
  12406. (cond ((stringp x) x)
  12407. ((numberp x) (number-to-string x))
  12408. ((symbolp x) (symbol-name x))
  12409. (t "???")))
  12410. vals)))))
  12411. (when (member ":ETC" vals)
  12412. (setq vals (remove ":ETC" vals))
  12413. (org-add-props (car vals) '(org-unrestricted t)))
  12414. (if table (mapcar 'list vals) vals)))
  12415. (defun org-property-previous-allowed-value (&optional _previous)
  12416. "Switch to the next allowed value for this property."
  12417. (interactive)
  12418. (org-property-next-allowed-value t))
  12419. (defun org-property-next-allowed-value (&optional previous)
  12420. "Switch to the next allowed value for this property."
  12421. (interactive)
  12422. (unless (org-at-property-p)
  12423. (user-error "Not at a property"))
  12424. (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  12425. (key (match-string 2))
  12426. (value (match-string 3))
  12427. (allowed (or (org-property-get-allowed-values (point) key)
  12428. (and (member value '("[ ]" "[-]" "[X]"))
  12429. '("[ ]" "[X]"))))
  12430. (heading (save-match-data (nth 4 (org-heading-components))))
  12431. nval)
  12432. (unless allowed
  12433. (user-error "Allowed values for this property have not been defined"))
  12434. (when previous (setq allowed (reverse allowed)))
  12435. (when (member value allowed)
  12436. (setq nval (car (cdr (member value allowed)))))
  12437. (setq nval (or nval (car allowed)))
  12438. (when (equal nval value)
  12439. (user-error "Only one allowed value for this property"))
  12440. (org-at-property-p)
  12441. (replace-match (concat " :" key ": " nval) t t)
  12442. (org-indent-line)
  12443. (beginning-of-line 1)
  12444. (skip-chars-forward " \t")
  12445. (when (equal prop org-effort-property)
  12446. (org-refresh-property
  12447. '((effort . identity)
  12448. (effort-minutes . org-duration-to-minutes))
  12449. nval)
  12450. (when (string= org-clock-current-task heading)
  12451. (setq org-clock-effort nval)
  12452. (org-clock-update-mode-line)))
  12453. (run-hook-with-args 'org-property-changed-functions key nval)))
  12454. (defun org-find-olp (path &optional this-buffer)
  12455. "Return a marker pointing to the entry at outline path OLP.
  12456. If anything goes wrong, throw an error, and if you need to do
  12457. something based on this error, you can catch it with
  12458. `condition-case'.
  12459. If THIS-BUFFER is set, the outline path does not contain a file,
  12460. only headings."
  12461. (let* ((file (if this-buffer buffer-file-name (pop path)))
  12462. (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  12463. (level 1)
  12464. (lmin 1)
  12465. (lmax 1)
  12466. end found flevel)
  12467. (unless buffer (error "File not found :%s" file))
  12468. (with-current-buffer buffer
  12469. (unless (derived-mode-p 'org-mode)
  12470. (error "Buffer %s needs to be in Org mode" buffer))
  12471. (org-with-wide-buffer
  12472. (goto-char (point-min))
  12473. (dolist (heading path)
  12474. (let ((re (format org-complex-heading-regexp-format
  12475. (regexp-quote heading)))
  12476. (cnt 0))
  12477. (while (re-search-forward re end t)
  12478. (setq level (- (match-end 1) (match-beginning 1)))
  12479. (when (and (>= level lmin) (<= level lmax))
  12480. (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  12481. (when (= cnt 0)
  12482. (error "Heading not found on level %d: %s" lmax heading))
  12483. (when (> cnt 1)
  12484. (error "Heading not unique on level %d: %s" lmax heading))
  12485. (goto-char found)
  12486. (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  12487. (setq end (save-excursion (org-end-of-subtree t t)))))
  12488. (when (org-at-heading-p)
  12489. (point-marker))))))
  12490. (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  12491. "Find node HEADING in BUFFER.
  12492. Return a marker to the heading if it was found, or nil if not.
  12493. If POS-ONLY is set, return just the position instead of a marker.
  12494. The heading text must match exact, but it may have a TODO keyword,
  12495. a priority cookie and tags in the standard locations."
  12496. (with-current-buffer (or buffer (current-buffer))
  12497. (org-with-wide-buffer
  12498. (goto-char (point-min))
  12499. (let (case-fold-search)
  12500. (when (re-search-forward
  12501. (format org-complex-heading-regexp-format
  12502. (regexp-quote heading)) nil t)
  12503. (if pos-only
  12504. (match-beginning 0)
  12505. (move-marker (make-marker) (match-beginning 0))))))))
  12506. (defun org-find-exact-heading-in-directory (heading &optional dir)
  12507. "Find Org node headline HEADING in all \".org\" files in directory DIR.
  12508. When the target headline is found, return a marker to this location."
  12509. (let ((files (directory-files (or dir default-directory)
  12510. t "\\`[^.#].*\\.org\\'"))
  12511. visiting m buffer)
  12512. (catch 'found
  12513. (dolist (file files)
  12514. (message "trying %s" file)
  12515. (setq visiting (org-find-base-buffer-visiting file))
  12516. (setq buffer (or visiting (find-file-noselect file)))
  12517. (setq m (org-find-exact-headline-in-buffer
  12518. heading buffer))
  12519. (when (and (not m) (not visiting)) (kill-buffer buffer))
  12520. (and m (throw 'found m))))))
  12521. (defun org-find-entry-with-id (ident)
  12522. "Locate the entry that contains the ID property with exact value IDENT.
  12523. IDENT can be a string, a symbol or a number, this function will search for
  12524. the string representation of it.
  12525. Return the position where this entry starts, or nil if there is no such entry."
  12526. (interactive "sID: ")
  12527. (let ((id (cond
  12528. ((stringp ident) ident)
  12529. ((symbolp ident) (symbol-name ident))
  12530. ((numberp ident) (number-to-string ident))
  12531. (t (error "IDENT %s must be a string, symbol or number" ident)))))
  12532. (org-with-wide-buffer (org-find-property "ID" id))))
  12533. ;;;; Timestamps
  12534. (defvar org-last-changed-timestamp nil)
  12535. (defvar org-last-inserted-timestamp nil
  12536. "The last time stamp inserted with `org-insert-time-stamp'.")
  12537. (defun org-time-stamp (arg &optional inactive)
  12538. "Prompt for a date/time and insert a time stamp.
  12539. If the user specifies a time like HH:MM or if this command is
  12540. called with at least one prefix argument, the time stamp contains
  12541. the date and the time. Otherwise, only the date is included.
  12542. All parts of a date not specified by the user are filled in from
  12543. the timestamp at point, if any, or the current date/time
  12544. otherwise.
  12545. If there is already a timestamp at the cursor, it is replaced.
  12546. With two universal prefix arguments, insert an active timestamp
  12547. with the current time without prompting the user.
  12548. When called from Lisp, the timestamp is inactive if INACTIVE is
  12549. non-nil."
  12550. (interactive "P")
  12551. (let* ((ts (cond
  12552. ((org-at-date-range-p t)
  12553. (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  12554. ((org-at-timestamp-p 'lax) (match-string 0))))
  12555. ;; Default time is either the timestamp at point or today.
  12556. ;; When entering a range, only the range start is considered.
  12557. (default-time (and ts (org-time-string-to-time ts)))
  12558. (default-input (and ts (org-get-compact-tod ts)))
  12559. (repeater (and ts
  12560. (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  12561. (match-string 0 ts)))
  12562. org-time-was-given
  12563. org-end-time-was-given
  12564. (time
  12565. (if (equal arg '(16)) (current-time)
  12566. ;; Preserve `this-command' and `last-command'.
  12567. (let ((this-command this-command)
  12568. (last-command last-command))
  12569. (org-read-date
  12570. arg 'totime nil nil default-time default-input
  12571. inactive)))))
  12572. (cond
  12573. ((and ts
  12574. (memq last-command '(org-time-stamp org-time-stamp-inactive))
  12575. (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  12576. (insert "--")
  12577. (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  12578. (ts
  12579. ;; Make sure we're on a timestamp. When in the middle of a date
  12580. ;; range, move arbitrarily to range end.
  12581. (unless (org-at-timestamp-p 'lax)
  12582. (skip-chars-forward "-")
  12583. (org-at-timestamp-p 'lax))
  12584. (replace-match "")
  12585. (setq org-last-changed-timestamp
  12586. (org-insert-time-stamp
  12587. time (or org-time-was-given arg)
  12588. inactive nil nil (list org-end-time-was-given)))
  12589. (when repeater
  12590. (backward-char)
  12591. (insert " " repeater)
  12592. (setq org-last-changed-timestamp
  12593. (concat (substring org-last-inserted-timestamp 0 -1)
  12594. " " repeater ">")))
  12595. (message "Timestamp updated"))
  12596. ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  12597. (t (org-insert-time-stamp
  12598. time (or org-time-was-given arg) inactive nil nil
  12599. (list org-end-time-was-given))))))
  12600. ;; FIXME: can we use this for something else, like computing time differences?
  12601. (defun org-get-compact-tod (s)
  12602. (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  12603. (let* ((t1 (match-string 1 s))
  12604. (h1 (string-to-number (match-string 2 s)))
  12605. (m1 (string-to-number (match-string 3 s)))
  12606. (t2 (and (match-end 4) (match-string 5 s)))
  12607. (h2 (and t2 (string-to-number (match-string 6 s))))
  12608. (m2 (and t2 (string-to-number (match-string 7 s))))
  12609. dh dm)
  12610. (if (not t2)
  12611. t1
  12612. (setq dh (- h2 h1) dm (- m2 m1))
  12613. (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  12614. (concat t1 "+" (number-to-string dh)
  12615. (and (/= 0 dm) (format ":%02d" dm)))))))
  12616. (defun org-time-stamp-inactive (&optional arg)
  12617. "Insert an inactive time stamp.
  12618. An inactive time stamp is enclosed in square brackets instead of
  12619. angle brackets. It is inactive in the sense that it does not
  12620. trigger agenda entries. So these are more for recording a
  12621. certain time/date.
  12622. If the user specifies a time like HH:MM or if this command is called with
  12623. at least one prefix argument, the time stamp contains the date and the time.
  12624. Otherwise, only the date is included.
  12625. When called with two universal prefix arguments, insert an inactive time stamp
  12626. with the current time without prompting the user."
  12627. (interactive "P")
  12628. (org-time-stamp arg 'inactive))
  12629. (defvar org-date-ovl (make-overlay 1 1))
  12630. (overlay-put org-date-ovl 'face 'org-date-selected)
  12631. (delete-overlay org-date-ovl)
  12632. (defvar org-ans1) ; dynamically scoped parameter
  12633. (defvar org-ans2) ; dynamically scoped parameter
  12634. (defvar org-plain-time-of-day-regexp) ; defined below
  12635. (defvar org-overriding-default-time nil) ; dynamically scoped
  12636. (defvar org-read-date-overlay nil)
  12637. (defvar org-read-date-history nil)
  12638. (defvar org-read-date-final-answer nil)
  12639. (defvar org-read-date-analyze-futurep nil)
  12640. (defvar org-read-date-analyze-forced-year nil)
  12641. (defvar org-read-date-inactive)
  12642. (defvar org-def)
  12643. (defvar org-defdecode)
  12644. (defvar org-with-time)
  12645. (defvar calendar-setup) ; Dynamically scoped.
  12646. (defun org-read-date (&optional with-time to-time from-string prompt
  12647. default-time default-input inactive)
  12648. "Read a date, possibly a time, and make things smooth for the user.
  12649. The prompt will suggest to enter an ISO date, but you can also enter anything
  12650. which will at least partially be understood by `parse-time-string'.
  12651. Unrecognized parts of the date will default to the current day, month, year,
  12652. hour and minute. If this command is called to replace a timestamp at point,
  12653. or to enter the second timestamp of a range, the default time is taken
  12654. from the existing stamp. Furthermore, the command prefers the future,
  12655. so if you are giving a date where the year is not given, and the day-month
  12656. combination is already past in the current year, it will assume you
  12657. mean next year. For details, see the manual. A few examples:
  12658. 3-2-5 --> 2003-02-05
  12659. feb 15 --> currentyear-02-15
  12660. 2/15 --> currentyear-02-15
  12661. sep 12 9 --> 2009-09-12
  12662. 12:45 --> today 12:45
  12663. 22 sept 0:34 --> currentyear-09-22 0:34
  12664. 12 --> currentyear-currentmonth-12
  12665. Fri --> nearest Friday after today
  12666. -Tue --> last Tuesday
  12667. etc.
  12668. Furthermore you can specify a relative date by giving, as the *first* thing
  12669. in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
  12670. change in days weeks, months, years.
  12671. With a single plus or minus, the date is relative to today. With a double
  12672. plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
  12673. +4d --> four days from today
  12674. +4 --> same as above
  12675. +2w --> two weeks from today
  12676. ++5 --> five days from default date
  12677. The function understands only English month and weekday abbreviations.
  12678. While prompting, a calendar is popped up - you can also select the
  12679. date with the mouse (button 1). The calendar shows a period of three
  12680. months. To scroll it to other months, use the keys `>' and `<'.
  12681. If you don't like the calendar, turn it off with
  12682. (setq org-read-date-popup-calendar nil)
  12683. With optional argument TO-TIME, the date will immediately be converted
  12684. to an internal time.
  12685. With an optional argument WITH-TIME, the prompt will suggest to
  12686. also insert a time. Note that when WITH-TIME is not set, you can
  12687. still enter a time, and this function will inform the calling routine
  12688. about this change. The calling routine may then choose to change the
  12689. format used to insert the time stamp into the buffer to include the time.
  12690. With optional argument FROM-STRING, read from this string instead from
  12691. the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
  12692. the time/date that is used for everything that is not specified by the
  12693. user."
  12694. (require 'parse-time)
  12695. (let* ((org-with-time with-time)
  12696. (org-time-stamp-rounding-minutes
  12697. (if (equal org-with-time '(16))
  12698. '(0 0)
  12699. org-time-stamp-rounding-minutes))
  12700. (ct (org-current-time))
  12701. (org-def (or org-overriding-default-time default-time ct))
  12702. (org-defdecode (decode-time org-def))
  12703. (cur-frame (selected-frame))
  12704. (mouse-autoselect-window nil) ; Don't let the mouse jump
  12705. (calendar-setup
  12706. (and (eq calendar-setup 'calendar-only) 'calendar-only))
  12707. (calendar-move-hook nil)
  12708. (calendar-view-diary-initially-flag nil)
  12709. (calendar-view-holidays-initially-flag nil)
  12710. ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  12711. ;; Rationalize `org-def' and `org-defdecode', if required.
  12712. (when (< (nth 2 org-defdecode) org-extend-today-until)
  12713. (setf (nth 2 org-defdecode) -1)
  12714. (setf (nth 1 org-defdecode) 59)
  12715. (setq org-def (apply #'encode-time org-defdecode))
  12716. (setq org-defdecode (decode-time org-def)))
  12717. (let* ((timestr (format-time-string
  12718. (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  12719. org-def))
  12720. (prompt (concat (if prompt (concat prompt " ") "")
  12721. (format "Date+time [%s]: " timestr))))
  12722. (cond
  12723. (from-string (setq ans from-string))
  12724. (org-read-date-popup-calendar
  12725. (save-excursion
  12726. (save-window-excursion
  12727. (calendar)
  12728. (when (eq calendar-setup 'calendar-only)
  12729. (setq cal-frame
  12730. (window-frame (get-buffer-window "*Calendar*" 'visible)))
  12731. (select-frame cal-frame))
  12732. (org-eval-in-calendar '(setq cursor-type nil) t)
  12733. (unwind-protect
  12734. (progn
  12735. (calendar-forward-day (- (time-to-days org-def)
  12736. (calendar-absolute-from-gregorian
  12737. (calendar-current-date))))
  12738. (org-eval-in-calendar nil t)
  12739. (let* ((old-map (current-local-map))
  12740. (map (copy-keymap calendar-mode-map))
  12741. (minibuffer-local-map
  12742. (copy-keymap org-read-date-minibuffer-local-map)))
  12743. (org-defkey map (kbd "RET") 'org-calendar-select)
  12744. (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  12745. (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  12746. (unwind-protect
  12747. (progn
  12748. (use-local-map map)
  12749. (setq org-read-date-inactive inactive)
  12750. (add-hook 'post-command-hook 'org-read-date-display)
  12751. (setq org-ans0
  12752. (read-string prompt
  12753. default-input
  12754. 'org-read-date-history
  12755. nil))
  12756. ;; org-ans0: from prompt
  12757. ;; org-ans1: from mouse click
  12758. ;; org-ans2: from calendar motion
  12759. (setq ans
  12760. (concat org-ans0 " " (or org-ans1 org-ans2))))
  12761. (remove-hook 'post-command-hook 'org-read-date-display)
  12762. (use-local-map old-map)
  12763. (when org-read-date-overlay
  12764. (delete-overlay org-read-date-overlay)
  12765. (setq org-read-date-overlay nil)))))
  12766. (bury-buffer "*Calendar*")
  12767. (when cal-frame
  12768. (delete-frame cal-frame)
  12769. (select-frame-set-input-focus cur-frame))))))
  12770. (t ; Naked prompt only
  12771. (unwind-protect
  12772. (setq ans (read-string prompt default-input
  12773. 'org-read-date-history timestr))
  12774. (when org-read-date-overlay
  12775. (delete-overlay org-read-date-overlay)
  12776. (setq org-read-date-overlay nil))))))
  12777. (setq final (org-read-date-analyze ans org-def org-defdecode))
  12778. (when org-read-date-analyze-forced-year
  12779. (message "Year was forced into %s"
  12780. (if org-read-date-force-compatible-dates
  12781. "compatible range (1970-2037)"
  12782. "range representable on this machine"))
  12783. (ding))
  12784. (setq final (apply #'encode-time final))
  12785. (setq org-read-date-final-answer ans)
  12786. (if to-time
  12787. final
  12788. ;; This round-trip gets rid of 34th of August and stuff like that....
  12789. (setq final (decode-time final))
  12790. (if (and (boundp 'org-time-was-given) org-time-was-given)
  12791. (format "%04d-%02d-%02d %02d:%02d"
  12792. (nth 5 final) (nth 4 final) (nth 3 final)
  12793. (nth 2 final) (nth 1 final))
  12794. (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  12795. (defun org-read-date-display ()
  12796. "Display the current date prompt interpretation in the minibuffer."
  12797. (when org-read-date-display-live
  12798. (when org-read-date-overlay
  12799. (delete-overlay org-read-date-overlay))
  12800. (when (minibufferp (current-buffer))
  12801. (save-excursion
  12802. (end-of-line 1)
  12803. (while (not (equal (buffer-substring
  12804. (max (point-min) (- (point) 4)) (point))
  12805. " "))
  12806. (insert " ")))
  12807. (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
  12808. " " (or org-ans1 org-ans2)))
  12809. (org-end-time-was-given nil)
  12810. (f (org-read-date-analyze ans org-def org-defdecode))
  12811. (fmts (if org-display-custom-times
  12812. org-time-stamp-custom-formats
  12813. org-time-stamp-formats))
  12814. (fmt (if (or org-with-time
  12815. (and (boundp 'org-time-was-given) org-time-was-given))
  12816. (cdr fmts)
  12817. (car fmts)))
  12818. (txt (format-time-string fmt (apply #'encode-time f)))
  12819. (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
  12820. (txt (concat "=> " txt)))
  12821. (when (and org-end-time-was-given
  12822. (string-match org-plain-time-of-day-regexp txt))
  12823. (setq txt (concat (substring txt 0 (match-end 0)) "-"
  12824. org-end-time-was-given
  12825. (substring txt (match-end 0)))))
  12826. (when org-read-date-analyze-futurep
  12827. (setq txt (concat txt " (=>F)")))
  12828. (setq org-read-date-overlay
  12829. (make-overlay (1- (point-at-eol)) (point-at-eol)))
  12830. (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  12831. (defun org-read-date-analyze (ans def defdecode)
  12832. "Analyze the combined answer of the date prompt."
  12833. ;; FIXME: cleanup and comment
  12834. (let ((org-def def)
  12835. (org-defdecode defdecode)
  12836. (nowdecode (decode-time))
  12837. delta deltan deltaw deltadef year month day
  12838. hour minute second wday pm h2 m2 tl wday1
  12839. iso-year iso-weekday iso-week iso-date futurep kill-year)
  12840. (setq org-read-date-analyze-futurep nil
  12841. org-read-date-analyze-forced-year nil)
  12842. (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  12843. (setq ans "+0"))
  12844. (when (setq delta (org-read-date-get-relative ans nil org-def))
  12845. (setq ans (replace-match "" t t ans)
  12846. deltan (car delta)
  12847. deltaw (nth 1 delta)
  12848. deltadef (nth 2 delta)))
  12849. ;; Check if there is an iso week date in there. If yes, store the
  12850. ;; info and postpone interpreting it until the rest of the parsing
  12851. ;; is done.
  12852. (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  12853. (setq iso-year (when (match-end 1)
  12854. (org-small-year-to-year
  12855. (string-to-number (match-string 1 ans))))
  12856. iso-weekday (when (match-end 3)
  12857. (string-to-number (match-string 3 ans)))
  12858. iso-week (string-to-number (match-string 2 ans)))
  12859. (setq ans (replace-match "" t t ans)))
  12860. ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  12861. (when (string-match
  12862. "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  12863. (setq year (if (match-end 2)
  12864. (string-to-number (match-string 2 ans))
  12865. (progn (setq kill-year t)
  12866. (string-to-number (format-time-string "%Y"))))
  12867. month (string-to-number (match-string 3 ans))
  12868. day (string-to-number (match-string 4 ans)))
  12869. (setq year (org-small-year-to-year year))
  12870. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12871. t nil ans)))
  12872. ;; Help matching dotted european dates
  12873. (when (string-match
  12874. "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  12875. (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  12876. (setq kill-year t)
  12877. (string-to-number (format-time-string "%Y")))
  12878. day (string-to-number (match-string 1 ans))
  12879. month (string-to-number (match-string 2 ans))
  12880. ans (replace-match (format "%04d-%02d-%02d" year month day)
  12881. t nil ans)))
  12882. ;; Help matching american dates, like 5/30 or 5/30/7
  12883. (when (string-match
  12884. "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  12885. (setq year (if (match-end 4)
  12886. (string-to-number (match-string 4 ans))
  12887. (progn (setq kill-year t)
  12888. (string-to-number (format-time-string "%Y"))))
  12889. month (string-to-number (match-string 1 ans))
  12890. day (string-to-number (match-string 2 ans)))
  12891. (setq year (org-small-year-to-year year))
  12892. (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  12893. t nil ans)))
  12894. ;; Help matching am/pm times, because `parse-time-string' does not do that.
  12895. ;; If there is a time with am/pm, and *no* time without it, we convert
  12896. ;; so that matching will be successful.
  12897. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12898. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12899. (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  12900. (setq hour (string-to-number (match-string 1 ans))
  12901. minute (if (match-end 3)
  12902. (string-to-number (match-string 3 ans))
  12903. 0)
  12904. pm (equal ?p
  12905. (string-to-char (downcase (match-string 4 ans)))))
  12906. (if (and (= hour 12) (not pm))
  12907. (setq hour 0)
  12908. (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  12909. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12910. t t ans))))
  12911. ;; Help matching HHhMM times, similarly as for am/pm times.
  12912. (cl-loop for i from 1 to 2 do ; twice, for end time as well
  12913. (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  12914. (string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  12915. (setq hour (if (match-end 1)
  12916. (string-to-number (match-string 1 ans))
  12917. 0)
  12918. minute (if (match-end 2)
  12919. (string-to-number (match-string 2 ans))
  12920. 0))
  12921. (setq ans (replace-match (format "%02d:%02d" hour minute)
  12922. t t ans))))
  12923. ;; Check if a time range is given as a duration
  12924. (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  12925. (setq hour (string-to-number (match-string 1 ans))
  12926. h2 (+ hour (string-to-number (match-string 3 ans)))
  12927. minute (string-to-number (match-string 2 ans))
  12928. m2 (+ minute (if (match-end 5) (string-to-number
  12929. (match-string 5 ans))0)))
  12930. (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  12931. (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  12932. t t ans)))
  12933. ;; Check if there is a time range
  12934. (when (boundp 'org-end-time-was-given)
  12935. (setq org-time-was-given nil)
  12936. (when (and (string-match org-plain-time-of-day-regexp ans)
  12937. (match-end 8))
  12938. (setq org-end-time-was-given (match-string 8 ans))
  12939. (setq ans (concat (substring ans 0 (match-beginning 7))
  12940. (substring ans (match-end 7))))))
  12941. (setq tl (parse-time-string ans)
  12942. day (or (nth 3 tl) (nth 3 org-defdecode))
  12943. month
  12944. (cond ((nth 4 tl))
  12945. ((not org-read-date-prefer-future) (nth 4 org-defdecode))
  12946. ;; Day was specified. Make sure DAY+MONTH
  12947. ;; combination happens in the future.
  12948. ((nth 3 tl)
  12949. (setq futurep t)
  12950. (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  12951. (nth 4 nowdecode)))
  12952. (t (nth 4 org-defdecode)))
  12953. year
  12954. (cond ((and (not kill-year) (nth 5 tl)))
  12955. ((not org-read-date-prefer-future) (nth 5 org-defdecode))
  12956. ;; Month was guessed in the future and is at least
  12957. ;; equal to NOWDECODE's. Fix year accordingly.
  12958. (futurep
  12959. (if (or (> month (nth 4 nowdecode))
  12960. (>= day (nth 3 nowdecode)))
  12961. (nth 5 nowdecode)
  12962. (1+ (nth 5 nowdecode))))
  12963. ;; Month was specified. Make sure MONTH+YEAR
  12964. ;; combination happens in the future.
  12965. ((nth 4 tl)
  12966. (setq futurep t)
  12967. (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  12968. ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  12969. ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  12970. (t (nth 5 nowdecode))))
  12971. (t (nth 5 org-defdecode)))
  12972. hour (or (nth 2 tl) (nth 2 org-defdecode))
  12973. minute (or (nth 1 tl) (nth 1 org-defdecode))
  12974. second (or (nth 0 tl) 0)
  12975. wday (nth 6 tl))
  12976. (when (and (eq org-read-date-prefer-future 'time)
  12977. (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  12978. (equal day (nth 3 nowdecode))
  12979. (equal month (nth 4 nowdecode))
  12980. (equal year (nth 5 nowdecode))
  12981. (nth 2 tl)
  12982. (or (< (nth 2 tl) (nth 2 nowdecode))
  12983. (and (= (nth 2 tl) (nth 2 nowdecode))
  12984. (nth 1 tl)
  12985. (< (nth 1 tl) (nth 1 nowdecode)))))
  12986. (setq day (1+ day)
  12987. futurep t))
  12988. ;; Special date definitions below
  12989. (cond
  12990. (iso-week
  12991. ;; There was an iso week
  12992. (require 'cal-iso)
  12993. (setq futurep nil)
  12994. (setq year (or iso-year year)
  12995. day (or iso-weekday wday 1)
  12996. wday nil ; to make sure that the trigger below does not match
  12997. iso-date (calendar-gregorian-from-absolute
  12998. (calendar-iso-to-absolute
  12999. (list iso-week day year))))
  13000. ; FIXME: Should we also push ISO weeks into the future?
  13001. ; (when (and org-read-date-prefer-future
  13002. ; (not iso-year)
  13003. ; (< (calendar-absolute-from-gregorian iso-date)
  13004. ; (time-to-days nil)))
  13005. ; (setq year (1+ year)
  13006. ; iso-date (calendar-gregorian-from-absolute
  13007. ; (calendar-iso-to-absolute
  13008. ; (list iso-week day year)))))
  13009. (setq month (car iso-date)
  13010. year (nth 2 iso-date)
  13011. day (nth 1 iso-date)))
  13012. (deltan
  13013. (setq futurep nil)
  13014. (unless deltadef
  13015. (let ((now (decode-time)))
  13016. (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  13017. (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
  13018. ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  13019. ((equal deltaw "m") (setq month (+ month deltan)))
  13020. ((equal deltaw "y") (setq year (+ year deltan)))))
  13021. ((and wday (not (nth 3 tl)))
  13022. ;; Weekday was given, but no day, so pick that day in the week
  13023. ;; on or after the derived date.
  13024. (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
  13025. (unless (equal wday wday1)
  13026. (setq day (+ day (% (- wday wday1 -7) 7))))))
  13027. (when (and (boundp 'org-time-was-given)
  13028. (nth 2 tl))
  13029. (setq org-time-was-given t))
  13030. (when (< year 100) (setq year (+ 2000 year)))
  13031. ;; Check of the date is representable
  13032. (if org-read-date-force-compatible-dates
  13033. (progn
  13034. (when (< year 1970)
  13035. (setq year 1970 org-read-date-analyze-forced-year t))
  13036. (when (> year 2037)
  13037. (setq year 2037 org-read-date-analyze-forced-year t)))
  13038. (condition-case nil
  13039. (ignore (encode-time second minute hour day month year))
  13040. (error
  13041. (setq year (nth 5 org-defdecode))
  13042. (setq org-read-date-analyze-forced-year t))))
  13043. (setq org-read-date-analyze-futurep futurep)
  13044. (list second minute hour day month year)))
  13045. (defvar parse-time-weekdays)
  13046. (defun org-read-date-get-relative (s today default)
  13047. "Check string S for special relative date string.
  13048. TODAY and DEFAULT are internal times, for today and for a default.
  13049. Return shift list (N what def-flag)
  13050. WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  13051. N is the number of WHATs to shift.
  13052. DEF-FLAG is t when a double ++ or -- indicates shift relative to
  13053. the DEFAULT date rather than TODAY."
  13054. (require 'parse-time)
  13055. (when (and
  13056. (string-match
  13057. (concat
  13058. "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  13059. "\\([0-9]+\\)?"
  13060. "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  13061. "\\([ \t]\\|$\\)") s)
  13062. (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  13063. (let* ((dir (if (> (match-end 1) (match-beginning 1))
  13064. (string-to-char (substring (match-string 1 s) -1))
  13065. ?+))
  13066. (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  13067. (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  13068. (what (if (match-end 3) (match-string 3 s) "d"))
  13069. (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  13070. (date (if rel default today))
  13071. (wday (nth 6 (decode-time date)))
  13072. delta)
  13073. (if wday1
  13074. (progn
  13075. (setq delta (mod (+ 7 (- wday1 wday)) 7))
  13076. (when (= delta 0) (setq delta 7))
  13077. (when (= dir ?-)
  13078. (setq delta (- delta 7))
  13079. (when (= delta 0) (setq delta -7)))
  13080. (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  13081. (list delta "d" rel))
  13082. (list (* n (if (= dir ?-) -1 1)) what rel)))))
  13083. (defun org-order-calendar-date-args (arg1 arg2 arg3)
  13084. "Turn a user-specified date into the internal representation.
  13085. The internal representation needed by the calendar is (month day year).
  13086. This is a wrapper to handle the brain-dead convention in calendar that
  13087. user function argument order change dependent on argument order."
  13088. (pcase calendar-date-style
  13089. (`american (list arg1 arg2 arg3))
  13090. (`european (list arg2 arg1 arg3))
  13091. (`iso (list arg2 arg3 arg1))))
  13092. (defun org-eval-in-calendar (form &optional keepdate)
  13093. "Eval FORM in the calendar window and return to current window.
  13094. Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  13095. (let ((sf (selected-frame))
  13096. (sw (selected-window)))
  13097. (select-window (get-buffer-window "*Calendar*" t))
  13098. (eval form)
  13099. (when (and (not keepdate) (calendar-cursor-to-date))
  13100. (let* ((date (calendar-cursor-to-date))
  13101. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13102. (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  13103. (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  13104. (select-window sw)
  13105. (select-frame-set-input-focus sf)))
  13106. (defun org-calendar-select ()
  13107. "Return to `org-read-date' with the date currently selected.
  13108. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13109. (interactive)
  13110. (when (calendar-cursor-to-date)
  13111. (let* ((date (calendar-cursor-to-date))
  13112. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13113. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13114. (when (active-minibuffer-window) (exit-minibuffer))))
  13115. (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  13116. "Insert a date stamp for the date given by the internal TIME.
  13117. See `format-time-string' for the format of TIME.
  13118. WITH-HM means use the stamp format that includes the time of the day.
  13119. INACTIVE means use square brackets instead of angular ones, so that the
  13120. stamp will not contribute to the agenda.
  13121. PRE and POST are optional strings to be inserted before and after the
  13122. stamp.
  13123. The command returns the inserted time stamp."
  13124. (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
  13125. stamp)
  13126. (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
  13127. (insert-before-markers (or pre ""))
  13128. (when (listp extra)
  13129. (setq extra (car extra))
  13130. (if (and (stringp extra)
  13131. (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  13132. (setq extra (format "-%02d:%02d"
  13133. (string-to-number (match-string 1 extra))
  13134. (string-to-number (match-string 2 extra))))
  13135. (setq extra nil)))
  13136. (when extra
  13137. (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  13138. (insert-before-markers (setq stamp (format-time-string fmt time)))
  13139. (insert-before-markers (or post ""))
  13140. (setq org-last-inserted-timestamp stamp)))
  13141. (defun org-toggle-time-stamp-overlays ()
  13142. "Toggle the use of custom time stamp formats."
  13143. (interactive)
  13144. (setq org-display-custom-times (not org-display-custom-times))
  13145. (unless org-display-custom-times
  13146. (let ((p (point-min)) (bmp (buffer-modified-p)))
  13147. (while (setq p (next-single-property-change p 'display))
  13148. (when (and (get-text-property p 'display)
  13149. (eq (get-text-property p 'face) 'org-date))
  13150. (remove-text-properties
  13151. p (setq p (next-single-property-change p 'display))
  13152. '(display t))))
  13153. (set-buffer-modified-p bmp)))
  13154. (org-restart-font-lock)
  13155. (setq org-table-may-need-update t)
  13156. (if org-display-custom-times
  13157. (message "Time stamps are overlaid with custom format")
  13158. (message "Time stamp overlays removed")))
  13159. (defun org-display-custom-time (beg end)
  13160. "Overlay modified time stamp format over timestamp between BEG and END."
  13161. (let* ((ts (buffer-substring beg end))
  13162. t1 with-hm tf time str (off 0))
  13163. (save-match-data
  13164. (setq t1 (org-parse-time-string ts t))
  13165. (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  13166. (setq off (- (match-end 0) (match-beginning 0)))))
  13167. (setq end (- end off))
  13168. (setq with-hm (and (nth 1 t1) (nth 2 t1))
  13169. tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
  13170. time (org-fix-decoded-time t1)
  13171. str (org-add-props
  13172. (format-time-string
  13173. (substring tf 1 -1) (apply 'encode-time time))
  13174. nil 'mouse-face 'highlight))
  13175. (put-text-property beg end 'display str)))
  13176. (defun org-fix-decoded-time (time)
  13177. "Set 0 instead of nil for the first 6 elements of time.
  13178. Don't touch the rest."
  13179. (let ((n 0))
  13180. (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  13181. (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  13182. "Difference between TIMESTAMP-STRING and now in days.
  13183. If SECONDS is non-nil, return the difference in seconds."
  13184. (let ((fdiff (if seconds #'float-time #'time-to-days)))
  13185. (- (funcall fdiff (org-time-string-to-time timestamp-string))
  13186. (funcall fdiff nil))))
  13187. (defun org-deadline-close-p (timestamp-string &optional ndays)
  13188. "Is the time in TIMESTAMP-STRING close to the current date?"
  13189. (setq ndays (or ndays (org-get-wdays timestamp-string)))
  13190. (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  13191. (not (org-entry-is-done-p))))
  13192. (defun org-get-wdays (ts &optional delay zero-delay)
  13193. "Get the deadline lead time appropriate for timestring TS.
  13194. When DELAY is non-nil, get the delay time for scheduled items
  13195. instead of the deadline lead time. When ZERO-DELAY is non-nil
  13196. and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  13197. don't try to find the delay cookie in the scheduled timestamp."
  13198. (let ((tv (if delay org-scheduled-delay-days
  13199. org-deadline-warning-days)))
  13200. (cond
  13201. ((or (and delay (< tv 0))
  13202. (and delay zero-delay (<= tv 0))
  13203. (and (not delay) (<= tv 0)))
  13204. ;; Enforce this value no matter what
  13205. (- tv))
  13206. ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  13207. ;; lead time is specified.
  13208. (floor (* (string-to-number (match-string 1 ts))
  13209. (cdr (assoc (match-string 2 ts)
  13210. '(("d" . 1) ("w" . 7)
  13211. ("m" . 30.4) ("y" . 365.25)
  13212. ("h" . 0.041667)))))))
  13213. ;; go for the default.
  13214. (t tv))))
  13215. (defun org-calendar-select-mouse (ev)
  13216. "Return to `org-read-date' with the date currently selected.
  13217. This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  13218. (interactive "e")
  13219. (mouse-set-point ev)
  13220. (when (calendar-cursor-to-date)
  13221. (let* ((date (calendar-cursor-to-date))
  13222. (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  13223. (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  13224. (when (active-minibuffer-window) (exit-minibuffer))))
  13225. (defun org-check-deadlines (ndays)
  13226. "Check if there are any deadlines due or past due.
  13227. A deadline is considered due if it happens within `org-deadline-warning-days'
  13228. days from today's date. If the deadline appears in an entry marked DONE,
  13229. it is not shown. A numeric prefix argument NDAYS can be used to test that
  13230. many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
  13231. are shown."
  13232. (interactive "P")
  13233. (let* ((org-warn-days
  13234. (cond
  13235. ((equal ndays '(4)) 100000)
  13236. (ndays (prefix-numeric-value ndays))
  13237. (t (abs org-deadline-warning-days))))
  13238. (case-fold-search nil)
  13239. (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  13240. (callback
  13241. (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  13242. (message "%d deadlines past-due or due within %d days"
  13243. (org-occur regexp nil callback)
  13244. org-warn-days)))
  13245. (defsubst org-re-timestamp (type)
  13246. "Return a regexp for timestamp TYPE.
  13247. Allowed values for TYPE are:
  13248. all: all timestamps
  13249. active: only active timestamps (<...>)
  13250. inactive: only inactive timestamps ([...])
  13251. scheduled: only scheduled timestamps
  13252. deadline: only deadline timestamps
  13253. closed: only closed time-stamps
  13254. When TYPE is nil, fall back on returning a regexp that matches
  13255. both scheduled and deadline timestamps."
  13256. (cl-case type
  13257. (all org-ts-regexp-both)
  13258. (active org-ts-regexp)
  13259. (inactive org-ts-regexp-inactive)
  13260. (scheduled org-scheduled-time-regexp)
  13261. (deadline org-deadline-time-regexp)
  13262. (closed org-closed-time-regexp)
  13263. (otherwise
  13264. (concat "\\<"
  13265. (regexp-opt (list org-deadline-string org-scheduled-string))
  13266. " *<\\([^>]+\\)>"))))
  13267. (defun org-check-before-date (d)
  13268. "Check if there are deadlines or scheduled entries before date D."
  13269. (interactive (list (org-read-date)))
  13270. (let* ((case-fold-search nil)
  13271. (regexp (org-re-timestamp org-ts-type))
  13272. (ts-type org-ts-type)
  13273. (callback
  13274. (lambda ()
  13275. (let ((match (match-string 1)))
  13276. (and (if (memq ts-type '(active inactive all))
  13277. (eq (org-element-type (save-excursion
  13278. (backward-char)
  13279. (org-element-context)))
  13280. 'timestamp)
  13281. (org-at-planning-p))
  13282. (time-less-p
  13283. (org-time-string-to-time match)
  13284. (org-time-string-to-time d)))))))
  13285. (message "%d entries before %s"
  13286. (org-occur regexp nil callback)
  13287. d)))
  13288. (defun org-check-after-date (d)
  13289. "Check if there are deadlines or scheduled entries after date D."
  13290. (interactive (list (org-read-date)))
  13291. (let* ((case-fold-search nil)
  13292. (regexp (org-re-timestamp org-ts-type))
  13293. (ts-type org-ts-type)
  13294. (callback
  13295. (lambda ()
  13296. (let ((match (match-string 1)))
  13297. (and (if (memq ts-type '(active inactive all))
  13298. (eq (org-element-type (save-excursion
  13299. (backward-char)
  13300. (org-element-context)))
  13301. 'timestamp)
  13302. (org-at-planning-p))
  13303. (not (time-less-p
  13304. (org-time-string-to-time match)
  13305. (org-time-string-to-time d))))))))
  13306. (message "%d entries after %s"
  13307. (org-occur regexp nil callback)
  13308. d)))
  13309. (defun org-check-dates-range (start-date end-date)
  13310. "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  13311. (interactive (list (org-read-date nil nil nil "Range starts")
  13312. (org-read-date nil nil nil "Range end")))
  13313. (let ((case-fold-search nil)
  13314. (regexp (org-re-timestamp org-ts-type))
  13315. (callback
  13316. (let ((type org-ts-type))
  13317. (lambda ()
  13318. (let ((match (match-string 1)))
  13319. (and
  13320. (if (memq type '(active inactive all))
  13321. (eq (org-element-type (save-excursion
  13322. (backward-char)
  13323. (org-element-context)))
  13324. 'timestamp)
  13325. (org-at-planning-p))
  13326. (not (time-less-p
  13327. (org-time-string-to-time match)
  13328. (org-time-string-to-time start-date)))
  13329. (time-less-p
  13330. (org-time-string-to-time match)
  13331. (org-time-string-to-time end-date))))))))
  13332. (message "%d entries between %s and %s"
  13333. (org-occur regexp nil callback) start-date end-date)))
  13334. (defun org-evaluate-time-range (&optional to-buffer)
  13335. "Evaluate a time range by computing the difference between start and end.
  13336. Normally the result is just printed in the echo area, but with prefix arg
  13337. TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  13338. If the time range is actually in a table, the result is inserted into the
  13339. next column.
  13340. For time difference computation, a year is assumed to be exactly 365
  13341. days in order to avoid rounding problems."
  13342. (interactive "P")
  13343. (or
  13344. (org-clock-update-time-maybe)
  13345. (save-excursion
  13346. (unless (org-at-date-range-p t)
  13347. (goto-char (point-at-bol))
  13348. (re-search-forward org-tr-regexp-both (point-at-eol) t))
  13349. (unless (org-at-date-range-p t)
  13350. (user-error "Not at a time-stamp range, and none found in current line")))
  13351. (let* ((ts1 (match-string 1))
  13352. (ts2 (match-string 2))
  13353. (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  13354. (match-end (match-end 0))
  13355. (time1 (org-time-string-to-time ts1))
  13356. (time2 (org-time-string-to-time ts2))
  13357. (diff (abs (float-time (time-subtract time2 time1))))
  13358. (negative (time-less-p time2 time1))
  13359. ;; (ys (floor (* 365 24 60 60)))
  13360. (ds (* 24 60 60))
  13361. (hs (* 60 60))
  13362. (fy "%dy %dd %02d:%02d")
  13363. (fy1 "%dy %dd")
  13364. (fd "%dd %02d:%02d")
  13365. (fd1 "%dd")
  13366. (fh "%02d:%02d")
  13367. y d h m align)
  13368. (if havetime
  13369. (setq ; y (floor diff ys) diff (mod diff ys)
  13370. y 0
  13371. d (floor diff ds) diff (mod diff ds)
  13372. h (floor diff hs) diff (mod diff hs)
  13373. m (floor diff 60))
  13374. (setq ; y (floor diff ys) diff (mod diff ys)
  13375. y 0
  13376. d (round diff ds)
  13377. h 0 m 0))
  13378. (if (not to-buffer)
  13379. (message "%s" (org-make-tdiff-string y d h m))
  13380. (if (org-at-table-p)
  13381. (progn
  13382. (goto-char match-end)
  13383. (setq align t)
  13384. (and (looking-at " *|") (goto-char (match-end 0))))
  13385. (goto-char match-end))
  13386. (when (looking-at
  13387. "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  13388. (replace-match ""))
  13389. (when negative (insert " -"))
  13390. (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  13391. (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  13392. (insert " " (format fh h m))))
  13393. (when align (org-table-align))
  13394. (message "Time difference inserted")))))
  13395. (defun org-make-tdiff-string (y d h m)
  13396. (let ((fmt "")
  13397. (l nil))
  13398. (when (> y 0)
  13399. (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  13400. (push y l))
  13401. (when (> d 0)
  13402. (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
  13403. (push d l))
  13404. (when (> h 0)
  13405. (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  13406. (push h l))
  13407. (when (> m 0)
  13408. (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  13409. (push m l))
  13410. (apply 'format fmt (nreverse l))))
  13411. (defun org-time-string-to-time (s)
  13412. "Convert timestamp string S into internal time."
  13413. (apply #'encode-time (org-parse-time-string s)))
  13414. (defun org-time-string-to-seconds (s)
  13415. "Convert a timestamp string S into a number of seconds."
  13416. (float-time (org-time-string-to-time s)))
  13417. (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  13418. (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  13419. "Convert time stamp S to an absolute day number.
  13420. If DAYNR in non-nil, and there is a specifier for a cyclic time
  13421. stamp, get the closest date to DAYNR. If PREFER is
  13422. `past' (respectively `future') return a date past (respectively
  13423. after) or equal to DAYNR.
  13424. POS is the location of time stamp S, as a buffer position in
  13425. BUFFER.
  13426. Diary sexp timestamps are matched against DAYNR, when non-nil.
  13427. If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  13428. signaled."
  13429. (cond
  13430. ((string-match "\\`%%\\((.*)\\)" s)
  13431. ;; Sexp timestamp: try to match DAYNR, if available, since we're
  13432. ;; only able to match individual dates. If it fails, raise an
  13433. ;; error.
  13434. (if (and daynr
  13435. (org-diary-sexp-entry
  13436. (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  13437. daynr
  13438. (signal 'org-diary-sexp-no-match (list s))))
  13439. (daynr (org-closest-date s daynr prefer))
  13440. (t (time-to-days
  13441. (condition-case errdata
  13442. (org-time-string-to-time s)
  13443. (error (error "Bad timestamp `%s'%s\nError was: %s"
  13444. s
  13445. (if (not (and buffer pos)) ""
  13446. (format-message " at %d in buffer `%s'" pos buffer))
  13447. (cdr errdata))))))))
  13448. (defun org-days-to-iso-week (days)
  13449. "Return the ISO week number."
  13450. (require 'cal-iso)
  13451. (car (calendar-iso-from-absolute days)))
  13452. (defun org-small-year-to-year (year)
  13453. "Convert 2-digit years into 4-digit years.
  13454. YEAR is expanded into one of the 30 next years, if possible, or
  13455. into a past one. Any year larger than 99 is returned unchanged."
  13456. (if (>= year 100) year
  13457. (let* ((current (string-to-number (format-time-string "%Y")))
  13458. (century (/ current 100))
  13459. (offset (- year (% current 100))))
  13460. (cond ((> offset 30) (+ (* (1- century) 100) year))
  13461. ((> offset -70) (+ (* century 100) year))
  13462. (t (+ (* (1+ century) 100) year))))))
  13463. (defun org-time-from-absolute (d)
  13464. "Return the time corresponding to date D.
  13465. D may be an absolute day number, or a calendar-type list (month day year)."
  13466. (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  13467. (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  13468. (defvar org-agenda-current-date)
  13469. (defun org-calendar-holiday ()
  13470. "List of holidays, for Diary display in Org mode."
  13471. (require 'holidays)
  13472. (let ((hl (calendar-check-holidays org-agenda-current-date)))
  13473. (and hl (mapconcat #'identity hl "; "))))
  13474. (defun org-diary-sexp-entry (sexp entry d)
  13475. "Process a SEXP diary ENTRY for date D."
  13476. (require 'diary-lib)
  13477. ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  13478. ;; dynamically.
  13479. (let* ((sexp `(let ((entry ,entry)
  13480. (date ',d))
  13481. ,(car (read-from-string sexp))))
  13482. (result (if calendar-debug-sexp (eval sexp)
  13483. (condition-case nil
  13484. (eval sexp)
  13485. (error
  13486. (beep)
  13487. (message "Bad sexp at line %d in %s: %s"
  13488. (org-current-line)
  13489. (buffer-file-name) sexp)
  13490. (sleep-for 2))))))
  13491. (cond ((stringp result) (split-string result "; "))
  13492. ((and (consp result)
  13493. (not (consp (cdr result)))
  13494. (stringp (cdr result))) (cdr result))
  13495. ((and (consp result)
  13496. (stringp (car result))) result)
  13497. (result entry))))
  13498. (defun org-diary-to-ical-string (frombuf)
  13499. "Get iCalendar entries from diary entries in buffer FROMBUF.
  13500. This uses the icalendar.el library."
  13501. (let* ((tmpdir temporary-file-directory)
  13502. (tmpfile (make-temp-name
  13503. (expand-file-name "orgics" tmpdir)))
  13504. buf rtn b e)
  13505. (with-current-buffer frombuf
  13506. (icalendar-export-region (point-min) (point-max) tmpfile)
  13507. (setq buf (find-buffer-visiting tmpfile))
  13508. (set-buffer buf)
  13509. (goto-char (point-min))
  13510. (when (re-search-forward "^BEGIN:VEVENT" nil t)
  13511. (setq b (match-beginning 0)))
  13512. (goto-char (point-max))
  13513. (when (re-search-backward "^END:VEVENT" nil t)
  13514. (setq e (match-end 0)))
  13515. (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  13516. (kill-buffer buf)
  13517. (delete-file tmpfile)
  13518. rtn))
  13519. (defun org-closest-date (start current prefer)
  13520. "Return closest date to CURRENT starting from START.
  13521. CURRENT and START are both time stamps.
  13522. When PREFER is `past', return a date that is either CURRENT or
  13523. past. When PREFER is `future', return a date that is either
  13524. CURRENT or future.
  13525. Only time stamps with a repeater are modified. Any other time
  13526. stamp stay unchanged. In any case, return value is an absolute
  13527. day number."
  13528. (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  13529. ;; No repeater. Do not shift time stamp.
  13530. (time-to-days (org-time-string-to-time start))
  13531. (let ((value (string-to-number (match-string 1 start)))
  13532. (type (match-string 2 start)))
  13533. (if (= 0 value)
  13534. ;; Repeater with a 0-value is considered as void.
  13535. (time-to-days (org-time-string-to-time start))
  13536. (let* ((base (org-date-to-gregorian start))
  13537. (target (org-date-to-gregorian current))
  13538. (sday (calendar-absolute-from-gregorian base))
  13539. (cday (calendar-absolute-from-gregorian target))
  13540. n1 n2)
  13541. ;; If START is already past CURRENT, just return START.
  13542. (if (<= cday sday) sday
  13543. ;; Compute closest date before (N1) and closest date past
  13544. ;; (N2) CURRENT.
  13545. (pcase type
  13546. ("h"
  13547. (let ((missing-hours
  13548. (mod (+ (- (* 24 (- cday sday))
  13549. (nth 2 (org-parse-time-string start)))
  13550. org-extend-today-until)
  13551. value)))
  13552. (setf n1 (if (= missing-hours 0) cday
  13553. (- cday (1+ (/ missing-hours 24)))))
  13554. (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  13555. ((or "d" "w")
  13556. (let ((value (if (equal type "w") (* 7 value) value)))
  13557. (setf n1 (+ sday (* value (/ (- cday sday) value))))
  13558. (setf n2 (+ n1 value))))
  13559. ("m"
  13560. (let* ((add-months
  13561. (lambda (d n)
  13562. ;; Add N months to gregorian date D, i.e.,
  13563. ;; a list (MONTH DAY YEAR). Return a valid
  13564. ;; gregorian date.
  13565. (let ((m (+ (nth 0 d) n)))
  13566. (list (mod m 12)
  13567. (nth 1 d)
  13568. (+ (/ m 12) (nth 2 d))))))
  13569. (months ; Complete months to TARGET.
  13570. (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  13571. (- (nth 0 target) (nth 0 base))
  13572. ;; If START's day is greater than
  13573. ;; TARGET's, remove incomplete month.
  13574. (if (> (nth 1 target) (nth 1 base)) 0 -1))
  13575. value)
  13576. value))
  13577. (before (funcall add-months base months)))
  13578. (setf n1 (calendar-absolute-from-gregorian before))
  13579. (setf n2
  13580. (calendar-absolute-from-gregorian
  13581. (funcall add-months before value)))))
  13582. (_
  13583. (let* ((d (nth 1 base))
  13584. (m (nth 0 base))
  13585. (y (nth 2 base))
  13586. (years ; Complete years to TARGET.
  13587. (* (/ (- (nth 2 target)
  13588. y
  13589. ;; If START's month and day are
  13590. ;; greater than TARGET's, remove
  13591. ;; incomplete year.
  13592. (if (or (> (nth 0 target) m)
  13593. (and (= (nth 0 target) m)
  13594. (> (nth 1 target) d)))
  13595. 0
  13596. 1))
  13597. value)
  13598. value))
  13599. (before (list m d (+ y years))))
  13600. (setf n1 (calendar-absolute-from-gregorian before))
  13601. (setf n2 (calendar-absolute-from-gregorian
  13602. (list m d (+ (nth 2 before) value)))))))
  13603. ;; Handle PREFER parameter, if any.
  13604. (cond
  13605. ((eq prefer 'past) (if (= cday n2) n2 n1))
  13606. ((eq prefer 'future) (if (= cday n1) n1 n2))
  13607. (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  13608. (defun org-date-to-gregorian (d)
  13609. "Turn any specification of date D into a Gregorian date for the calendar."
  13610. (cond ((integerp d) (calendar-gregorian-from-absolute d))
  13611. ((and (listp d) (= (length d) 3)) d)
  13612. ((stringp d)
  13613. (let ((d (org-parse-time-string d)))
  13614. (list (nth 4 d) (nth 3 d) (nth 5 d))))
  13615. ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  13616. (defun org-timestamp-up (&optional arg)
  13617. "Increase the date item at the cursor by one.
  13618. If the cursor is on the year, change the year. If it is on the month,
  13619. the day or the time, change that. If the cursor is on the enclosing
  13620. bracket, change the timestamp type.
  13621. With prefix ARG, change by that many units."
  13622. (interactive "p")
  13623. (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  13624. (defun org-timestamp-down (&optional arg)
  13625. "Decrease the date item at the cursor by one.
  13626. If the cursor is on the year, change the year. If it is on the month,
  13627. the day or the time, change that. If the cursor is on the enclosing
  13628. bracket, change the timestamp type.
  13629. With prefix ARG, change by that many units."
  13630. (interactive "p")
  13631. (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  13632. (defun org-timestamp-up-day (&optional arg)
  13633. "Increase the date in the time stamp by one day.
  13634. With prefix ARG, change that many days."
  13635. (interactive "p")
  13636. (if (and (not (org-at-timestamp-p 'lax))
  13637. (org-at-heading-p))
  13638. (org-todo 'up)
  13639. (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  13640. (defun org-timestamp-down-day (&optional arg)
  13641. "Decrease the date in the time stamp by one day.
  13642. With prefix ARG, change that many days."
  13643. (interactive "p")
  13644. (if (and (not (org-at-timestamp-p 'lax))
  13645. (org-at-heading-p))
  13646. (org-todo 'down)
  13647. (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  13648. (defun org-at-timestamp-p (&optional extended)
  13649. "Non-nil if point is inside a timestamp.
  13650. By default, the function only consider syntactically valid active
  13651. timestamps. However, the caller may have a broader definition
  13652. for timestamps. As a consequence, optional argument EXTENDED can
  13653. be set to the following values
  13654. `inactive'
  13655. Include also syntactically valid inactive timestamps.
  13656. `agenda'
  13657. Include timestamps allowed in Agenda, i.e., those in
  13658. properties drawers, planning lines and clock lines.
  13659. `lax'
  13660. Ignore context. The function matches any part of the
  13661. document looking like a timestamp. This includes comments,
  13662. example blocks...
  13663. For backward-compatibility with Org 9.0, every other non-nil
  13664. value is equivalent to `inactive'.
  13665. When at a timestamp, return the position of the point as a symbol
  13666. among `bracket', `after', `year', `month', `hour', `minute',
  13667. `day' or a number of character from the last know part of the
  13668. time stamp.
  13669. When matching, the match groups are the following:
  13670. group 1: year
  13671. group 2: month
  13672. group 3: day number
  13673. group 4: day name
  13674. group 5: hours, if any
  13675. group 6: minutes, if any"
  13676. (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
  13677. (pos (point))
  13678. (match?
  13679. (let ((boundaries (org-in-regexp regexp)))
  13680. (save-match-data
  13681. (cond ((null boundaries) nil)
  13682. ((eq extended 'lax) t)
  13683. (t
  13684. (or (and (eq extended 'agenda)
  13685. (or (org-at-planning-p)
  13686. (org-at-property-p)
  13687. (and (bound-and-true-p
  13688. org-agenda-include-inactive-timestamps)
  13689. (org-at-clock-log-p))))
  13690. (eq 'timestamp
  13691. (save-excursion
  13692. (when (= pos (cdr boundaries)) (forward-char -1))
  13693. (org-element-type (org-element-context)))))))))))
  13694. (cond
  13695. ((not match?) nil)
  13696. ((= pos (match-beginning 0)) 'bracket)
  13697. ;; Distinguish location right before the closing bracket from
  13698. ;; right after it.
  13699. ((= pos (1- (match-end 0))) 'bracket)
  13700. ((= pos (match-end 0)) 'after)
  13701. ((org-pos-in-match-range pos 2) 'year)
  13702. ((org-pos-in-match-range pos 3) 'month)
  13703. ((org-pos-in-match-range pos 7) 'hour)
  13704. ((org-pos-in-match-range pos 8) 'minute)
  13705. ((or (org-pos-in-match-range pos 4)
  13706. (org-pos-in-match-range pos 5)) 'day)
  13707. ((and (> pos (or (match-end 8) (match-end 5)))
  13708. (< pos (match-end 0)))
  13709. (- pos (or (match-end 8) (match-end 5))))
  13710. (t 'day))))
  13711. (defun org-toggle-timestamp-type ()
  13712. "Toggle the type (<active> or [inactive]) of a time stamp."
  13713. (interactive)
  13714. (when (org-at-timestamp-p 'lax)
  13715. (let ((beg (match-beginning 0)) (end (match-end 0))
  13716. (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  13717. (save-excursion
  13718. (goto-char beg)
  13719. (while (re-search-forward "[][<>]" end t)
  13720. (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  13721. t t)))
  13722. (message "Timestamp is now %sactive"
  13723. (if (equal (char-after beg) ?<) "" "in")))))
  13724. (defun org-at-clock-log-p ()
  13725. "Non-nil if point is on a clock log line."
  13726. (and (org-match-line org-clock-line-re)
  13727. (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  13728. (defvar org-clock-history) ; defined in org-clock.el
  13729. (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
  13730. (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  13731. "Change the date in the time stamp at point.
  13732. The date is changed by N times WHAT. WHAT can be `day', `month',
  13733. `year', `hour', or `minute'. If WHAT is not given, the cursor
  13734. position in the timestamp determines what is changed.
  13735. When optional argument UPDOWN is non-nil, minutes are rounded
  13736. according to `org-time-stamp-rounding-minutes'.
  13737. When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  13738. \"--2d\"."
  13739. (let ((origin (point))
  13740. (timestamp? (org-at-timestamp-p 'lax))
  13741. origin-cat
  13742. with-hm inactive
  13743. (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  13744. extra rem
  13745. ts time time0 fixnext clrgx)
  13746. (unless timestamp? (user-error "Not at a timestamp"))
  13747. (if (and (not what) (eq timestamp? 'bracket))
  13748. (org-toggle-timestamp-type)
  13749. ;; Point isn't on brackets. Remember the part of the time-stamp
  13750. ;; the point was in. Indeed, size of time-stamps may change,
  13751. ;; but point must be kept in the same category nonetheless.
  13752. (setq origin-cat timestamp?)
  13753. (when (and (not what) (not (eq timestamp? 'day))
  13754. org-display-custom-times
  13755. (get-text-property (point) 'display)
  13756. (not (get-text-property (1- (point)) 'display)))
  13757. (setq timestamp? 'day))
  13758. (setq timestamp? (or what timestamp?)
  13759. inactive (= (char-after (match-beginning 0)) ?\[)
  13760. ts (match-string 0))
  13761. (replace-match "")
  13762. (when (string-match
  13763. "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  13764. ts)
  13765. (setq extra (match-string 1 ts))
  13766. (when suppress-tmp-delay
  13767. (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  13768. (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  13769. (setq with-hm t))
  13770. (setq time0 (org-parse-time-string ts))
  13771. (when (and updown
  13772. (eq timestamp? 'minute)
  13773. (not current-prefix-arg))
  13774. ;; This looks like s-up and s-down. Change by one rounding step.
  13775. (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  13776. (unless (= 0 (setq rem (% (nth 1 time0) dm)))
  13777. (setcar (cdr time0) (+ (nth 1 time0)
  13778. (if (> n 0) (- rem) (- dm rem))))))
  13779. (setq time
  13780. (apply #'encode-time
  13781. (or (car time0) 0)
  13782. (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  13783. (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
  13784. (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
  13785. (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
  13786. (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
  13787. (nthcdr 6 time0)))
  13788. (when (and (memq timestamp? '(hour minute))
  13789. extra
  13790. (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  13791. (setq extra (org-modify-ts-extra
  13792. extra
  13793. (if (eq timestamp? 'hour) 2 5)
  13794. n dm)))
  13795. (when (integerp timestamp?)
  13796. (setq extra (org-modify-ts-extra extra timestamp? n dm)))
  13797. (when (eq what 'calendar)
  13798. (let ((cal-date (org-get-date-from-calendar)))
  13799. (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  13800. (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  13801. (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  13802. (setcar time0 (or (car time0) 0))
  13803. (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  13804. (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  13805. (setq time (apply 'encode-time time0))))
  13806. ;; Insert the new time-stamp, and ensure point stays in the same
  13807. ;; category as before (i.e. not after the last position in that
  13808. ;; category).
  13809. (let ((pos (point)))
  13810. ;; Stay before inserted string. `save-excursion' is of no use.
  13811. (setq org-last-changed-timestamp
  13812. (org-insert-time-stamp time with-hm inactive nil nil extra))
  13813. (goto-char pos))
  13814. (save-match-data
  13815. (looking-at org-ts-regexp3)
  13816. (goto-char
  13817. (pcase origin-cat
  13818. ;; `day' category ends before `hour' if any, or at the end
  13819. ;; of the day name.
  13820. (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  13821. (`hour (min (match-end 7) origin))
  13822. (`minute (min (1- (match-end 8)) origin))
  13823. ((pred integerp) (min (1- (match-end 0)) origin))
  13824. ;; Point was right after the time-stamp. However, the
  13825. ;; time-stamp length might have changed, so refer to
  13826. ;; (match-end 0) instead.
  13827. (`after (match-end 0))
  13828. ;; `year' and `month' have both fixed size: point couldn't
  13829. ;; have moved into another part.
  13830. (_ origin))))
  13831. ;; Update clock if on a CLOCK line.
  13832. (org-clock-update-time-maybe)
  13833. ;; Maybe adjust the closest clock in `org-clock-history'
  13834. (when org-clock-adjust-closest
  13835. (if (not (and (org-at-clock-log-p)
  13836. (< 1 (length (delq nil (mapcar 'marker-position
  13837. org-clock-history))))))
  13838. (message "No clock to adjust")
  13839. (cond ((save-excursion ; fix previous clock?
  13840. (re-search-backward org-ts-regexp0 nil t)
  13841. (looking-back (concat org-clock-string " \\[")
  13842. (line-beginning-position)))
  13843. (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  13844. ((save-excursion ; fix next clock?
  13845. (re-search-backward org-ts-regexp0 nil t)
  13846. (looking-at (concat org-ts-regexp0 "\\] =>")))
  13847. (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  13848. (save-window-excursion
  13849. ;; Find closest clock to point, adjust the previous/next one in history
  13850. (let* ((p (save-excursion (org-back-to-heading t)))
  13851. (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  13852. (clfixnth
  13853. (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  13854. (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  13855. (if (not clfixpos)
  13856. (message "No clock to adjust")
  13857. (save-excursion
  13858. (org-goto-marker-or-bmk clfixpos)
  13859. (org-show-subtree)
  13860. (when (re-search-forward clrgx nil t)
  13861. (goto-char (match-beginning 1))
  13862. (let (org-clock-adjust-closest)
  13863. (org-timestamp-change n timestamp? updown))
  13864. (message "Clock adjusted in %s for heading: %s"
  13865. (file-name-nondirectory (buffer-file-name))
  13866. (org-get-heading t t)))))))))
  13867. ;; Try to recenter the calendar window, if any.
  13868. (when (and org-calendar-follow-timestamp-change
  13869. (get-buffer-window "*Calendar*" t)
  13870. (memq timestamp? '(day month year)))
  13871. (org-recenter-calendar (time-to-days time))))))
  13872. (defun org-modify-ts-extra (s pos n dm)
  13873. "Change the different parts of the lead-time and repeat fields in timestamp."
  13874. (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  13875. ng h m new rem)
  13876. (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  13877. (cond
  13878. ((or (org-pos-in-match-range pos 2)
  13879. (org-pos-in-match-range pos 3))
  13880. (setq m (string-to-number (match-string 3 s))
  13881. h (string-to-number (match-string 2 s)))
  13882. (if (org-pos-in-match-range pos 2)
  13883. (setq h (+ h n))
  13884. (setq n (* dm (with-no-warnings (cl-signum n))))
  13885. (unless (= 0 (setq rem (% m dm)))
  13886. (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  13887. (setq m (+ m n)))
  13888. (when (< m 0) (setq m (+ m 60) h (1- h)))
  13889. (when (> m 59) (setq m (- m 60) h (1+ h)))
  13890. (setq h (mod h 24))
  13891. (setq ng 1 new (format "-%02d:%02d" h m)))
  13892. ((org-pos-in-match-range pos 6)
  13893. (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  13894. ((org-pos-in-match-range pos 5)
  13895. (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  13896. ((org-pos-in-match-range pos 9)
  13897. (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  13898. ((org-pos-in-match-range pos 8)
  13899. (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  13900. (when ng
  13901. (setq s (concat
  13902. (substring s 0 (match-beginning ng))
  13903. new
  13904. (substring s (match-end ng))))))
  13905. s))
  13906. (defun org-recenter-calendar (d)
  13907. "If the calendar is visible, recenter it to date D."
  13908. (let ((cwin (get-buffer-window "*Calendar*" t)))
  13909. (when cwin
  13910. (let ((calendar-move-hook nil))
  13911. (with-selected-window cwin
  13912. (calendar-goto-date
  13913. (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  13914. (defun org-goto-calendar (&optional arg)
  13915. "Go to the Emacs calendar at the current date.
  13916. If there is a time stamp in the current line, go to that date.
  13917. A prefix ARG can be used to force the current date."
  13918. (interactive "P")
  13919. (let ((calendar-move-hook nil)
  13920. (calendar-view-holidays-initially-flag nil)
  13921. (calendar-view-diary-initially-flag nil)
  13922. diff)
  13923. (when (or (org-at-timestamp-p 'lax)
  13924. (org-match-line (concat ".*" org-ts-regexp)))
  13925. (let ((d1 (time-to-days nil))
  13926. (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  13927. (setq diff (- d2 d1))))
  13928. (calendar)
  13929. (calendar-goto-today)
  13930. (when (and diff (not arg)) (calendar-forward-day diff))))
  13931. (defun org-get-date-from-calendar ()
  13932. "Return a list (month day year) of date at point in calendar."
  13933. (with-current-buffer "*Calendar*"
  13934. (save-match-data
  13935. (calendar-cursor-to-date))))
  13936. (defun org-date-from-calendar ()
  13937. "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  13938. If there is already a time stamp at the cursor position, update it."
  13939. (interactive)
  13940. (if (org-at-timestamp-p 'lax)
  13941. (org-timestamp-change 0 'calendar)
  13942. (let ((cal-date (org-get-date-from-calendar)))
  13943. (org-insert-time-stamp
  13944. (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  13945. (defcustom org-image-actual-width t
  13946. "When non-nil, use the actual width of images when inlining them.
  13947. When set to a number, use imagemagick (when available) to set the
  13948. image's width to this value.
  13949. When set to a number in a list, try to get the width from any
  13950. #+ATTR.* keyword if it matches a width specification like
  13951. #+ATTR_HTML: :width 300px
  13952. and fall back on that number if none is found.
  13953. When set to nil, try to get the width from an #+ATTR.* keyword
  13954. and fall back on the original width if none is found.
  13955. When set to any other non-nil value, always use the image width.
  13956. This requires Emacs >= 24.1, built with imagemagick support."
  13957. :group 'org-appearance
  13958. :version "24.4"
  13959. :package-version '(Org . "8.0")
  13960. :type '(choice
  13961. (const :tag "Use the image width" t)
  13962. (integer :tag "Use a number of pixels")
  13963. (list :tag "Use #+ATTR* or a number of pixels" (integer))
  13964. (const :tag "Use #+ATTR* or don't resize" nil)))
  13965. (defcustom org-agenda-inhibit-startup nil
  13966. "Inhibit startup when preparing agenda buffers.
  13967. When this variable is t, the initialization of the Org agenda
  13968. buffers is inhibited: e.g. the visibility state is not set, the
  13969. tables are not re-aligned, etc."
  13970. :type 'boolean
  13971. :version "24.3"
  13972. :group 'org-agenda)
  13973. (defcustom org-agenda-ignore-properties nil
  13974. "Avoid updating text properties when building the agenda.
  13975. Properties are used to prepare buffers for effort estimates,
  13976. appointments, statistics and subtree-local categories.
  13977. If you don't use these in the agenda, you can add them to this
  13978. list and agenda building will be a bit faster.
  13979. The value is a list, with zero or more of the symbols `effort', `appt',
  13980. `stats' or `category'."
  13981. :type '(set :greedy t
  13982. (const effort)
  13983. (const appt)
  13984. (const stats)
  13985. (const category))
  13986. :version "26.1"
  13987. :package-version '(Org . "8.3")
  13988. :group 'org-agenda)
  13989. ;;;; Files
  13990. (defun org-save-all-org-buffers ()
  13991. "Save all Org buffers without user confirmation."
  13992. (interactive)
  13993. (message "Saving all Org buffers...")
  13994. (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
  13995. (when (featurep 'org-id) (org-id-locations-save))
  13996. (message "Saving all Org buffers... done"))
  13997. (defun org-revert-all-org-buffers ()
  13998. "Revert all Org buffers.
  13999. Prompt for confirmation when there are unsaved changes.
  14000. Be sure you know what you are doing before letting this function
  14001. overwrite your changes.
  14002. This function is useful in a setup where one tracks Org files
  14003. with a version control system, to revert on one machine after pulling
  14004. changes from another. I believe the procedure must be like this:
  14005. 1. \\[org-save-all-org-buffers]
  14006. 2. Pull changes from the other machine, resolve conflicts
  14007. 3. \\[org-revert-all-org-buffers]"
  14008. (interactive)
  14009. (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  14010. (user-error "Abort"))
  14011. (save-excursion
  14012. (save-window-excursion
  14013. (dolist (b (buffer-list))
  14014. (when (and (with-current-buffer b (derived-mode-p 'org-mode))
  14015. (with-current-buffer b buffer-file-name))
  14016. (pop-to-buffer-same-window b)
  14017. (revert-buffer t 'no-confirm)))
  14018. (when (and (featurep 'org-id) org-id-track-globally)
  14019. (org-id-locations-load)))))
  14020. ;;;; Agenda files
  14021. ;;;###autoload
  14022. (defun org-switchb (&optional arg)
  14023. "Switch between Org buffers.
  14024. With `\\[universal-argument]' prefix, restrict available buffers to files.
  14025. With `\\[universal-argument] \\[universal-argument]' \
  14026. prefix, restrict available buffers to agenda files."
  14027. (interactive "P")
  14028. (let ((blist (org-buffer-list
  14029. (cond ((equal arg '(4)) 'files)
  14030. ((equal arg '(16)) 'agenda)))))
  14031. (pop-to-buffer-same-window
  14032. (completing-read "Org buffer: "
  14033. (mapcar #'list (mapcar #'buffer-name blist))
  14034. nil t))))
  14035. (defun org-buffer-list (&optional predicate exclude-tmp)
  14036. "Return a list of Org buffers.
  14037. PREDICATE can be `export', `files' or `agenda'.
  14038. export restrict the list to Export buffers.
  14039. files restrict the list to buffers visiting Org files.
  14040. agenda restrict the list to buffers visiting agenda files.
  14041. If EXCLUDE-TMP is non-nil, ignore temporary buffers."
  14042. (let* ((bfn nil)
  14043. (agenda-files (and (eq predicate 'agenda)
  14044. (mapcar 'file-truename (org-agenda-files t))))
  14045. (filter
  14046. (cond
  14047. ((eq predicate 'files)
  14048. (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
  14049. ((eq predicate 'export)
  14050. (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
  14051. ((eq predicate 'agenda)
  14052. (lambda (b)
  14053. (with-current-buffer b
  14054. (and (derived-mode-p 'org-mode)
  14055. (setq bfn (buffer-file-name b))
  14056. (member (file-truename bfn) agenda-files)))))
  14057. (t (lambda (b) (with-current-buffer b
  14058. (or (derived-mode-p 'org-mode)
  14059. (string-match "\\*Org .*Export"
  14060. (buffer-name b)))))))))
  14061. (delq nil
  14062. (mapcar
  14063. (lambda(b)
  14064. (if (and (funcall filter b)
  14065. (or (not exclude-tmp)
  14066. (not (string-match "tmp" (buffer-name b)))))
  14067. b
  14068. nil))
  14069. (buffer-list)))))
  14070. (defun org-agenda-files (&optional unrestricted archives)
  14071. "Get the list of agenda files.
  14072. Optional UNRESTRICTED means return the full list even if a restriction
  14073. is currently in place.
  14074. When ARCHIVES is t, include all archive files that are really being
  14075. used by the agenda files. If ARCHIVE is `ifmode', do this only if
  14076. `org-agenda-archives-mode' is t."
  14077. (let ((files
  14078. (cond
  14079. ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  14080. ((stringp org-agenda-files) (org-read-agenda-file-list))
  14081. ((listp org-agenda-files) org-agenda-files)
  14082. (t (error "Invalid value of `org-agenda-files'")))))
  14083. (setq files (apply 'append
  14084. (mapcar (lambda (f)
  14085. (if (file-directory-p f)
  14086. (directory-files
  14087. f t org-agenda-file-regexp)
  14088. (list (expand-file-name f org-directory))))
  14089. files)))
  14090. (when org-agenda-skip-unavailable-files
  14091. (setq files (delq nil
  14092. (mapcar (lambda (file)
  14093. (and (file-readable-p file) file))
  14094. files))))
  14095. (when (or (eq archives t)
  14096. (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  14097. (setq files (org-add-archive-files files)))
  14098. files))
  14099. (defun org-agenda-file-p (&optional file)
  14100. "Return non-nil, if FILE is an agenda file.
  14101. If FILE is omitted, use the file associated with the current
  14102. buffer."
  14103. (let ((fname (or file (buffer-file-name))))
  14104. (and fname
  14105. (member (file-truename fname)
  14106. (mapcar #'file-truename (org-agenda-files t))))))
  14107. (defun org-edit-agenda-file-list ()
  14108. "Edit the list of agenda files.
  14109. Depending on setup, this either uses customize to edit the variable
  14110. `org-agenda-files', or it visits the file that is holding the list. In the
  14111. latter case, the buffer is set up in a way that saving it automatically kills
  14112. the buffer and restores the previous window configuration."
  14113. (interactive)
  14114. (if (stringp org-agenda-files)
  14115. (let ((cw (current-window-configuration)))
  14116. (find-file org-agenda-files)
  14117. (setq-local org-window-configuration cw)
  14118. (add-hook 'after-save-hook
  14119. (lambda ()
  14120. (set-window-configuration
  14121. (prog1 org-window-configuration
  14122. (kill-buffer (current-buffer))))
  14123. (org-install-agenda-files-menu)
  14124. (message "New agenda file list installed"))
  14125. nil 'local)
  14126. (message "%s" (substitute-command-keys
  14127. "Edit list and finish with \\[save-buffer]")))
  14128. (customize-variable 'org-agenda-files)))
  14129. (defun org-store-new-agenda-file-list (list)
  14130. "Set new value for the agenda file list and save it correctly."
  14131. (if (stringp org-agenda-files)
  14132. (let ((fe (org-read-agenda-file-list t)) b u)
  14133. (while (setq b (find-buffer-visiting org-agenda-files))
  14134. (kill-buffer b))
  14135. (with-temp-file org-agenda-files
  14136. (insert
  14137. (mapconcat
  14138. (lambda (f) ;; Keep un-expanded entries.
  14139. (if (setq u (assoc f fe))
  14140. (cdr u)
  14141. f))
  14142. list "\n")
  14143. "\n")))
  14144. (let ((org-mode-hook nil) (org-inhibit-startup t)
  14145. (org-insert-mode-line-in-empty-file nil))
  14146. (setq org-agenda-files list)
  14147. (customize-save-variable 'org-agenda-files org-agenda-files))))
  14148. (defun org-read-agenda-file-list (&optional pair-with-expansion)
  14149. "Read the list of agenda files from a file.
  14150. If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  14151. filenames, used by `org-store-new-agenda-file-list' to write back
  14152. un-expanded file names."
  14153. (when (file-directory-p org-agenda-files)
  14154. (error "`org-agenda-files' cannot be a single directory"))
  14155. (when (stringp org-agenda-files)
  14156. (with-temp-buffer
  14157. (insert-file-contents org-agenda-files)
  14158. (mapcar
  14159. (lambda (f)
  14160. (let ((e (expand-file-name (substitute-in-file-name f)
  14161. org-directory)))
  14162. (if pair-with-expansion
  14163. (cons e f)
  14164. e)))
  14165. (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  14166. ;;;###autoload
  14167. (defun org-cycle-agenda-files ()
  14168. "Cycle through the files in `org-agenda-files'.
  14169. If the current buffer visits an agenda file, find the next one in the list.
  14170. If the current buffer does not, find the first agenda file."
  14171. (interactive)
  14172. (let* ((fs (or (org-agenda-files t)
  14173. (user-error "No agenda files")))
  14174. (files (copy-sequence fs))
  14175. (tcf (and buffer-file-name (file-truename buffer-file-name)))
  14176. file)
  14177. (when tcf
  14178. (while (and (setq file (pop files))
  14179. (not (equal (file-truename file) tcf)))))
  14180. (find-file (car (or files fs)))
  14181. (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  14182. (defun org-agenda-file-to-front (&optional to-end)
  14183. "Move/add the current file to the top of the agenda file list.
  14184. If the file is not present in the list, it is added to the front. If it is
  14185. present, it is moved there. With optional argument TO-END, add/move to the
  14186. end of the list."
  14187. (interactive "P")
  14188. (let ((org-agenda-skip-unavailable-files nil)
  14189. (file-alist (mapcar (lambda (x)
  14190. (cons (file-truename x) x))
  14191. (org-agenda-files t)))
  14192. (ctf (file-truename
  14193. (or buffer-file-name
  14194. (user-error "Please save the current buffer to a file"))))
  14195. x had)
  14196. (setq x (assoc ctf file-alist) had x)
  14197. (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  14198. (if to-end
  14199. (setq file-alist (append (delq x file-alist) (list x)))
  14200. (setq file-alist (cons x (delq x file-alist))))
  14201. (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  14202. (org-install-agenda-files-menu)
  14203. (message "File %s to %s of agenda file list"
  14204. (if had "moved" "added") (if to-end "end" "front"))))
  14205. (defun org-remove-file (&optional file)
  14206. "Remove current file from the list of files in variable `org-agenda-files'.
  14207. These are the files which are being checked for agenda entries.
  14208. Optional argument FILE means use this file instead of the current."
  14209. (interactive)
  14210. (let* ((org-agenda-skip-unavailable-files nil)
  14211. (file (or file buffer-file-name
  14212. (user-error "Current buffer does not visit a file")))
  14213. (true-file (file-truename file))
  14214. (afile (abbreviate-file-name file))
  14215. (files (delq nil (mapcar
  14216. (lambda (x)
  14217. (unless (equal true-file
  14218. (file-truename x))
  14219. x))
  14220. (org-agenda-files t)))))
  14221. (if (not (= (length files) (length (org-agenda-files t))))
  14222. (progn
  14223. (org-store-new-agenda-file-list files)
  14224. (org-install-agenda-files-menu)
  14225. (message "Removed from Org Agenda list: %s" afile))
  14226. (message "File was not in list: %s (not removed)" afile))))
  14227. (defun org-file-menu-entry (file)
  14228. (vector file (list 'find-file file) t))
  14229. (defun org-check-agenda-file (file)
  14230. "Make sure FILE exists. If not, ask user what to do."
  14231. (unless (file-exists-p file)
  14232. (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
  14233. (abbreviate-file-name file))
  14234. (let ((r (downcase (read-char-exclusive))))
  14235. (cond
  14236. ((equal r ?r)
  14237. (org-remove-file file)
  14238. (throw 'nextfile t))
  14239. (t (user-error "Abort"))))))
  14240. (defun org-get-agenda-file-buffer (file)
  14241. "Get an agenda buffer visiting FILE.
  14242. If the buffer needs to be created, add it to the list of buffers
  14243. which might be released later."
  14244. (let ((buf (org-find-base-buffer-visiting file)))
  14245. (if buf
  14246. buf ; just return it
  14247. ;; Make a new buffer and remember it
  14248. (setq buf (find-file-noselect file))
  14249. (when buf (push buf org-agenda-new-buffers))
  14250. buf)))
  14251. (defun org-release-buffers (blist)
  14252. "Release all buffers in list, asking the user for confirmation when needed.
  14253. When a buffer is unmodified, it is just killed. When modified, it is saved
  14254. \(if the user agrees) and then killed."
  14255. (let (file)
  14256. (dolist (buf blist)
  14257. (setq file (buffer-file-name buf))
  14258. (when (and (buffer-modified-p buf)
  14259. file
  14260. (y-or-n-p (format "Save file %s? " file)))
  14261. (with-current-buffer buf (save-buffer)))
  14262. (kill-buffer buf))))
  14263. (defun org-agenda-prepare-buffers (files)
  14264. "Create buffers for all agenda files, protect archived trees and comments."
  14265. (interactive)
  14266. (let ((pa '(:org-archived t))
  14267. (pc '(:org-comment t))
  14268. (pall '(:org-archived t :org-comment t))
  14269. (inhibit-read-only t)
  14270. (org-inhibit-startup org-agenda-inhibit-startup)
  14271. (rea (org-make-tag-string (list org-archive-tag)))
  14272. re pos)
  14273. (setq org-tag-alist-for-agenda nil
  14274. org-tag-groups-alist-for-agenda nil)
  14275. (save-excursion
  14276. (save-restriction
  14277. (dolist (file files)
  14278. (catch 'nextfile
  14279. (if (bufferp file)
  14280. (set-buffer file)
  14281. (org-check-agenda-file file)
  14282. (set-buffer (org-get-agenda-file-buffer file)))
  14283. (widen)
  14284. (org-set-regexps-and-options 'tags-only)
  14285. (setq pos (point))
  14286. (or (memq 'category org-agenda-ignore-properties)
  14287. (org-refresh-category-properties))
  14288. (or (memq 'stats org-agenda-ignore-properties)
  14289. (org-refresh-stats-properties))
  14290. (or (memq 'effort org-agenda-ignore-properties)
  14291. (org-refresh-effort-properties))
  14292. (or (memq 'appt org-agenda-ignore-properties)
  14293. (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  14294. (setq org-todo-keywords-for-agenda
  14295. (append org-todo-keywords-for-agenda org-todo-keywords-1))
  14296. (setq org-done-keywords-for-agenda
  14297. (append org-done-keywords-for-agenda org-done-keywords))
  14298. (setq org-todo-keyword-alist-for-agenda
  14299. (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
  14300. (setq org-tag-alist-for-agenda
  14301. (org--tag-add-to-alist
  14302. org-tag-alist-for-agenda
  14303. org-current-tag-alist))
  14304. ;; Merge current file's tag groups into global
  14305. ;; `org-tag-groups-alist-for-agenda'.
  14306. (when org-group-tags
  14307. (dolist (alist org-tag-groups-alist)
  14308. (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  14309. (if old
  14310. (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  14311. (push alist org-tag-groups-alist-for-agenda)))))
  14312. (with-silent-modifications
  14313. (save-excursion
  14314. (remove-text-properties (point-min) (point-max) pall)
  14315. (when org-agenda-skip-archived-trees
  14316. (goto-char (point-min))
  14317. (while (re-search-forward rea nil t)
  14318. (when (org-at-heading-p t)
  14319. (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
  14320. (goto-char (point-min))
  14321. (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
  14322. (while (re-search-forward re nil t)
  14323. (when (save-match-data (org-in-commented-heading-p t))
  14324. (add-text-properties
  14325. (match-beginning 0) (org-end-of-subtree t) pc)))))
  14326. (goto-char pos)))))
  14327. (setq org-todo-keywords-for-agenda
  14328. (org-uniquify org-todo-keywords-for-agenda))
  14329. (setq org-todo-keyword-alist-for-agenda
  14330. (org-uniquify org-todo-keyword-alist-for-agenda))))
  14331. ;;;; CDLaTeX minor mode
  14332. (defvar org-cdlatex-mode-map (make-sparse-keymap)
  14333. "Keymap for the minor `org-cdlatex-mode'.")
  14334. (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  14335. (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  14336. (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  14337. (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  14338. (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  14339. (defvar org-cdlatex-texmathp-advice-is-done nil
  14340. "Flag remembering if we have applied the advice to texmathp already.")
  14341. (define-minor-mode org-cdlatex-mode
  14342. "Toggle the minor `org-cdlatex-mode'.
  14343. This mode supports entering LaTeX environment and math in LaTeX fragments
  14344. in Org mode.
  14345. \\{org-cdlatex-mode-map}"
  14346. :lighter " OCDL"
  14347. (when org-cdlatex-mode
  14348. (require 'cdlatex)
  14349. (run-hooks 'cdlatex-mode-hook)
  14350. (cdlatex-compute-tables))
  14351. (unless org-cdlatex-texmathp-advice-is-done
  14352. (setq org-cdlatex-texmathp-advice-is-done t)
  14353. (defadvice texmathp (around org-math-always-on activate)
  14354. "Always return t in Org buffers.
  14355. This is because we want to insert math symbols without dollars even outside
  14356. the LaTeX math segments. If Org mode thinks that point is actually inside
  14357. an embedded LaTeX fragment, let `texmathp' do its job.
  14358. `\\[org-cdlatex-mode-map]'"
  14359. (interactive)
  14360. (let (p)
  14361. (cond
  14362. ((not (derived-mode-p 'org-mode)) ad-do-it)
  14363. ((eq this-command 'cdlatex-math-symbol)
  14364. (setq ad-return-value t
  14365. texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
  14366. (t
  14367. (let ((p (org-inside-LaTeX-fragment-p)))
  14368. (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
  14369. (setq ad-return-value t
  14370. texmathp-why '("Org mode embedded math" . 0))
  14371. (when p ad-do-it)))))))))
  14372. (defun turn-on-org-cdlatex ()
  14373. "Unconditionally turn on `org-cdlatex-mode'."
  14374. (org-cdlatex-mode 1))
  14375. (defun org-try-cdlatex-tab ()
  14376. "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  14377. It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  14378. - inside a LaTeX fragment, or
  14379. - after the first word in a line, where an abbreviation expansion could
  14380. insert a LaTeX environment."
  14381. (when org-cdlatex-mode
  14382. (cond
  14383. ;; Before any word on the line: No expansion possible.
  14384. ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  14385. ;; Just after first word on the line: Expand it. Make sure it
  14386. ;; cannot happen on headlines, though.
  14387. ((save-excursion
  14388. (skip-chars-backward "a-zA-Z0-9*")
  14389. (skip-chars-backward " \t")
  14390. (and (bolp) (not (org-at-heading-p))))
  14391. (cdlatex-tab) t)
  14392. ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  14393. (defun org-cdlatex-underscore-caret (&optional _arg)
  14394. "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  14395. Revert to the normal definition outside of these fragments."
  14396. (interactive "P")
  14397. (if (org-inside-LaTeX-fragment-p)
  14398. (call-interactively 'cdlatex-sub-superscript)
  14399. (let (org-cdlatex-mode)
  14400. (call-interactively (key-binding (vector last-input-event))))))
  14401. (defun org-cdlatex-math-modify (&optional _arg)
  14402. "Execute `cdlatex-math-modify' in LaTeX fragments.
  14403. Revert to the normal definition outside of these fragments."
  14404. (interactive "P")
  14405. (if (org-inside-LaTeX-fragment-p)
  14406. (call-interactively 'cdlatex-math-modify)
  14407. (let (org-cdlatex-mode)
  14408. (call-interactively (key-binding (vector last-input-event))))))
  14409. (defun org-cdlatex-environment-indent (&optional environment item)
  14410. "Execute `cdlatex-environment' and indent the inserted environment.
  14411. ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  14412. The inserted environment is indented to current indentation
  14413. unless point is at the beginning of the line, in which the
  14414. environment remains unintended."
  14415. (interactive)
  14416. ;; cdlatex-environment always return nil. Therefore, capture output
  14417. ;; first and determine if an environment was selected.
  14418. (let* ((beg (point-marker))
  14419. (end (copy-marker (point) t))
  14420. (inserted (progn
  14421. (ignore-errors (cdlatex-environment environment item))
  14422. (< beg end)))
  14423. ;; Figure out how many lines to move forward after the
  14424. ;; environment has been inserted.
  14425. (lines (when inserted
  14426. (save-excursion
  14427. (- (cl-loop while (< beg (point))
  14428. with x = 0
  14429. do (forward-line -1)
  14430. (cl-incf x)
  14431. finally return x)
  14432. (if (progn (goto-char beg)
  14433. (and (progn (skip-chars-forward " \t") (eolp))
  14434. (progn (skip-chars-backward " \t") (bolp))))
  14435. 1 0)))))
  14436. (env (org-trim (delete-and-extract-region beg end))))
  14437. (when inserted
  14438. ;; Get indentation of next line unless at column 0.
  14439. (let ((ind (if (bolp) 0
  14440. (save-excursion
  14441. (org-return t)
  14442. (prog1 (current-indentation)
  14443. (when (progn (skip-chars-forward " \t") (eolp))
  14444. (delete-region beg (point)))))))
  14445. (bol (progn (skip-chars-backward " \t") (bolp))))
  14446. ;; Insert a newline before environment unless at column zero
  14447. ;; to "escape" the current line. Insert a newline if
  14448. ;; something is one the same line as \end{ENVIRONMENT}.
  14449. (insert
  14450. (concat (unless bol "\n") env
  14451. (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  14452. (unless (zerop ind)
  14453. (save-excursion
  14454. (goto-char beg)
  14455. (while (< (point) end)
  14456. (unless (eolp) (indent-line-to ind))
  14457. (forward-line))))
  14458. (goto-char beg)
  14459. (forward-line lines)
  14460. (indent-line-to ind)))
  14461. (set-marker beg nil)
  14462. (set-marker end nil)))
  14463. ;;;; LaTeX fragments
  14464. (defun org-inside-LaTeX-fragment-p ()
  14465. "Test if point is inside a LaTeX fragment.
  14466. I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  14467. sequence appearing also before point.
  14468. Even though the matchers for math are configurable, this function assumes
  14469. that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
  14470. delimiters are skipped when they have been removed by customization.
  14471. The return value is nil, or a cons cell with the delimiter and the
  14472. position of this delimiter.
  14473. This function does a reasonably good job, but can locally be fooled by
  14474. for example currency specifications. For example it will assume being in
  14475. inline math after \"$22.34\". The LaTeX fragment formatter will only format
  14476. fragments that are properly closed, but during editing, we have to live
  14477. with the uncertainty caused by missing closing delimiters. This function
  14478. looks only before point, not after."
  14479. (catch 'exit
  14480. (let ((pos (point))
  14481. (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  14482. (lim (progn
  14483. (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  14484. 'move)
  14485. (point)))
  14486. dd-on str (start 0) m re)
  14487. (goto-char pos)
  14488. (when dodollar
  14489. (setq str (concat (buffer-substring lim (point)) "\000 X$.")
  14490. re (nth 1 (assoc "$" org-latex-regexps)))
  14491. (while (string-match re str start)
  14492. (cond
  14493. ((= (match-end 0) (length str))
  14494. (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  14495. ((= (match-end 0) (- (length str) 5))
  14496. (throw 'exit nil))
  14497. (t (setq start (match-end 0))))))
  14498. (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  14499. (goto-char pos)
  14500. (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  14501. (and (match-beginning 2) (throw 'exit nil))
  14502. ;; count $$
  14503. (while (re-search-backward "\\$\\$" lim t)
  14504. (setq dd-on (not dd-on)))
  14505. (goto-char pos)
  14506. (when dd-on (cons "$$" m))))))
  14507. (defun org-inside-latex-macro-p ()
  14508. "Is point inside a LaTeX macro or its arguments?"
  14509. (save-match-data
  14510. (org-in-regexp
  14511. "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  14512. (defun org--make-preview-overlay (beg end image &optional imagetype)
  14513. "Build an overlay between BEG and END using IMAGE file.
  14514. Argument IMAGETYPE is the extension of the displayed image,
  14515. as a string. It defaults to \"png\"."
  14516. (let ((ov (make-overlay beg end))
  14517. (imagetype (or (intern imagetype) 'png)))
  14518. (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  14519. (overlay-put ov 'evaporate t)
  14520. (overlay-put ov
  14521. 'modification-hooks
  14522. (list (lambda (o _flag _beg _end &optional _l)
  14523. (delete-overlay o))))
  14524. (overlay-put ov
  14525. 'display
  14526. (list 'image :type imagetype :file image :ascent 'center))))
  14527. (defun org-clear-latex-preview (&optional beg end)
  14528. "Remove all overlays with LaTeX fragment images in current buffer.
  14529. When optional arguments BEG and END are non-nil, remove all
  14530. overlays between them instead. Return a non-nil value when some
  14531. overlays were removed, nil otherwise."
  14532. (let ((overlays
  14533. (cl-remove-if-not
  14534. (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  14535. (overlays-in (or beg (point-min)) (or end (point-max))))))
  14536. (mapc #'delete-overlay overlays)
  14537. overlays))
  14538. (defun org--latex-preview-region (beg end)
  14539. "Preview LaTeX fragments between BEG and END.
  14540. BEG and END are buffer positions."
  14541. (let ((file (buffer-file-name (buffer-base-buffer))))
  14542. (save-excursion
  14543. (org-format-latex
  14544. (concat org-preview-latex-image-directory "org-ltximg")
  14545. beg end
  14546. ;; Emacs cannot overlay images from remote hosts. Create it in
  14547. ;; `temporary-file-directory' instead.
  14548. (if (or (not file) (file-remote-p file))
  14549. temporary-file-directory
  14550. default-directory)
  14551. 'overlays nil 'forbuffer org-preview-latex-default-process))))
  14552. (defun org-latex-preview (&optional arg)
  14553. "Toggle preview of the LaTeX fragment at point.
  14554. If the cursor is on a LaTeX fragment, create the image and
  14555. overlay it over the source code, if there is none. Remove it
  14556. otherwise. If there is no fragment at point, display images for
  14557. all fragments in the current section.
  14558. With a `\\[universal-argument]' prefix argument ARG, clear images \
  14559. for all fragments
  14560. in the current section.
  14561. With a `\\[universal-argument] \\[universal-argument]' prefix \
  14562. argument ARG, display image for all
  14563. fragments in the buffer.
  14564. With a `\\[universal-argument] \\[universal-argument] \
  14565. \\[universal-argument]' prefix argument ARG, clear image for all
  14566. fragments in the buffer."
  14567. (interactive "P")
  14568. (cond
  14569. ((not (display-graphic-p)) nil)
  14570. ;; Clear whole buffer.
  14571. ((equal arg '(64))
  14572. (org-clear-latex-preview (point-min) (point-max))
  14573. (message "LaTeX previews removed from buffer"))
  14574. ;; Preview whole buffer.
  14575. ((equal arg '(16))
  14576. (message "Creating LaTeX previews in buffer...")
  14577. (org--latex-preview-region (point-min) (point-max))
  14578. (message "Creating LaTeX previews in buffer... done."))
  14579. ;; Clear current section.
  14580. ((equal arg '(4))
  14581. (org-clear-latex-preview
  14582. (if (org-before-first-heading-p) (point-min)
  14583. (save-excursion
  14584. (org-with-limited-levels (org-back-to-heading t) (point))))
  14585. (org-with-limited-levels (org-entry-end-position))))
  14586. ;; Toggle preview on LaTeX code at point.
  14587. ((let ((datum (org-element-context)))
  14588. (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  14589. (let ((beg (org-element-property :begin datum))
  14590. (end (org-element-property :end datum)))
  14591. (if (org-clear-latex-preview beg end)
  14592. (message "LaTeX preview removed")
  14593. (message "Creating LaTeX preview...")
  14594. (org--latex-preview-region beg end)
  14595. (message "Creating LaTeX preview... done."))
  14596. t))))
  14597. ;; Preview current section.
  14598. (t
  14599. (let ((beg (if (org-before-first-heading-p) (point-min)
  14600. (save-excursion
  14601. (org-with-limited-levels (org-back-to-heading t) (point)))))
  14602. (end (org-with-limited-levels (org-entry-end-position))))
  14603. (message "Creating LaTeX previews in section...")
  14604. (org--latex-preview-region beg end)
  14605. (message "Creating LaTeX previews in section... done.")))))
  14606. (defun org-format-latex
  14607. (prefix &optional beg end dir overlays msg forbuffer processing-type)
  14608. "Replace LaTeX fragments with links to an image.
  14609. The function takes care of creating the replacement image.
  14610. Only consider fragments between BEG and END when those are
  14611. provided.
  14612. When optional argument OVERLAYS is non-nil, display the image on
  14613. top of the fragment instead of replacing it.
  14614. PROCESSING-TYPE is the conversion method to use, as a symbol.
  14615. Some of the options can be changed using the variable
  14616. `org-format-latex-options', which see."
  14617. (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  14618. (unless (eq processing-type 'verbatim)
  14619. (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  14620. (cnt 0)
  14621. checkdir-flag)
  14622. (goto-char (or beg (point-min)))
  14623. ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  14624. (when (and overlays (memq processing-type '(dvipng imagemagick)))
  14625. (overlay-recenter (or end (point-max))))
  14626. (while (re-search-forward math-regexp end t)
  14627. (unless (and overlays
  14628. (eq (get-char-property (point) 'org-overlay-type)
  14629. 'org-latex-overlay))
  14630. (let* ((context (org-element-context))
  14631. (type (org-element-type context)))
  14632. (when (memq type '(latex-environment latex-fragment))
  14633. (let ((block-type (eq type 'latex-environment))
  14634. (value (org-element-property :value context))
  14635. (beg (org-element-property :begin context))
  14636. (end (save-excursion
  14637. (goto-char (org-element-property :end context))
  14638. (skip-chars-backward " \r\t\n")
  14639. (point))))
  14640. (cond
  14641. ((eq processing-type 'mathjax)
  14642. ;; Prepare for MathJax processing.
  14643. (if (not (string-match "\\`\\$\\$?" value))
  14644. (goto-char end)
  14645. (delete-region beg end)
  14646. (if (string= (match-string 0 value) "$$")
  14647. (insert "\\[" (substring value 2 -2) "\\]")
  14648. (insert "\\(" (substring value 1 -1) "\\)"))))
  14649. ((eq processing-type 'html)
  14650. (goto-char beg)
  14651. (delete-region beg end)
  14652. (insert (org-format-latex-as-html value)))
  14653. ((assq processing-type org-preview-latex-process-alist)
  14654. ;; Process to an image.
  14655. (cl-incf cnt)
  14656. (goto-char beg)
  14657. (let* ((processing-info
  14658. (cdr (assq processing-type org-preview-latex-process-alist)))
  14659. (face (face-at-point))
  14660. ;; Get the colors from the face at point.
  14661. (fg
  14662. (let ((color (plist-get org-format-latex-options
  14663. :foreground)))
  14664. (if forbuffer
  14665. (cond
  14666. ((eq color 'auto)
  14667. (face-attribute face :foreground nil 'default))
  14668. ((eq color 'default)
  14669. (face-attribute 'default :foreground nil))
  14670. (t color))
  14671. color)))
  14672. (bg
  14673. (let ((color (plist-get org-format-latex-options
  14674. :background)))
  14675. (if forbuffer
  14676. (cond
  14677. ((eq color 'auto)
  14678. (face-attribute face :background nil 'default))
  14679. ((eq color 'default)
  14680. (face-attribute 'default :background nil))
  14681. (t color))
  14682. color)))
  14683. (hash (sha1 (prin1-to-string
  14684. (list org-format-latex-header
  14685. org-latex-default-packages-alist
  14686. org-latex-packages-alist
  14687. org-format-latex-options
  14688. forbuffer value fg bg))))
  14689. (imagetype (or (plist-get processing-info :image-output-type) "png"))
  14690. (absprefix (expand-file-name prefix dir))
  14691. (linkfile (format "%s_%s.%s" prefix hash imagetype))
  14692. (movefile (format "%s_%s.%s" absprefix hash imagetype))
  14693. (sep (and block-type "\n\n"))
  14694. (link (concat sep "[[file:" linkfile "]]" sep))
  14695. (options
  14696. (org-combine-plists
  14697. org-format-latex-options
  14698. `(:foreground ,fg :background ,bg))))
  14699. (when msg (message msg cnt))
  14700. (unless checkdir-flag ; Ensure the directory exists.
  14701. (setq checkdir-flag t)
  14702. (let ((todir (file-name-directory absprefix)))
  14703. (unless (file-directory-p todir)
  14704. (make-directory todir t))))
  14705. (unless (file-exists-p movefile)
  14706. (org-create-formula-image
  14707. value movefile options forbuffer processing-type))
  14708. (if overlays
  14709. (progn
  14710. (dolist (o (overlays-in beg end))
  14711. (when (eq (overlay-get o 'org-overlay-type)
  14712. 'org-latex-overlay)
  14713. (delete-overlay o)))
  14714. (org--make-preview-overlay beg end movefile imagetype)
  14715. (goto-char end))
  14716. (delete-region beg end)
  14717. (insert
  14718. (org-add-props link
  14719. (list 'org-latex-src
  14720. (replace-regexp-in-string "\"" "" value)
  14721. 'org-latex-src-embed-type
  14722. (if block-type 'paragraph 'character)))))))
  14723. ((eq processing-type 'mathml)
  14724. ;; Process to MathML.
  14725. (unless (org-format-latex-mathml-available-p)
  14726. (user-error "LaTeX to MathML converter not configured"))
  14727. (cl-incf cnt)
  14728. (when msg (message msg cnt))
  14729. (goto-char beg)
  14730. (delete-region beg end)
  14731. (insert (org-format-latex-as-mathml
  14732. value block-type prefix dir)))
  14733. (t
  14734. (error "Unknown conversion process %s for LaTeX fragments"
  14735. processing-type)))))))))))
  14736. (defun org-create-math-formula (latex-frag &optional mathml-file)
  14737. "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  14738. Use `org-latex-to-mathml-convert-command'. If the conversion is
  14739. successful, return the portion between \"<math...> </math>\"
  14740. elements otherwise return nil. When MATHML-FILE is specified,
  14741. write the results in to that file. When invoked as an
  14742. interactive command, prompt for LATEX-FRAG, with initial value
  14743. set to the current active region and echo the results for user
  14744. inspection."
  14745. (interactive (list (let ((frag (when (org-region-active-p)
  14746. (buffer-substring-no-properties
  14747. (region-beginning) (region-end)))))
  14748. (read-string "LaTeX Fragment: " frag nil frag))))
  14749. (unless latex-frag (user-error "Invalid LaTeX fragment"))
  14750. (let* ((tmp-in-file
  14751. (let ((file (file-relative-name
  14752. (make-temp-name (expand-file-name "ltxmathml-in")))))
  14753. (write-region latex-frag nil file)
  14754. file))
  14755. (tmp-out-file (file-relative-name
  14756. (make-temp-name (expand-file-name "ltxmathml-out"))))
  14757. (cmd (format-spec
  14758. org-latex-to-mathml-convert-command
  14759. `((?j . ,(and org-latex-to-mathml-jar-file
  14760. (shell-quote-argument
  14761. (expand-file-name
  14762. org-latex-to-mathml-jar-file))))
  14763. (?I . ,(shell-quote-argument tmp-in-file))
  14764. (?i . ,latex-frag)
  14765. (?o . ,(shell-quote-argument tmp-out-file)))))
  14766. mathml shell-command-output)
  14767. (when (called-interactively-p 'any)
  14768. (unless (org-format-latex-mathml-available-p)
  14769. (user-error "LaTeX to MathML converter not configured")))
  14770. (message "Running %s" cmd)
  14771. (setq shell-command-output (shell-command-to-string cmd))
  14772. (setq mathml
  14773. (when (file-readable-p tmp-out-file)
  14774. (with-current-buffer (find-file-noselect tmp-out-file t)
  14775. (goto-char (point-min))
  14776. (when (re-search-forward
  14777. (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  14778. (regexp-quote
  14779. "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  14780. nil t)
  14781. (prog1 (match-string 0) (kill-buffer))))))
  14782. (cond
  14783. (mathml
  14784. (setq mathml
  14785. (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  14786. (when mathml-file
  14787. (write-region mathml nil mathml-file))
  14788. (when (called-interactively-p 'any)
  14789. (message mathml)))
  14790. ((warn "LaTeX to MathML conversion failed")
  14791. (message shell-command-output)))
  14792. (delete-file tmp-in-file)
  14793. (when (file-exists-p tmp-out-file)
  14794. (delete-file tmp-out-file))
  14795. mathml))
  14796. (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  14797. prefix &optional dir)
  14798. "Use `org-create-math-formula' but check local cache first."
  14799. (let* ((absprefix (expand-file-name prefix dir))
  14800. (print-length nil) (print-level nil)
  14801. (formula-id (concat
  14802. "formula-"
  14803. (sha1
  14804. (prin1-to-string
  14805. (list latex-frag
  14806. org-latex-to-mathml-convert-command)))))
  14807. (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  14808. (formula-cache-dir (file-name-directory formula-cache)))
  14809. (unless (file-directory-p formula-cache-dir)
  14810. (make-directory formula-cache-dir t))
  14811. (unless (file-exists-p formula-cache)
  14812. (org-create-math-formula latex-frag formula-cache))
  14813. (if (file-exists-p formula-cache)
  14814. ;; Successful conversion. Return the link to MathML file.
  14815. (org-add-props
  14816. (format "[[file:%s]]" (file-relative-name formula-cache dir))
  14817. (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  14818. 'org-latex-src-embed-type (if latex-frag-type
  14819. 'paragraph 'character)))
  14820. ;; Failed conversion. Return the LaTeX fragment verbatim
  14821. latex-frag)))
  14822. (defun org-format-latex-as-html (latex-fragment)
  14823. "Convert LATEX-FRAGMENT to HTML.
  14824. This uses `org-latex-to-html-convert-command', which see."
  14825. (let ((cmd (format-spec org-latex-to-html-convert-command
  14826. `((?i . ,latex-fragment)))))
  14827. (message "Running %s" cmd)
  14828. (shell-command-to-string cmd)))
  14829. (defun org--get-display-dpi ()
  14830. "Get the DPI of the display.
  14831. The function assumes that the display has the same pixel width in
  14832. the horizontal and vertical directions."
  14833. (if (display-graphic-p)
  14834. (round (/ (display-pixel-height)
  14835. (/ (display-mm-height) 25.4)))
  14836. (error "Attempt to calculate the dpi of a non-graphic display")))
  14837. (defun org-create-formula-image
  14838. (string tofile options buffer &optional processing-type)
  14839. "Create an image from LaTeX source using external processes.
  14840. The LaTeX STRING is saved to a temporary LaTeX file, then
  14841. converted to an image file by process PROCESSING-TYPE defined in
  14842. `org-preview-latex-process-alist'. A nil value defaults to
  14843. `org-preview-latex-default-process'.
  14844. The generated image file is eventually moved to TOFILE.
  14845. The OPTIONS argument controls the size, foreground color and
  14846. background color of the generated image.
  14847. When BUFFER non-nil, this function is used for LaTeX previewing.
  14848. Otherwise, it is used to deal with LaTeX snippets showed in
  14849. a HTML file."
  14850. (let* ((processing-type (or processing-type
  14851. org-preview-latex-default-process))
  14852. (processing-info
  14853. (cdr (assq processing-type org-preview-latex-process-alist)))
  14854. (programs (plist-get processing-info :programs))
  14855. (error-message (or (plist-get processing-info :message) ""))
  14856. (image-input-type (plist-get processing-info :image-input-type))
  14857. (image-output-type (plist-get processing-info :image-output-type))
  14858. (post-clean (or (plist-get processing-info :post-clean)
  14859. '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  14860. ".svg" ".png" ".jpg" ".jpeg" ".out")))
  14861. (latex-header
  14862. (or (plist-get processing-info :latex-header)
  14863. (org-latex-make-preamble
  14864. (org-export-get-environment (org-export-get-backend 'latex))
  14865. org-format-latex-header
  14866. 'snippet)))
  14867. (latex-compiler (plist-get processing-info :latex-compiler))
  14868. (tmpdir temporary-file-directory)
  14869. (texfilebase (make-temp-name
  14870. (expand-file-name "orgtex" tmpdir)))
  14871. (texfile (concat texfilebase ".tex"))
  14872. (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  14873. '(1.0 . 1.0)))
  14874. (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  14875. (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  14876. (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
  14877. (fg (or (plist-get options (if buffer :foreground :html-foreground))
  14878. "Black"))
  14879. (bg (or (plist-get options (if buffer :background :html-background))
  14880. "Transparent"))
  14881. (image-converter
  14882. (or (and (string= bg "Transparent")
  14883. (plist-get processing-info :transparent-image-converter))
  14884. (plist-get processing-info :image-converter)))
  14885. (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  14886. (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  14887. (dolist (program programs)
  14888. (org-check-external-command program error-message))
  14889. (if (eq fg 'default)
  14890. (setq fg (org-latex-color :foreground))
  14891. (setq fg (org-latex-color-format fg)))
  14892. (setq bg (cond
  14893. ((eq bg 'default) (org-latex-color :background))
  14894. ((string= bg "Transparent") nil)
  14895. (t (org-latex-color-format bg))))
  14896. ;; Remove TeX \par at end of snippet to avoid trailing space.
  14897. (if (string-suffix-p string "\n")
  14898. (aset string (1- (length string)) ?%)
  14899. (setq string (concat string "%")))
  14900. (with-temp-file texfile
  14901. (insert latex-header)
  14902. (insert "\n\\begin{document}\n"
  14903. "\\definecolor{fg}{rgb}{" fg "}%\n"
  14904. (if bg
  14905. (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  14906. "\n\\pagecolor{bg}%\n")
  14907. "")
  14908. "\n{\\color{fg}\n"
  14909. string
  14910. "\n}\n"
  14911. "\n\\end{document}\n"))
  14912. (let* ((err-msg (format "Please adjust `%s' part of \
  14913. `org-preview-latex-process-alist'."
  14914. processing-type))
  14915. (image-input-file
  14916. (org-compile-file
  14917. texfile latex-compiler image-input-type err-msg log-buf))
  14918. (image-output-file
  14919. (org-compile-file
  14920. image-input-file image-converter image-output-type err-msg log-buf
  14921. `((?D . ,(shell-quote-argument (format "%s" dpi)))
  14922. (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  14923. (copy-file image-output-file tofile 'replace)
  14924. (dolist (e post-clean)
  14925. (when (file-exists-p (concat texfilebase e))
  14926. (delete-file (concat texfilebase e))))
  14927. image-output-file)))
  14928. (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  14929. "Fill a LaTeX header template TPL.
  14930. In the template, the following place holders will be recognized:
  14931. [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
  14932. [NO-DEFAULT-PACKAGES] do not include DEF-PKG
  14933. [PACKAGES] \\usepackage statements for PKG
  14934. [NO-PACKAGES] do not include PKG
  14935. [EXTRA] the string EXTRA
  14936. [NO-EXTRA] do not include EXTRA
  14937. For backward compatibility, if both the positive and the negative place
  14938. holder is missing, the positive one (without the \"NO-\") will be
  14939. assumed to be present at the end of the template.
  14940. DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  14941. EXTRA is a string.
  14942. SNIPPETS-P indicates if this is run to create snippet images for HTML."
  14943. (let (rpl (end ""))
  14944. (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  14945. (setq rpl (if (or (match-end 1) (not def-pkg))
  14946. "" (org-latex-packages-to-string def-pkg snippets-p t))
  14947. tpl (replace-match rpl t t tpl))
  14948. (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  14949. (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  14950. (setq rpl (if (or (match-end 1) (not pkg))
  14951. "" (org-latex-packages-to-string pkg snippets-p t))
  14952. tpl (replace-match rpl t t tpl))
  14953. (when pkg (setq end
  14954. (concat end "\n"
  14955. (org-latex-packages-to-string pkg snippets-p)))))
  14956. (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  14957. (setq rpl (if (or (match-end 1) (not extra))
  14958. "" (concat extra "\n"))
  14959. tpl (replace-match rpl t t tpl))
  14960. (when (and extra (string-match "\\S-" extra))
  14961. (setq end (concat end "\n" extra))))
  14962. (if (string-match "\\S-" end)
  14963. (concat tpl "\n" end)
  14964. tpl)))
  14965. (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  14966. "Turn an alist of packages into a string with the \\usepackage macros."
  14967. (setq pkg (mapconcat (lambda(p)
  14968. (cond
  14969. ((stringp p) p)
  14970. ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  14971. (format "%% Package %s omitted" (cadr p)))
  14972. ((equal "" (car p))
  14973. (format "\\usepackage{%s}" (cadr p)))
  14974. (t
  14975. (format "\\usepackage[%s]{%s}"
  14976. (car p) (cadr p)))))
  14977. pkg
  14978. "\n"))
  14979. (if newline (concat pkg "\n") pkg))
  14980. (defun org-dvipng-color (attr)
  14981. "Return a RGB color specification for dvipng."
  14982. (org-dvipng-color-format (face-attribute 'default attr nil)))
  14983. (defun org-dvipng-color-format (color-name)
  14984. "Convert COLOR-NAME to a RGB color value for dvipng."
  14985. (apply #'format "rgb %s %s %s"
  14986. (mapcar 'org-normalize-color
  14987. (color-values color-name))))
  14988. (defun org-latex-color (attr)
  14989. "Return a RGB color for the LaTeX color package."
  14990. (org-latex-color-format (face-attribute 'default attr nil)))
  14991. (defun org-latex-color-format (color-name)
  14992. "Convert COLOR-NAME to a RGB color value."
  14993. (apply #'format "%s,%s,%s"
  14994. (mapcar 'org-normalize-color
  14995. (color-values color-name))))
  14996. (defun org-normalize-color (value)
  14997. "Return string to be used as color value for an RGB component."
  14998. (format "%g" (/ value 65535.0)))
  14999. ;; Image display
  15000. (defvar-local org-inline-image-overlays nil)
  15001. (defun org-toggle-inline-images (&optional include-linked)
  15002. "Toggle the display of inline images.
  15003. INCLUDE-LINKED is passed to `org-display-inline-images'."
  15004. (interactive "P")
  15005. (if org-inline-image-overlays
  15006. (progn
  15007. (org-remove-inline-images)
  15008. (when (called-interactively-p 'interactive)
  15009. (message "Inline image display turned off")))
  15010. (org-display-inline-images include-linked)
  15011. (when (called-interactively-p 'interactive)
  15012. (message (if org-inline-image-overlays
  15013. (format "%d images displayed inline"
  15014. (length org-inline-image-overlays))
  15015. "No images to display inline")))))
  15016. (defun org-redisplay-inline-images ()
  15017. "Assure display of inline images and refresh them."
  15018. (interactive)
  15019. (org-toggle-inline-images)
  15020. (unless org-inline-image-overlays
  15021. (org-toggle-inline-images)))
  15022. ;; For without-x builds.
  15023. (declare-function image-refresh "image" (spec &optional frame))
  15024. (defcustom org-display-remote-inline-images 'skip
  15025. "How to display remote inline images.
  15026. Possible values of this option are:
  15027. skip Don't display remote images.
  15028. download Always download and display remote images.
  15029. cache Display remote images, and open them in separate buffers
  15030. for caching. Silently update the image buffer when a file
  15031. change is detected."
  15032. :group 'org-appearance
  15033. :package-version '(Org . "9.4")
  15034. :type '(choice
  15035. (const :tag "Ignore remote images" skip)
  15036. (const :tag "Always display remote images" download)
  15037. (const :tag "Display and silently update remote images" cache))
  15038. :safe #'symbolp)
  15039. (defun org--create-inline-image (file width)
  15040. "Create image located at FILE, or return nil.
  15041. WIDTH is the width of the image. The image may not be created
  15042. according to the value of `org-display-remote-inline-images'."
  15043. (let* ((remote? (file-remote-p file))
  15044. (file-or-data
  15045. (pcase org-display-remote-inline-images
  15046. ((guard (not remote?)) file)
  15047. (`download (with-temp-buffer
  15048. (set-buffer-multibyte nil)
  15049. (insert-file-contents-literally file)
  15050. (buffer-string)))
  15051. (`cache (let ((revert-without-query '(".")))
  15052. (with-current-buffer (find-file-noselect file)
  15053. (buffer-string))))
  15054. (`skip nil)
  15055. (other
  15056. (message "Invalid value of `org-display-remote-inline-images': %S"
  15057. other)
  15058. nil))))
  15059. (when file-or-data
  15060. (create-image file-or-data
  15061. (and (image-type-available-p 'imagemagick)
  15062. width
  15063. 'imagemagick)
  15064. remote?
  15065. :width width))))
  15066. (defun org-display-inline-images (&optional include-linked refresh beg end)
  15067. "Display inline images.
  15068. An inline image is a link which follows either of these
  15069. conventions:
  15070. 1. Its path is a file with an extension matching return value
  15071. from `image-file-name-regexp' and it has no contents.
  15072. 2. Its description consists in a single link of the previous
  15073. type. In this case, that link must be a well-formed plain
  15074. or angle link, i.e., it must have an explicit \"file\" type.
  15075. Equip each image with the key-map `image-map'.
  15076. When optional argument INCLUDE-LINKED is non-nil, also links with
  15077. a text description part will be inlined. This can be nice for
  15078. a quick look at those images, but it does not reflect what
  15079. exported files will look like.
  15080. When optional argument REFRESH is non-nil, refresh existing
  15081. images between BEG and END. This will create new image displays
  15082. only if necessary.
  15083. BEG and END define the considered part. They default to the
  15084. buffer boundaries with possible narrowing."
  15085. (interactive "P")
  15086. (when (display-graphic-p)
  15087. (unless refresh
  15088. (org-remove-inline-images)
  15089. (when (fboundp 'clear-image-cache) (clear-image-cache)))
  15090. (let ((end (or end (point-max))))
  15091. (org-with-point-at (or beg (point-min))
  15092. (let* ((case-fold-search t)
  15093. (file-extension-re (image-file-name-regexp))
  15094. (link-abbrevs (mapcar #'car
  15095. (append org-link-abbrev-alist-local
  15096. org-link-abbrev-alist)))
  15097. ;; Check absolute, relative file names and explicit
  15098. ;; "file:" links. Also check link abbreviations since
  15099. ;; some might expand to "file" links.
  15100. (file-types-re
  15101. (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  15102. (if (not link-abbrevs) ""
  15103. (concat "\\|" (regexp-opt link-abbrevs))))))
  15104. (while (re-search-forward file-types-re end t)
  15105. (let* ((link (org-element-lineage
  15106. (save-match-data (org-element-context))
  15107. '(link) t))
  15108. (linktype (org-element-property :type link))
  15109. (inner-start (match-beginning 1))
  15110. (path
  15111. (cond
  15112. ;; No link at point; no inline image.
  15113. ((not link) nil)
  15114. ;; File link without a description. Also handle
  15115. ;; INCLUDE-LINKED here since it should have
  15116. ;; precedence over the next case. I.e., if link
  15117. ;; contains filenames in both the path and the
  15118. ;; description, prioritize the path only when
  15119. ;; INCLUDE-LINKED is non-nil.
  15120. ((or (not (org-element-property :contents-begin link))
  15121. include-linked)
  15122. (and (or (equal "file" linktype)
  15123. (equal "attachment" linktype))
  15124. (org-element-property :path link)))
  15125. ;; Link with a description. Check if description
  15126. ;; is a filename. Even if Org doesn't have syntax
  15127. ;; for those -- clickable image -- constructs, fake
  15128. ;; them, as in `org-export-insert-image-links'.
  15129. ((not inner-start) nil)
  15130. (t
  15131. (org-with-point-at inner-start
  15132. (and (looking-at
  15133. (if (char-equal ?< (char-after inner-start))
  15134. org-link-angle-re
  15135. org-link-plain-re))
  15136. ;; File name must fill the whole
  15137. ;; description.
  15138. (= (org-element-property :contents-end link)
  15139. (match-end 0))
  15140. (match-string 2)))))))
  15141. (when (and path (string-match-p file-extension-re path))
  15142. (let ((file (if (equal "attachment" linktype)
  15143. (progn
  15144. (require 'org-attach)
  15145. (ignore-errors (org-attach-expand path)))
  15146. (expand-file-name path))))
  15147. (when (and file (file-exists-p file))
  15148. (let ((width (org-display-inline-image--width link))
  15149. (old (get-char-property-and-overlay
  15150. (org-element-property :begin link)
  15151. 'org-image-overlay)))
  15152. (if (and (car-safe old) refresh)
  15153. (image-refresh (overlay-get (cdr old) 'display))
  15154. (let ((image (org--create-inline-image file width)))
  15155. (when image
  15156. (let ((ov (make-overlay
  15157. (org-element-property :begin link)
  15158. (progn
  15159. (goto-char
  15160. (org-element-property :end link))
  15161. (skip-chars-backward " \t")
  15162. (point)))))
  15163. (overlay-put ov 'display image)
  15164. (overlay-put ov 'face 'default)
  15165. (overlay-put ov 'org-image-overlay t)
  15166. (overlay-put
  15167. ov 'modification-hooks
  15168. (list 'org-display-inline-remove-overlay))
  15169. (when (boundp 'image-map)
  15170. (overlay-put ov 'keymap image-map))
  15171. (push ov org-inline-image-overlays))))))))))))))))
  15172. (defvar visual-fill-column-width) ; Silence compiler warning
  15173. (defun org-display-inline-image--width (link)
  15174. "Determine the display width of the image LINK, in pixels.
  15175. - When `org-image-actual-width' is t, the image's pixel width is used.
  15176. - When `org-image-actual-width' is a number, that value will is used.
  15177. - When `org-image-actual-width' is nil or a list, the first :width attribute
  15178. set (if it exists) is used to set the image width. A width of X% is
  15179. divided by 100.
  15180. If no :width attribute is given and `org-image-actual-width' is a list with
  15181. a number as the car, then that number is used as the default value.
  15182. If the value is a float between 0 and 2, it interpreted as that proportion
  15183. of the text width in the buffer."
  15184. ;; Apply `org-image-actual-width' specifications.
  15185. (cond
  15186. ((eq org-image-actual-width t) nil)
  15187. ((listp org-image-actual-width)
  15188. (let* ((case-fold-search t)
  15189. (par (org-element-lineage link '(paragraph)))
  15190. (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  15191. (par-end (org-element-property :post-affiliated par))
  15192. ;; Try to find an attribute providing a :width.
  15193. (attr-width
  15194. (when (and par (org-with-point-at
  15195. (org-element-property :begin par)
  15196. (re-search-forward attr-re par-end t)))
  15197. (match-string 1)))
  15198. (attr-width-val
  15199. (cond
  15200. ((null attr-width) nil)
  15201. ((string-match-p "\\`[0-9.]+%" attr-width)
  15202. (/ (string-to-number attr-width) 100.0))
  15203. (t (string-to-number attr-width))))
  15204. ;; Fallback to `org-image-actual-width' if no explicit width is given.
  15205. (width (or attr-width-val (car org-image-actual-width))))
  15206. (if (and (floatp width) (<= 0.0 width 2.0))
  15207. ;; A float in [0,2] should be interpereted as this portion of
  15208. ;; the text width in the window. This works well with cases like
  15209. ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  15210. ;; as the "0.X" is pulled out as a float. We use 2 as the upper
  15211. ;; bound as cases such as 1.2\linewidth are feasible.
  15212. (round (* width
  15213. (window-pixel-width)
  15214. (/ (or (and (bound-and-true-p visual-fill-column-mode)
  15215. (or visual-fill-column-width auto-fill-function))
  15216. (when auto-fill-function fill-column)
  15217. (- (window-text-width) display-line-numbers-width))
  15218. (float (window-total-width)))))
  15219. width)))
  15220. ((numberp org-image-actual-width)
  15221. org-image-actual-width)
  15222. (t nil)))
  15223. (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  15224. "Remove inline-display overlay if a corresponding region is modified."
  15225. (let ((inhibit-modification-hooks t))
  15226. (when (and ov after)
  15227. (delete ov org-inline-image-overlays)
  15228. (delete-overlay ov))))
  15229. (defun org-remove-inline-images ()
  15230. "Remove inline display of images."
  15231. (interactive)
  15232. (mapc #'delete-overlay org-inline-image-overlays)
  15233. (setq org-inline-image-overlays nil))
  15234. (defvar org-self-insert-command-undo-counter 0)
  15235. (defvar org-speed-command nil)
  15236. (defun org-self-insert-command (N)
  15237. "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  15238. If the cursor is in a table looking at whitespace, the whitespace is
  15239. overwritten, and the table is not marked as requiring realignment."
  15240. (interactive "p")
  15241. (org-check-before-invisible-edit 'insert)
  15242. (cond
  15243. ((and org-use-speed-commands
  15244. (let ((kv (this-command-keys-vector)))
  15245. (setq org-speed-command
  15246. (run-hook-with-args-until-success
  15247. 'org-speed-command-hook
  15248. (make-string 1 (aref kv (1- (length kv))))))))
  15249. (cond
  15250. ((commandp org-speed-command)
  15251. (setq this-command org-speed-command)
  15252. (call-interactively org-speed-command))
  15253. ((functionp org-speed-command)
  15254. (funcall org-speed-command))
  15255. ((and org-speed-command (listp org-speed-command))
  15256. (eval org-speed-command))
  15257. (t (let (org-use-speed-commands)
  15258. (call-interactively 'org-self-insert-command)))))
  15259. ((and
  15260. (= N 1)
  15261. (not (org-region-active-p))
  15262. (org-at-table-p)
  15263. (progn
  15264. ;; Check if we blank the field, and if that triggers align.
  15265. (and (featurep 'org-table)
  15266. org-table-auto-blank-field
  15267. (memq last-command
  15268. '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  15269. (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
  15270. ;; Got extra space, this field does not determine
  15271. ;; column width.
  15272. (let (org-table-may-need-update) (org-table-blank-field))
  15273. ;; No extra space, this field may determine column
  15274. ;; width.
  15275. (org-table-blank-field)))
  15276. t)
  15277. (looking-at "[^|\n]* |"))
  15278. ;; There is room for insertion without re-aligning the table.
  15279. (self-insert-command N)
  15280. (org-table-with-shrunk-field
  15281. (save-excursion
  15282. (skip-chars-forward "^|")
  15283. ;; Do not delete last space, which is
  15284. ;; `org-table-separator-space', but the regular space before
  15285. ;; it.
  15286. (delete-region (- (point) 2) (1- (point))))))
  15287. (t
  15288. (setq org-table-may-need-update t)
  15289. (self-insert-command N)
  15290. (org-fix-tags-on-the-fly)
  15291. (when org-self-insert-cluster-for-undo
  15292. (if (not (eq last-command 'org-self-insert-command))
  15293. (setq org-self-insert-command-undo-counter 1)
  15294. (if (>= org-self-insert-command-undo-counter 20)
  15295. (setq org-self-insert-command-undo-counter 1)
  15296. (and (> org-self-insert-command-undo-counter 0)
  15297. buffer-undo-list (listp buffer-undo-list)
  15298. (not (cadr buffer-undo-list)) ; remove nil entry
  15299. (setcdr buffer-undo-list (cddr buffer-undo-list)))
  15300. (setq org-self-insert-command-undo-counter
  15301. (1+ org-self-insert-command-undo-counter))))))))
  15302. (defun org-check-before-invisible-edit (kind)
  15303. "Check if editing kind KIND would be dangerous with invisible text around.
  15304. The detailed reaction depends on the user option `org-catch-invisible-edits'."
  15305. ;; First, try to get out of here as quickly as possible, to reduce overhead
  15306. (when (and org-catch-invisible-edits
  15307. (or (not (boundp 'visible-mode)) (not visible-mode))
  15308. (or (get-char-property (point) 'invisible)
  15309. (get-char-property (max (point-min) (1- (point))) 'invisible)))
  15310. ;; OK, we need to take a closer look. Do not consider
  15311. ;; invisibility obtained through text properties (e.g., link
  15312. ;; fontification), as it cannot be toggled.
  15313. (let* ((invisible-at-point
  15314. (pcase (get-char-property-and-overlay (point) 'invisible)
  15315. (`(,_ . ,(and (pred overlayp) o)) o)))
  15316. ;; Assume that point cannot land in the middle of an
  15317. ;; overlay, or between two overlays.
  15318. (invisible-before-point
  15319. (and (not invisible-at-point)
  15320. (not (bobp))
  15321. (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  15322. (`(,_ . ,(and (pred overlayp) o)) o))))
  15323. (border-and-ok-direction
  15324. (or
  15325. ;; Check if we are acting predictably before invisible
  15326. ;; text.
  15327. (and invisible-at-point
  15328. (memq kind '(insert delete-backward)))
  15329. ;; Check if we are acting predictably after invisible text
  15330. ;; This works not well, and I have turned it off. It seems
  15331. ;; better to always show and stop after invisible text.
  15332. ;; (and (not invisible-at-point) invisible-before-point
  15333. ;; (memq kind '(insert delete)))
  15334. )))
  15335. (when (or invisible-at-point invisible-before-point)
  15336. (when (eq org-catch-invisible-edits 'error)
  15337. (user-error "Editing in invisible areas is prohibited, make them visible first"))
  15338. (if (and org-custom-properties-overlays
  15339. (y-or-n-p "Display invisible properties in this buffer? "))
  15340. (org-toggle-custom-properties-visibility)
  15341. ;; Make the area visible
  15342. (save-excursion
  15343. (when invisible-before-point
  15344. (goto-char
  15345. (previous-single-char-property-change (point) 'invisible)))
  15346. ;; Remove whatever overlay is currently making yet-to-be
  15347. ;; edited text invisible. Also remove nested invisibility
  15348. ;; related overlays.
  15349. (delete-overlay (or invisible-at-point invisible-before-point))
  15350. (let ((origin (if invisible-at-point (point) (1- (point)))))
  15351. (while (pcase (get-char-property-and-overlay origin 'invisible)
  15352. (`(,_ . ,(and (pred overlayp) o))
  15353. (delete-overlay o)
  15354. t)))))
  15355. (cond
  15356. ((eq org-catch-invisible-edits 'show)
  15357. ;; That's it, we do the edit after showing
  15358. (message
  15359. "Unfolding invisible region around point before editing")
  15360. (sit-for 1))
  15361. ((and (eq org-catch-invisible-edits 'smart)
  15362. border-and-ok-direction)
  15363. (message "Unfolding invisible region around point before editing"))
  15364. (t
  15365. ;; Don't do the edit, make the user repeat it in full visibility
  15366. (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
  15367. (defun org-fix-tags-on-the-fly ()
  15368. "Align tags in headline at point.
  15369. Unlike `org-align-tags', this function does nothing if point is
  15370. either not currently on a tagged headline or on a tag."
  15371. (when (and (org-match-line org-tag-line-re)
  15372. (< (point) (match-beginning 1)))
  15373. (org-align-tags)))
  15374. (defun org-delete-backward-char (N)
  15375. "Like `delete-backward-char', insert whitespace at field end in tables.
  15376. When deleting backwards, in tables this function will insert whitespace in
  15377. front of the next \"|\" separator, to keep the table aligned. The table will
  15378. still be marked for re-alignment if the field did fill the entire column,
  15379. because, in this case the deletion might narrow the column."
  15380. (interactive "p")
  15381. (save-match-data
  15382. (org-check-before-invisible-edit 'delete-backward)
  15383. (if (and (= N 1)
  15384. (not overwrite-mode)
  15385. (not (org-region-active-p))
  15386. (not (eq (char-before) ?|))
  15387. (save-excursion (skip-chars-backward " \t") (not (bolp)))
  15388. (looking-at-p ".*?|")
  15389. (org-at-table-p))
  15390. (progn (forward-char -1) (org-delete-char 1))
  15391. (backward-delete-char N)
  15392. (org-fix-tags-on-the-fly))))
  15393. (defun org-delete-char (N)
  15394. "Like `delete-char', but insert whitespace at field end in tables.
  15395. When deleting characters, in tables this function will insert whitespace in
  15396. front of the next \"|\" separator, to keep the table aligned. The table will
  15397. still be marked for re-alignment if the field did fill the entire column,
  15398. because, in this case the deletion might narrow the column."
  15399. (interactive "p")
  15400. (save-match-data
  15401. (org-check-before-invisible-edit 'delete)
  15402. (cond
  15403. ((or (/= N 1)
  15404. (eq (char-after) ?|)
  15405. (save-excursion (skip-chars-backward " \t") (bolp))
  15406. (not (org-at-table-p)))
  15407. (delete-char N)
  15408. (org-fix-tags-on-the-fly))
  15409. ((looking-at ".\\(.*?\\)|")
  15410. (let* ((update? org-table-may-need-update)
  15411. (noalign (looking-at-p ".*? |")))
  15412. (delete-char 1)
  15413. (org-table-with-shrunk-field
  15414. (save-excursion
  15415. ;; Last space is `org-table-separator-space', so insert
  15416. ;; a regular one before it instead.
  15417. (goto-char (- (match-end 0) 2))
  15418. (insert " ")))
  15419. ;; If there were two spaces at the end, this field does not
  15420. ;; determine the width of the column.
  15421. (when noalign (setq org-table-may-need-update update?))))
  15422. (t
  15423. (delete-char N)))))
  15424. ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  15425. (put 'org-self-insert-command 'delete-selection
  15426. (lambda ()
  15427. (not (run-hook-with-args-until-success
  15428. 'self-insert-uses-region-functions))))
  15429. (put 'orgtbl-self-insert-command 'delete-selection
  15430. (lambda ()
  15431. (not (run-hook-with-args-until-success
  15432. 'self-insert-uses-region-functions))))
  15433. (put 'org-delete-char 'delete-selection 'supersede)
  15434. (put 'org-delete-backward-char 'delete-selection 'supersede)
  15435. (put 'org-yank 'delete-selection 'yank)
  15436. (put 'org-return 'delete-selection t)
  15437. ;; Make `flyspell-mode' delay after some commands
  15438. (put 'org-self-insert-command 'flyspell-delayed t)
  15439. (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  15440. (put 'org-delete-char 'flyspell-delayed t)
  15441. (put 'org-delete-backward-char 'flyspell-delayed t)
  15442. ;; Make pabbrev-mode expand after Org mode commands
  15443. (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  15444. (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  15445. (defun org-transpose-words ()
  15446. "Transpose words for Org.
  15447. This uses the `org-mode-transpose-word-syntax-table' syntax
  15448. table, which interprets characters in `org-emphasis-alist' as
  15449. word constituents."
  15450. (interactive)
  15451. (with-syntax-table org-mode-transpose-word-syntax-table
  15452. (call-interactively 'transpose-words)))
  15453. (defvar org-ctrl-c-ctrl-c-hook nil
  15454. "Hook for functions attaching themselves to `C-c C-c'.
  15455. This can be used to add additional functionality to the `C-c C-c'
  15456. key which executes context-dependent commands. This hook is run
  15457. before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  15458. run after the last test.
  15459. Each function will be called with no arguments. The function
  15460. must check if the context is appropriate for it to act. If yes,
  15461. it should do its thing and then return a non-nil value. If the
  15462. context is wrong, just do nothing and return nil.")
  15463. (defvar org-ctrl-c-ctrl-c-final-hook nil
  15464. "Hook for functions attaching themselves to `C-c C-c'.
  15465. This can be used to add additional functionality to the `C-c C-c'
  15466. key which executes context-dependent commands. This hook is run
  15467. after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  15468. before the first test.
  15469. Each function will be called with no arguments. The function
  15470. must check if the context is appropriate for it to act. If yes,
  15471. it should do its thing and then return a non-nil value. If the
  15472. context is wrong, just do nothing and return nil.")
  15473. (defvar org-tab-first-hook nil
  15474. "Hook for functions to attach themselves to TAB.
  15475. See `org-ctrl-c-ctrl-c-hook' for more information.
  15476. This hook runs as the first action when TAB is pressed, even before
  15477. `org-cycle' messes around with the `outline-regexp' to cater for
  15478. inline tasks and plain list item folding.
  15479. If any function in this hook returns t, any other actions that
  15480. would have been caused by TAB (such as table field motion or visibility
  15481. cycling) will not occur.")
  15482. (defvar org-tab-after-check-for-table-hook nil
  15483. "Hook for functions to attach themselves to TAB.
  15484. See `org-ctrl-c-ctrl-c-hook' for more information.
  15485. This hook runs after it has been established that the cursor is not in a
  15486. table, but before checking if the cursor is in a headline or if global cycling
  15487. should be done.
  15488. If any function in this hook returns t, not other actions like visibility
  15489. cycling will be done.")
  15490. (defvar org-tab-after-check-for-cycling-hook nil
  15491. "Hook for functions to attach themselves to TAB.
  15492. See `org-ctrl-c-ctrl-c-hook' for more information.
  15493. This hook runs after it has been established that not table field motion and
  15494. not visibility should be done because of current context. This is probably
  15495. the place where a package like yasnippets can hook in.")
  15496. (defvar org-tab-before-tab-emulation-hook nil
  15497. "Hook for functions to attach themselves to TAB.
  15498. See `org-ctrl-c-ctrl-c-hook' for more information.
  15499. This hook runs after every other options for TAB have been exhausted, but
  15500. before indentation and \t insertion takes place.")
  15501. (defvar org-metaleft-hook nil
  15502. "Hook for functions attaching themselves to `M-left'.
  15503. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15504. (defvar org-metaright-hook nil
  15505. "Hook for functions attaching themselves to `M-right'.
  15506. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15507. (defvar org-metaup-hook nil
  15508. "Hook for functions attaching themselves to `M-up'.
  15509. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15510. (defvar org-metadown-hook nil
  15511. "Hook for functions attaching themselves to `M-down'.
  15512. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15513. (defvar org-shiftmetaleft-hook nil
  15514. "Hook for functions attaching themselves to `M-S-left'.
  15515. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15516. (defvar org-shiftmetaright-hook nil
  15517. "Hook for functions attaching themselves to `M-S-right'.
  15518. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15519. (defvar org-shiftmetaup-hook nil
  15520. "Hook for functions attaching themselves to `M-S-up'.
  15521. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15522. (defvar org-shiftmetadown-hook nil
  15523. "Hook for functions attaching themselves to `M-S-down'.
  15524. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15525. (defvar org-metareturn-hook nil
  15526. "Hook for functions attaching themselves to `M-RET'.
  15527. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15528. (defvar org-shiftup-hook nil
  15529. "Hook for functions attaching themselves to `S-up'.
  15530. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15531. (defvar org-shiftup-final-hook nil
  15532. "Hook for functions attaching themselves to `S-up'.
  15533. This one runs after all other options except shift-select have been excluded.
  15534. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15535. (defvar org-shiftdown-hook nil
  15536. "Hook for functions attaching themselves to `S-down'.
  15537. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15538. (defvar org-shiftdown-final-hook nil
  15539. "Hook for functions attaching themselves to `S-down'.
  15540. This one runs after all other options except shift-select have been excluded.
  15541. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15542. (defvar org-shiftleft-hook nil
  15543. "Hook for functions attaching themselves to `S-left'.
  15544. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15545. (defvar org-shiftleft-final-hook nil
  15546. "Hook for functions attaching themselves to `S-left'.
  15547. This one runs after all other options except shift-select have been excluded.
  15548. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15549. (defvar org-shiftright-hook nil
  15550. "Hook for functions attaching themselves to `S-right'.
  15551. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15552. (defvar org-shiftright-final-hook nil
  15553. "Hook for functions attaching themselves to `S-right'.
  15554. This one runs after all other options except shift-select have been excluded.
  15555. See `org-ctrl-c-ctrl-c-hook' for more information.")
  15556. (defun org-modifier-cursor-error ()
  15557. "Throw an error, a modified cursor command was applied in wrong context."
  15558. (user-error "This command is active in special context like tables, headlines or items"))
  15559. (defun org-shiftselect-error ()
  15560. "Throw an error because Shift-Cursor command was applied in wrong context."
  15561. (if (and (boundp 'shift-select-mode) shift-select-mode)
  15562. (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  15563. (user-error "This command works only in special context like headlines or timestamps")))
  15564. (defun org-call-for-shift-select (cmd)
  15565. (let ((this-command-keys-shift-translated t))
  15566. (call-interactively cmd)))
  15567. (defun org-shifttab (&optional arg)
  15568. "Global visibility cycling or move to previous table field.
  15569. Call `org-table-previous-field' within a table.
  15570. When ARG is nil, cycle globally through visibility states.
  15571. When ARG is a numeric prefix, show contents of this level."
  15572. (interactive "P")
  15573. (cond
  15574. ((org-at-table-p) (call-interactively 'org-table-previous-field))
  15575. ((integerp arg)
  15576. (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  15577. (message "Content view to level: %d" arg)
  15578. (org-content (prefix-numeric-value arg2))
  15579. (org-cycle-show-empty-lines t)
  15580. (setq org-cycle-global-status 'overview)
  15581. (run-hook-with-args 'org-cycle-hook 'overview)))
  15582. (t (call-interactively 'org-global-cycle))))
  15583. (defun org-shiftmetaleft ()
  15584. "Promote subtree or delete table column.
  15585. Calls `org-promote-subtree', `org-outdent-item-tree', or
  15586. `org-table-delete-column', depending on context. See the
  15587. individual commands for more information."
  15588. (interactive)
  15589. (cond
  15590. ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  15591. ((org-at-table-p) (call-interactively 'org-table-delete-column))
  15592. ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  15593. ((if (not (org-region-active-p)) (org-at-item-p)
  15594. (save-excursion (goto-char (region-beginning))
  15595. (org-at-item-p)))
  15596. (call-interactively 'org-outdent-item-tree))
  15597. (t (org-modifier-cursor-error))))
  15598. (defun org-shiftmetaright ()
  15599. "Demote subtree or insert table column.
  15600. Calls `org-demote-subtree', `org-indent-item-tree', or
  15601. `org-table-insert-column', depending on context. See the
  15602. individual commands for more information."
  15603. (interactive)
  15604. (cond
  15605. ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  15606. ((org-at-table-p) (call-interactively 'org-table-insert-column))
  15607. ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  15608. ((if (not (org-region-active-p)) (org-at-item-p)
  15609. (save-excursion (goto-char (region-beginning))
  15610. (org-at-item-p)))
  15611. (call-interactively 'org-indent-item-tree))
  15612. (t (org-modifier-cursor-error))))
  15613. (defun org-shiftmetaup (&optional _arg)
  15614. "Drag the line at point up.
  15615. In a table, kill the current row.
  15616. On a clock timestamp, update the value of the timestamp like `S-<up>'
  15617. but also adjust the previous clocked item in the clock history.
  15618. Everywhere else, drag the line at point up."
  15619. (interactive "P")
  15620. (cond
  15621. ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  15622. ((org-at-table-p) (call-interactively 'org-table-kill-row))
  15623. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15624. (call-interactively 'org-timestamp-up)))
  15625. (t (call-interactively 'org-drag-line-backward))))
  15626. (defun org-shiftmetadown (&optional _arg)
  15627. "Drag the line at point down.
  15628. In a table, insert an empty row at the current line.
  15629. On a clock timestamp, update the value of the timestamp like `S-<down>'
  15630. but also adjust the previous clocked item in the clock history.
  15631. Everywhere else, drag the line at point down."
  15632. (interactive "P")
  15633. (cond
  15634. ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  15635. ((org-at-table-p) (call-interactively 'org-table-insert-row))
  15636. ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  15637. (call-interactively 'org-timestamp-down)))
  15638. (t (call-interactively 'org-drag-line-forward))))
  15639. (defsubst org-hidden-tree-error ()
  15640. (user-error
  15641. "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  15642. (defun org-metaleft (&optional _arg)
  15643. "Promote heading, list item at point or move table column left.
  15644. Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  15645. depending on context. With no specific context, calls the Emacs
  15646. default `backward-word'. See the individual commands for more
  15647. information.
  15648. This function runs the hook `org-metaleft-hook' as a first step,
  15649. and returns at first non-nil value."
  15650. (interactive "P")
  15651. (cond
  15652. ((run-hook-with-args-until-success 'org-metaleft-hook))
  15653. ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  15654. ((org-with-limited-levels
  15655. (or (org-at-heading-p)
  15656. (and (org-region-active-p)
  15657. (save-excursion
  15658. (goto-char (region-beginning))
  15659. (org-at-heading-p)))))
  15660. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15661. (call-interactively 'org-do-promote))
  15662. ;; At an inline task.
  15663. ((org-at-heading-p)
  15664. (call-interactively 'org-inlinetask-promote))
  15665. ((or (org-at-item-p)
  15666. (and (org-region-active-p)
  15667. (save-excursion
  15668. (goto-char (region-beginning))
  15669. (org-at-item-p))))
  15670. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15671. (call-interactively 'org-outdent-item))
  15672. (t (call-interactively 'backward-word))))
  15673. (defun org-metaright (&optional _arg)
  15674. "Demote heading, list item at point or move table column right.
  15675. In front of a drawer or a block keyword, indent it correctly.
  15676. Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  15677. `org-indent-drawer' or `org-indent-block' depending on context.
  15678. With no specific context, calls the Emacs default `forward-word'.
  15679. See the individual commands for more information.
  15680. This function runs the hook `org-metaright-hook' as a first step,
  15681. and returns at first non-nil value."
  15682. (interactive "P")
  15683. (cond
  15684. ((run-hook-with-args-until-success 'org-metaright-hook))
  15685. ((org-at-table-p) (call-interactively 'org-table-move-column))
  15686. ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  15687. ((org-at-block-p) (call-interactively 'org-indent-block))
  15688. ((org-with-limited-levels
  15689. (or (org-at-heading-p)
  15690. (and (org-region-active-p)
  15691. (save-excursion
  15692. (goto-char (region-beginning))
  15693. (org-at-heading-p)))))
  15694. (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  15695. (call-interactively 'org-do-demote))
  15696. ;; At an inline task.
  15697. ((org-at-heading-p)
  15698. (call-interactively 'org-inlinetask-demote))
  15699. ((or (org-at-item-p)
  15700. (and (org-region-active-p)
  15701. (save-excursion
  15702. (goto-char (region-beginning))
  15703. (org-at-item-p))))
  15704. (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  15705. (call-interactively 'org-indent-item))
  15706. (t (call-interactively 'forward-word))))
  15707. (defun org-check-for-hidden (what)
  15708. "Check if there are hidden headlines/items in the current visual line.
  15709. WHAT can be either `headlines' or `items'. If the current line is
  15710. an outline or item heading and it has a folded subtree below it,
  15711. this function returns t, nil otherwise."
  15712. (let ((re (cond
  15713. ((eq what 'headlines) org-outline-regexp-bol)
  15714. ((eq what 'items) (org-item-beginning-re))
  15715. (t (error "This should not happen"))))
  15716. beg end)
  15717. (save-excursion
  15718. (catch 'exit
  15719. (unless (org-region-active-p)
  15720. (setq beg (point-at-bol))
  15721. (beginning-of-line 2)
  15722. (while (and (not (eobp)) ;; this is like `next-line'
  15723. (get-char-property (1- (point)) 'invisible))
  15724. (beginning-of-line 2))
  15725. (setq end (point))
  15726. (goto-char beg)
  15727. (goto-char (point-at-eol))
  15728. (setq end (max end (point)))
  15729. (while (re-search-forward re end t)
  15730. (when (get-char-property (match-beginning 0) 'invisible)
  15731. (throw 'exit t))))
  15732. nil))))
  15733. (defun org-metaup (&optional _arg)
  15734. "Move subtree up or move table row up.
  15735. Calls `org-move-subtree-up' or `org-table-move-row' or
  15736. `org-move-item-up', depending on context. See the individual commands
  15737. for more information."
  15738. (interactive "P")
  15739. (cond
  15740. ((run-hook-with-args-until-success 'org-metaup-hook))
  15741. ((org-region-active-p)
  15742. (let* ((a (save-excursion
  15743. (goto-char (min (region-beginning) (region-end)))
  15744. (line-beginning-position)))
  15745. (b (save-excursion
  15746. (goto-char (max (region-beginning) (region-end)))
  15747. (if (bolp) (1- (point)) (line-end-position))))
  15748. (c (save-excursion
  15749. (goto-char a)
  15750. (move-beginning-of-line 0)
  15751. (point)))
  15752. (d (save-excursion
  15753. (goto-char a)
  15754. (move-end-of-line 0)
  15755. (point))))
  15756. (transpose-regions a b c d)
  15757. (goto-char c)))
  15758. ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  15759. ((and (featurep 'org-inlinetask)
  15760. (org-inlinetask-in-task-p))
  15761. (org-drag-element-backward))
  15762. ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  15763. ((org-at-item-p) (call-interactively 'org-move-item-up))
  15764. (t (org-drag-element-backward))))
  15765. (defun org-metadown (&optional _arg)
  15766. "Move subtree down or move table row down.
  15767. Calls `org-move-subtree-down' or `org-table-move-row' or
  15768. `org-move-item-down', depending on context. See the individual
  15769. commands for more information."
  15770. (interactive "P")
  15771. (cond
  15772. ((run-hook-with-args-until-success 'org-metadown-hook))
  15773. ((org-region-active-p)
  15774. (let* ((a (save-excursion
  15775. (goto-char (min (region-beginning) (region-end)))
  15776. (line-beginning-position)))
  15777. (b (save-excursion
  15778. (goto-char (max (region-beginning) (region-end)))
  15779. (if (bolp) (1- (point)) (line-end-position))))
  15780. (c (save-excursion
  15781. (goto-char b)
  15782. (move-beginning-of-line (if (bolp) 1 2))
  15783. (point)))
  15784. (d (save-excursion
  15785. (goto-char b)
  15786. (move-end-of-line (if (bolp) 1 2))
  15787. (point))))
  15788. (transpose-regions a b c d)
  15789. (goto-char d)))
  15790. ((org-at-table-p) (call-interactively 'org-table-move-row))
  15791. ((and (featurep 'org-inlinetask)
  15792. (org-inlinetask-in-task-p))
  15793. (org-drag-element-forward))
  15794. ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  15795. ((org-at-item-p) (call-interactively 'org-move-item-down))
  15796. (t (org-drag-element-forward))))
  15797. (defun org-shiftup (&optional arg)
  15798. "Act on current element according to context.
  15799. Call `org-timestamp-up' or `org-priority-up', or
  15800. `org-previous-item', or `org-table-move-cell-up'. See the
  15801. individual commands for more information."
  15802. (interactive "P")
  15803. (cond
  15804. ((run-hook-with-args-until-success 'org-shiftup-hook))
  15805. ((and org-support-shift-select (org-region-active-p))
  15806. (org-call-for-shift-select 'previous-line))
  15807. ((org-at-timestamp-p 'lax)
  15808. (call-interactively (if org-edit-timestamp-down-means-later
  15809. 'org-timestamp-down 'org-timestamp-up)))
  15810. ((and (not (eq org-support-shift-select 'always))
  15811. org-priority-enable-commands
  15812. (org-at-heading-p))
  15813. (call-interactively 'org-priority-up))
  15814. ((and (not org-support-shift-select) (org-at-item-p))
  15815. (call-interactively 'org-previous-item))
  15816. ((org-clocktable-try-shift 'up arg))
  15817. ((and (not (eq org-support-shift-select 'always))
  15818. (org-at-table-p))
  15819. (org-table-move-cell-up))
  15820. ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  15821. (org-support-shift-select
  15822. (org-call-for-shift-select 'previous-line))
  15823. (t (org-shiftselect-error))))
  15824. (defun org-shiftdown (&optional arg)
  15825. "Act on current element according to context.
  15826. Call `org-timestamp-down' or `org-priority-down', or
  15827. `org-next-item', or `org-table-move-cell-down'. See the
  15828. individual commands for more information."
  15829. (interactive "P")
  15830. (cond
  15831. ((run-hook-with-args-until-success 'org-shiftdown-hook))
  15832. ((and org-support-shift-select (org-region-active-p))
  15833. (org-call-for-shift-select 'next-line))
  15834. ((org-at-timestamp-p 'lax)
  15835. (call-interactively (if org-edit-timestamp-down-means-later
  15836. 'org-timestamp-up 'org-timestamp-down)))
  15837. ((and (not (eq org-support-shift-select 'always))
  15838. org-priority-enable-commands
  15839. (org-at-heading-p))
  15840. (call-interactively 'org-priority-down))
  15841. ((and (not org-support-shift-select) (org-at-item-p))
  15842. (call-interactively 'org-next-item))
  15843. ((org-clocktable-try-shift 'down arg))
  15844. ((and (not (eq org-support-shift-select 'always))
  15845. (org-at-table-p))
  15846. (org-table-move-cell-down))
  15847. ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  15848. (org-support-shift-select
  15849. (org-call-for-shift-select 'next-line))
  15850. (t (org-shiftselect-error))))
  15851. (defun org-shiftright (&optional arg)
  15852. "Act on the current element according to context.
  15853. This does one of the following:
  15854. - switch a timestamp at point one day into the future
  15855. - on a headline, switch to the next TODO keyword
  15856. - on an item, switch entire list to the next bullet type
  15857. - on a property line, switch to the next allowed value
  15858. - on a clocktable definition line, move time block into the future
  15859. - in a table, move a single cell right"
  15860. (interactive "P")
  15861. (cond
  15862. ((run-hook-with-args-until-success 'org-shiftright-hook))
  15863. ((and org-support-shift-select (org-region-active-p))
  15864. (org-call-for-shift-select 'forward-char))
  15865. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  15866. ((and (not (eq org-support-shift-select 'always))
  15867. (org-at-heading-p))
  15868. (let ((org-inhibit-logging
  15869. (not org-treat-S-cursor-todo-selection-as-state-change))
  15870. (org-inhibit-blocking
  15871. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15872. (org-call-with-arg 'org-todo 'right)))
  15873. ((or (and org-support-shift-select
  15874. (not (eq org-support-shift-select 'always))
  15875. (org-at-item-bullet-p))
  15876. (and (not org-support-shift-select) (org-at-item-p)))
  15877. (org-call-with-arg 'org-cycle-list-bullet nil))
  15878. ((and (not (eq org-support-shift-select 'always))
  15879. (org-at-property-p))
  15880. (call-interactively 'org-property-next-allowed-value))
  15881. ((org-clocktable-try-shift 'right arg))
  15882. ((and (not (eq org-support-shift-select 'always))
  15883. (org-at-table-p))
  15884. (org-table-move-cell-right))
  15885. ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  15886. (org-support-shift-select
  15887. (org-call-for-shift-select 'forward-char))
  15888. (t (org-shiftselect-error))))
  15889. (defun org-shiftleft (&optional arg)
  15890. "Act on current element according to context.
  15891. This does one of the following:
  15892. - switch a timestamp at point one day into the past
  15893. - on a headline, switch to the previous TODO keyword.
  15894. - on an item, switch entire list to the previous bullet type
  15895. - on a property line, switch to the previous allowed value
  15896. - on a clocktable definition line, move time block into the past
  15897. - in a table, move a single cell left"
  15898. (interactive "P")
  15899. (cond
  15900. ((run-hook-with-args-until-success 'org-shiftleft-hook))
  15901. ((and org-support-shift-select (org-region-active-p))
  15902. (org-call-for-shift-select 'backward-char))
  15903. ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  15904. ((and (not (eq org-support-shift-select 'always))
  15905. (org-at-heading-p))
  15906. (let ((org-inhibit-logging
  15907. (not org-treat-S-cursor-todo-selection-as-state-change))
  15908. (org-inhibit-blocking
  15909. (not org-treat-S-cursor-todo-selection-as-state-change)))
  15910. (org-call-with-arg 'org-todo 'left)))
  15911. ((or (and org-support-shift-select
  15912. (not (eq org-support-shift-select 'always))
  15913. (org-at-item-bullet-p))
  15914. (and (not org-support-shift-select) (org-at-item-p)))
  15915. (org-call-with-arg 'org-cycle-list-bullet 'previous))
  15916. ((and (not (eq org-support-shift-select 'always))
  15917. (org-at-property-p))
  15918. (call-interactively 'org-property-previous-allowed-value))
  15919. ((org-clocktable-try-shift 'left arg))
  15920. ((and (not (eq org-support-shift-select 'always))
  15921. (org-at-table-p))
  15922. (org-table-move-cell-left))
  15923. ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  15924. (org-support-shift-select
  15925. (org-call-for-shift-select 'backward-char))
  15926. (t (org-shiftselect-error))))
  15927. (defun org-shiftcontrolright ()
  15928. "Switch to next TODO set."
  15929. (interactive)
  15930. (cond
  15931. ((and org-support-shift-select (org-region-active-p))
  15932. (org-call-for-shift-select 'forward-word))
  15933. ((and (not (eq org-support-shift-select 'always))
  15934. (org-at-heading-p))
  15935. (org-call-with-arg 'org-todo 'nextset))
  15936. (org-support-shift-select
  15937. (org-call-for-shift-select 'forward-word))
  15938. (t (org-shiftselect-error))))
  15939. (defun org-shiftcontrolleft ()
  15940. "Switch to previous TODO set."
  15941. (interactive)
  15942. (cond
  15943. ((and org-support-shift-select (org-region-active-p))
  15944. (org-call-for-shift-select 'backward-word))
  15945. ((and (not (eq org-support-shift-select 'always))
  15946. (org-at-heading-p))
  15947. (org-call-with-arg 'org-todo 'previousset))
  15948. (org-support-shift-select
  15949. (org-call-for-shift-select 'backward-word))
  15950. (t (org-shiftselect-error))))
  15951. (defun org-shiftcontrolup (&optional n)
  15952. "Change timestamps synchronously up in CLOCK log lines.
  15953. Optional argument N tells to change by that many units."
  15954. (interactive "P")
  15955. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15956. (let (org-support-shift-select)
  15957. (org-clock-timestamps-up n))
  15958. (user-error "Not at a clock log")))
  15959. (defun org-shiftcontroldown (&optional n)
  15960. "Change timestamps synchronously down in CLOCK log lines.
  15961. Optional argument N tells to change by that many units."
  15962. (interactive "P")
  15963. (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  15964. (let (org-support-shift-select)
  15965. (org-clock-timestamps-down n))
  15966. (user-error "Not at a clock log")))
  15967. (defun org-increase-number-at-point (&optional inc)
  15968. "Increment the number at point.
  15969. With an optional prefix numeric argument INC, increment using
  15970. this numeric value."
  15971. (interactive "p")
  15972. (if (not (number-at-point))
  15973. (user-error "Not on a number")
  15974. (unless inc (setq inc 1))
  15975. (let ((pos (point))
  15976. (beg (skip-chars-backward "-+^/*0-9eE."))
  15977. (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  15978. (setq nap (buffer-substring-no-properties
  15979. (+ pos beg) (+ pos beg end)))
  15980. (delete-region (+ pos beg) (+ pos beg end))
  15981. (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  15982. (when (org-at-table-p)
  15983. (org-table-align)
  15984. (org-table-end-of-field 1))))
  15985. (defun org-decrease-number-at-point (&optional inc)
  15986. "Decrement the number at point.
  15987. With an optional prefix numeric argument INC, decrement using
  15988. this numeric value."
  15989. (interactive "p")
  15990. (org-increase-number-at-point (- (or inc 1))))
  15991. (defun org-ctrl-c-ret ()
  15992. "Call `org-table-hline-and-move' or `org-insert-heading'."
  15993. (interactive)
  15994. (cond
  15995. ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  15996. (t (call-interactively 'org-insert-heading))))
  15997. (defun org-copy-visible (beg end)
  15998. "Copy the visible parts of the region."
  15999. (interactive "r")
  16000. (let ((result ""))
  16001. (while (/= beg end)
  16002. (when (get-char-property beg 'invisible)
  16003. (setq beg (next-single-char-property-change beg 'invisible nil end)))
  16004. (let ((next (next-single-char-property-change beg 'invisible nil end)))
  16005. (setq result (concat result (buffer-substring beg next)))
  16006. (setq beg next)))
  16007. (setq deactivate-mark t)
  16008. (kill-new result)
  16009. (message "Visible strings have been copied to the kill ring.")))
  16010. (defun org-copy-special ()
  16011. "Copy region in table or copy current subtree.
  16012. Calls `org-table-copy-region' or `org-copy-subtree', depending on
  16013. context. See the individual commands for more information."
  16014. (interactive)
  16015. (call-interactively
  16016. (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  16017. (defun org-cut-special ()
  16018. "Cut region in table or cut current subtree.
  16019. Calls `org-table-cut-region' or `org-cut-subtree', depending on
  16020. context. See the individual commands for more information."
  16021. (interactive)
  16022. (call-interactively
  16023. (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  16024. (defun org-paste-special (arg)
  16025. "Paste rectangular region into table, or past subtree relative to level.
  16026. Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  16027. See the individual commands for more information."
  16028. (interactive "P")
  16029. (if (org-at-table-p)
  16030. (org-table-paste-rectangle)
  16031. (org-paste-subtree arg)))
  16032. (defun org-edit-special (&optional arg)
  16033. "Call a special editor for the element at point.
  16034. When at a table, call the formula editor with `org-table-edit-formulas'.
  16035. When in a source code block, call `org-edit-src-code'.
  16036. When in a fixed-width region, call `org-edit-fixed-width-region'.
  16037. When in an export block, call `org-edit-export-block'.
  16038. When in a LaTeX environment, call `org-edit-latex-environment'.
  16039. When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  16040. When at a footnote reference, call `org-edit-footnote-reference'.
  16041. When at a planning line call, `org-deadline' and/or `org-schedule'.
  16042. When at an active timestamp, call `org-time-stamp'.
  16043. When at an inactive timestamp, call `org-time-stamp-inactive'.
  16044. On a link, call `ffap' to visit the link at point.
  16045. Otherwise, return a user error."
  16046. (interactive "P")
  16047. (let ((element (org-element-at-point)))
  16048. (barf-if-buffer-read-only)
  16049. (pcase (org-element-type element)
  16050. (`src-block
  16051. (if (not arg) (org-edit-src-code)
  16052. (let* ((info (org-babel-get-src-block-info))
  16053. (lang (nth 0 info))
  16054. (params (nth 2 info))
  16055. (session (cdr (assq :session params))))
  16056. (if (not session) (org-edit-src-code)
  16057. ;; At a source block with a session and function called
  16058. ;; with an ARG: switch to the buffer related to the
  16059. ;; inferior process.
  16060. (switch-to-buffer
  16061. (funcall (intern (concat "org-babel-prep-session:" lang))
  16062. session params))))))
  16063. (`keyword
  16064. (unless (member (org-element-property :key element)
  16065. '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  16066. (user-error "No special environment to edit here"))
  16067. (let ((value (org-element-property :value element)))
  16068. (unless (org-string-nw-p value) (user-error "No file to edit"))
  16069. (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  16070. (or (match-string 1 value)
  16071. (match-string 0 value)))))
  16072. (when (org-url-p file)
  16073. (user-error "Files located with a URL cannot be edited"))
  16074. (org-link-open-from-string
  16075. (format "[[%s]]" (expand-file-name file))))))
  16076. (`table
  16077. (if (eq (org-element-property :type element) 'table.el)
  16078. (org-edit-table.el)
  16079. (call-interactively 'org-table-edit-formulas)))
  16080. ;; Only Org tables contain `table-row' type elements.
  16081. (`table-row (call-interactively 'org-table-edit-formulas))
  16082. (`example-block (org-edit-src-code))
  16083. (`export-block (org-edit-export-block))
  16084. (`fixed-width (org-edit-fixed-width-region))
  16085. (`latex-environment (org-edit-latex-environment))
  16086. (`planning
  16087. (let ((proplist (cadr element)))
  16088. (mapc #'call-interactively
  16089. (remq nil
  16090. (list
  16091. (when (plist-get proplist :deadline) #'org-deadline)
  16092. (when (plist-get proplist :scheduled) #'org-schedule))))))
  16093. (_
  16094. ;; No notable element at point. Though, we may be at a link or
  16095. ;; a footnote reference, which are objects. Thus, scan deeper.
  16096. (let ((context (org-element-context element)))
  16097. (pcase (org-element-type context)
  16098. (`footnote-reference (org-edit-footnote-reference))
  16099. (`inline-src-block (org-edit-inline-src-code))
  16100. (`latex-fragment (org-edit-latex-fragment))
  16101. (`timestamp (if (eq 'inactive (org-element-property :type context))
  16102. (call-interactively #'org-time-stamp-inactive)
  16103. (call-interactively #'org-time-stamp)))
  16104. (`link (call-interactively #'ffap))
  16105. (_ (user-error "No special environment to edit here"))))))))
  16106. (defun org-ctrl-c-ctrl-c (&optional arg)
  16107. "Set tags in headline, or update according to changed information at point.
  16108. This command does many different things, depending on context:
  16109. - If column view is active, in agenda or org buffers, quit it.
  16110. - If there are highlights, remove them.
  16111. - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  16112. this is what we do.
  16113. - If the cursor is on a statistics cookie, update it.
  16114. - If the cursor is in a headline, in an agenda or an org buffer,
  16115. prompt for tags and insert them into the current line, aligned
  16116. to `org-tags-column'. When called with prefix arg, realign all
  16117. tags in the current buffer.
  16118. - If the cursor is in one of the special #+KEYWORD lines, this
  16119. triggers scanning the buffer for these lines and updating the
  16120. information.
  16121. - If the cursor is inside a table, realign the table. This command
  16122. works even if the automatic table editor has been turned off.
  16123. - If the cursor is on a #+TBLFM line, re-apply the formulas to
  16124. the entire table.
  16125. - If the cursor is at a footnote reference or definition, jump to
  16126. the corresponding definition or references, respectively.
  16127. - If the cursor is a the beginning of a dynamic block, update it.
  16128. - If the current buffer is a capture buffer, close note and file it.
  16129. - If the cursor is on a <<<target>>>, update radio targets and
  16130. corresponding links in this buffer.
  16131. - If the cursor is on a numbered item in a plain list, renumber the
  16132. ordered list.
  16133. - If the cursor is on a checkbox, toggle it.
  16134. - If the cursor is on a code block, evaluate it. The variable
  16135. `org-confirm-babel-evaluate' can be used to control prompting
  16136. before code block evaluation, by default every code block
  16137. evaluation requires confirmation. Code block evaluation can be
  16138. inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  16139. (interactive "P")
  16140. (cond
  16141. ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  16142. ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  16143. (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  16144. (org-remove-occur-highlights)
  16145. (message "Temporary highlights/overlays removed from current buffer"))
  16146. ((and (local-variable-p 'org-finish-function)
  16147. (fboundp org-finish-function))
  16148. (funcall org-finish-function))
  16149. ((org-babel-hash-at-point))
  16150. ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  16151. (t
  16152. (let* ((context
  16153. (org-element-lineage
  16154. (org-element-context)
  16155. ;; Limit to supported contexts.
  16156. '(babel-call clock dynamic-block footnote-definition
  16157. footnote-reference inline-babel-call inline-src-block
  16158. inlinetask item keyword node-property paragraph
  16159. plain-list planning property-drawer radio-target
  16160. src-block statistics-cookie table table-cell table-row
  16161. timestamp)
  16162. t))
  16163. (radio-list-p (org-at-radio-list-p))
  16164. (type (org-element-type context)))
  16165. ;; For convenience: at the first line of a paragraph on the same
  16166. ;; line as an item, apply function on that item instead.
  16167. (when (eq type 'paragraph)
  16168. (let ((parent (org-element-property :parent context)))
  16169. (when (and (eq (org-element-type parent) 'item)
  16170. (= (line-beginning-position)
  16171. (org-element-property :begin parent)))
  16172. (setq context parent)
  16173. (setq type 'item))))
  16174. ;; Act according to type of element or object at point.
  16175. ;;
  16176. ;; Do nothing on a blank line, except if it is contained in
  16177. ;; a source block. Hence, we first check if point is in such
  16178. ;; a block and then if it is at a blank line.
  16179. (pcase type
  16180. ((or `inline-src-block `src-block)
  16181. (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  16182. (org-babel-eval-wipe-error-buffer)
  16183. (org-babel-execute-src-block
  16184. current-prefix-arg (org-babel-get-src-block-info nil context))))
  16185. ((guard (org-match-line "[ \t]*$"))
  16186. (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  16187. (user-error
  16188. (substitute-command-keys
  16189. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  16190. ((or `babel-call `inline-babel-call)
  16191. (let ((info (org-babel-lob-get-info context)))
  16192. (when info (org-babel-execute-src-block nil info))))
  16193. (`clock (org-clock-update-time-maybe))
  16194. (`dynamic-block
  16195. (save-excursion
  16196. (goto-char (org-element-property :post-affiliated context))
  16197. (org-update-dblock)))
  16198. (`footnote-definition
  16199. (goto-char (org-element-property :post-affiliated context))
  16200. (call-interactively 'org-footnote-action))
  16201. (`footnote-reference (call-interactively #'org-footnote-action))
  16202. ((or `headline `inlinetask)
  16203. (save-excursion (goto-char (org-element-property :begin context))
  16204. (call-interactively #'org-set-tags-command)))
  16205. (`item
  16206. ;; At an item: `C-u C-u' sets checkbox to "[-]"
  16207. ;; unconditionally, whereas `C-u' will toggle its presence.
  16208. ;; Without a universal argument, if the item has a checkbox,
  16209. ;; toggle it. Otherwise repair the list.
  16210. (if (or radio-list-p
  16211. (and (boundp org-list-checkbox-radio-mode)
  16212. org-list-checkbox-radio-mode))
  16213. (org-toggle-radio-button arg)
  16214. (let* ((box (org-element-property :checkbox context))
  16215. (struct (org-element-property :structure context))
  16216. (old-struct (copy-tree struct))
  16217. (parents (org-list-parents-alist struct))
  16218. (prevs (org-list-prevs-alist struct))
  16219. (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  16220. (org-list-set-checkbox
  16221. (org-element-property :begin context) struct
  16222. (cond ((equal arg '(16)) "[-]")
  16223. ((and (not box) (equal arg '(4))) "[ ]")
  16224. ((or (not box) (equal arg '(4))) nil)
  16225. ((eq box 'on) "[ ]")
  16226. (t "[X]")))
  16227. ;; Mimic `org-list-write-struct' but with grabbing a return
  16228. ;; value from `org-list-struct-fix-box'.
  16229. (org-list-struct-fix-ind struct parents 2)
  16230. (org-list-struct-fix-item-end struct)
  16231. (org-list-struct-fix-bul struct prevs)
  16232. (org-list-struct-fix-ind struct parents)
  16233. (let ((block-item
  16234. (org-list-struct-fix-box struct parents prevs orderedp)))
  16235. (if (and box (equal struct old-struct))
  16236. (if (equal arg '(16))
  16237. (message "Checkboxes already reset")
  16238. (user-error "Cannot toggle this checkbox: %s"
  16239. (if (eq box 'on)
  16240. "all subitems checked"
  16241. "unchecked subitems")))
  16242. (org-list-struct-apply-struct struct old-struct)
  16243. (org-update-checkbox-count-maybe))
  16244. (when block-item
  16245. (message "Checkboxes were removed due to empty box at line %d"
  16246. (org-current-line block-item)))))))
  16247. (`plain-list
  16248. ;; At a plain list, with a double C-u argument, set
  16249. ;; checkboxes of each item to "[-]", whereas a single one
  16250. ;; will toggle their presence according to the state of the
  16251. ;; first item in the list. Without an argument, repair the
  16252. ;; list.
  16253. (if (or radio-list-p
  16254. (and (boundp org-list-checkbox-radio-mode)
  16255. org-list-checkbox-radio-mode))
  16256. (org-toggle-radio-button arg)
  16257. (let* ((begin (org-element-property :contents-begin context))
  16258. (struct (org-element-property :structure context))
  16259. (old-struct (copy-tree struct))
  16260. (first-box (save-excursion
  16261. (goto-char begin)
  16262. (looking-at org-list-full-item-re)
  16263. (match-string-no-properties 3)))
  16264. (new-box (cond ((equal arg '(16)) "[-]")
  16265. ((equal arg '(4)) (unless first-box "[ ]"))
  16266. ((equal first-box "[X]") "[ ]")
  16267. (t "[X]"))))
  16268. (cond
  16269. (arg
  16270. (dolist (pos
  16271. (org-list-get-all-items
  16272. begin struct (org-list-prevs-alist struct)))
  16273. (org-list-set-checkbox pos struct new-box)))
  16274. ((and first-box (eq (point) begin))
  16275. ;; For convenience, when point is at bol on the first
  16276. ;; item of the list and no argument is provided, simply
  16277. ;; toggle checkbox of that item, if any.
  16278. (org-list-set-checkbox begin struct new-box)))
  16279. (when (equal
  16280. (org-list-write-struct
  16281. struct (org-list-parents-alist struct) old-struct)
  16282. old-struct)
  16283. (message "Cannot update this checkbox"))
  16284. (org-update-checkbox-count-maybe))))
  16285. (`keyword
  16286. (let ((org-inhibit-startup-visibility-stuff t)
  16287. (org-startup-align-all-tables nil))
  16288. (when (boundp 'org-table-coordinate-overlays)
  16289. (mapc #'delete-overlay org-table-coordinate-overlays)
  16290. (setq org-table-coordinate-overlays nil))
  16291. (org-save-outline-visibility 'use-markers (org-mode-restart)))
  16292. (message "Local setup has been refreshed"))
  16293. ((or `property-drawer `node-property)
  16294. (call-interactively #'org-property-action))
  16295. (`radio-target
  16296. (call-interactively #'org-update-radio-target-regexp))
  16297. (`statistics-cookie
  16298. (call-interactively #'org-update-statistics-cookies))
  16299. ((or `table `table-cell `table-row)
  16300. ;; At a table, generate a plot if on the #+plot line,
  16301. ;; recalculate every field and align it otherwise. Also
  16302. ;; send the table if necessary.
  16303. (cond
  16304. ((and (org-match-line "[ \t]*#\\+plot:")
  16305. (< (point) (org-element-property :post-affiliated context)))
  16306. (org-plot/gnuplot))
  16307. ;; If the table has a `table.el' type, just give up.
  16308. ((eq (org-element-property :type context) 'table.el)
  16309. (message "%s" (substitute-command-keys "\\<org-mode-map>\
  16310. Use `\\[org-edit-special]' to edit table.el tables")))
  16311. ;; At a table row or cell, maybe recalculate line but always
  16312. ;; align table.
  16313. ((or (eq type 'table)
  16314. ;; Check if point is at a TBLFM line.
  16315. (and (eq type 'table-row)
  16316. (= (point) (org-element-property :end context))))
  16317. (save-excursion
  16318. (if (org-at-TBLFM-p)
  16319. (progn (require 'org-table)
  16320. (org-table-calc-current-TBLFM))
  16321. (goto-char (org-element-property :contents-begin context))
  16322. (org-call-with-arg 'org-table-recalculate (or arg t))
  16323. (orgtbl-send-table 'maybe))))
  16324. (t
  16325. (org-table-maybe-eval-formula)
  16326. (cond (arg (call-interactively #'org-table-recalculate))
  16327. ((org-table-maybe-recalculate-line))
  16328. (t (org-table-align))))))
  16329. ((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  16330. (org-timestamp-change 0 'day))
  16331. ((and `nil (guard (org-at-heading-p)))
  16332. ;; When point is on an unsupported object type, we can miss
  16333. ;; the fact that it also is at a heading. Handle it here.
  16334. (call-interactively #'org-set-tags-command))
  16335. ((guard
  16336. (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  16337. (_
  16338. (user-error
  16339. (substitute-command-keys
  16340. "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  16341. (defun org-mode-restart ()
  16342. "Restart `org-mode'."
  16343. (interactive)
  16344. (let ((indent-status (bound-and-true-p org-indent-mode)))
  16345. (funcall major-mode)
  16346. (hack-local-variables)
  16347. (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  16348. (org-indent-mode -1))
  16349. (org-reset-file-cache))
  16350. (message "%s restarted" major-mode))
  16351. (defun org-flag-above-first-heading (&optional arg)
  16352. "Hide from bob up to the first heading.
  16353. Move point to the beginning of first heading or end of buffer."
  16354. (goto-char (point-min))
  16355. (unless (org-at-heading-p)
  16356. (outline-next-heading))
  16357. (unless (bobp)
  16358. (org-flag-region 1 (1- (point)) (not arg) 'outline)))
  16359. (defun org-show-branches-buffer ()
  16360. "Show all branches in the buffer."
  16361. (org-flag-above-first-heading)
  16362. (outline-hide-sublevels 1)
  16363. (unless (eobp)
  16364. (outline-show-branches)
  16365. (while (outline-get-next-sibling)
  16366. (outline-show-branches)))
  16367. (goto-char (point-min)))
  16368. (defun org-kill-note-or-show-branches ()
  16369. "Abort storing current note, or show just branches."
  16370. (interactive)
  16371. (cond (org-finish-function
  16372. (let ((org-note-abort t)) (funcall org-finish-function)))
  16373. ((org-before-first-heading-p)
  16374. (org-show-branches-buffer)
  16375. (org-hide-archived-subtrees (point-min) (point-max)))
  16376. (t
  16377. (let ((beg (progn (org-back-to-heading) (point)))
  16378. (end (save-excursion (org-end-of-subtree t t) (point))))
  16379. (outline-hide-subtree)
  16380. (outline-show-branches)
  16381. (org-hide-archived-subtrees beg end)))))
  16382. (defun org-delete-indentation (&optional arg)
  16383. "Join current line to previous and fix whitespace at join.
  16384. If previous line is a headline add to headline title. Otherwise
  16385. the function calls `delete-indentation'.
  16386. I.e. with a non-nil optional argument, join the line with the
  16387. following one. If there is a region then join the lines in that
  16388. region."
  16389. (interactive "*P")
  16390. (if (save-excursion
  16391. (beginning-of-line (if arg 1 0))
  16392. (let ((case-fold-search nil))
  16393. (looking-at org-complex-heading-regexp)))
  16394. ;; At headline.
  16395. (let ((tags-column (when (match-beginning 5)
  16396. (save-excursion (goto-char (match-beginning 5))
  16397. (current-column))))
  16398. (string (concat " " (progn (when arg (forward-line 1))
  16399. (org-trim (delete-and-extract-region
  16400. (line-beginning-position)
  16401. (line-end-position)))))))
  16402. (unless (bobp) (delete-region (point) (1- (point))))
  16403. (goto-char (or (match-end 4)
  16404. (match-beginning 5)
  16405. (match-end 0)))
  16406. (skip-chars-backward " \t")
  16407. (save-excursion (insert string))
  16408. ;; Adjust alignment of tags.
  16409. (cond
  16410. ((not tags-column)) ;no tags
  16411. (org-auto-align-tags (org-align-tags))
  16412. (t (org--align-tags-here tags-column)))) ;preserve tags column
  16413. (let ((current-prefix-arg arg))
  16414. (call-interactively #'delete-indentation))))
  16415. (defun org-open-line (n)
  16416. "Insert a new row in tables, call `open-line' elsewhere.
  16417. If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  16418. As a special case, when a document starts with a table, allow to
  16419. call `open-line' on the very first character."
  16420. (interactive "*p")
  16421. (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  16422. (org-table-insert-row)
  16423. (open-line n)))
  16424. (defun org--newline (indent arg interactive)
  16425. "Call `newline-and-indent' or just `newline'.
  16426. If INDENT is non-nil, call `newline-and-indent' with ARG to
  16427. indent unconditionally; otherwise, call `newline' with ARG and
  16428. INTERACTIVE, which can trigger indentation if
  16429. `electric-indent-mode' is enabled."
  16430. (if indent
  16431. (org-newline-and-indent arg)
  16432. (newline arg interactive)))
  16433. (defun org-return (&optional indent arg interactive)
  16434. "Goto next table row or insert a newline.
  16435. Calls `org-table-next-row' or `newline', depending on context.
  16436. When optional INDENT argument is non-nil, call
  16437. `newline-and-indent' with ARG, otherwise call `newline' with ARG
  16438. and INTERACTIVE.
  16439. When `org-return-follows-link' is non-nil and point is on
  16440. a timestamp or a link, call `org-open-at-point'. However, it
  16441. will not happen if point is in a table or on a \"dead\"
  16442. object (e.g., within a comment). In these case, you need to use
  16443. `org-open-at-point' directly."
  16444. (interactive "i\nP\np")
  16445. (let* ((context (if org-return-follows-link (org-element-context)
  16446. (org-element-at-point)))
  16447. (element-type (org-element-type context)))
  16448. (cond
  16449. ;; In a table, call `org-table-next-row'. However, before first
  16450. ;; column or after last one, split the table.
  16451. ((or (and (eq 'table element-type)
  16452. (not (eq 'table.el (org-element-property :type context)))
  16453. (>= (point) (org-element-property :contents-begin context))
  16454. (< (point) (org-element-property :contents-end context)))
  16455. (org-element-lineage context '(table-row table-cell) t))
  16456. (if (or (looking-at-p "[ \t]*$")
  16457. (save-excursion (skip-chars-backward " \t") (bolp)))
  16458. (insert "\n")
  16459. (org-table-justify-field-maybe)
  16460. (call-interactively #'org-table-next-row)))
  16461. ;; On a link or a timestamp, call `org-open-at-point' if
  16462. ;; `org-return-follows-link' allows it. Tolerate fuzzy
  16463. ;; locations, e.g., in a comment, as `org-open-at-point'.
  16464. ((and org-return-follows-link
  16465. (or (and (eq 'link element-type)
  16466. ;; Ensure point is not on the white spaces after
  16467. ;; the link.
  16468. (let ((origin (point)))
  16469. (org-with-point-at (org-element-property :end context)
  16470. (skip-chars-backward " \t")
  16471. (> (point) origin))))
  16472. (org-in-regexp org-ts-regexp-both nil t)
  16473. (org-in-regexp org-tsr-regexp-both nil t)
  16474. (org-in-regexp org-link-any-re nil t)))
  16475. (call-interactively #'org-open-at-point))
  16476. ;; Insert newline in heading, but preserve tags.
  16477. ((and (not (bolp))
  16478. (let ((case-fold-search nil))
  16479. (org-match-line org-complex-heading-regexp)))
  16480. ;; At headline. Split line. However, if point is on keyword,
  16481. ;; priority cookie or tags, do not break any of them: add
  16482. ;; a newline after the headline instead.
  16483. (let ((tags-column (and (match-beginning 5)
  16484. (save-excursion (goto-char (match-beginning 5))
  16485. (current-column))))
  16486. (string
  16487. (when (and (match-end 4) (org-point-in-group (point) 4))
  16488. (delete-and-extract-region (point) (match-end 4)))))
  16489. ;; Adjust tag alignment.
  16490. (cond
  16491. ((not (and tags-column string)))
  16492. (org-auto-align-tags (org-align-tags))
  16493. (t (org--align-tags-here tags-column))) ;preserve tags column
  16494. (end-of-line)
  16495. (org-show-entry)
  16496. (org--newline indent arg interactive)
  16497. (when string (save-excursion (insert (org-trim string))))))
  16498. ;; In a list, make sure indenting keeps trailing text within.
  16499. ((and (not (eolp))
  16500. (org-element-lineage context '(item)))
  16501. (let ((trailing-data
  16502. (delete-and-extract-region (point) (line-end-position))))
  16503. (org--newline indent arg interactive)
  16504. (save-excursion (insert trailing-data))))
  16505. (t
  16506. ;; Do not auto-fill when point is in an Org property drawer.
  16507. (let ((auto-fill-function (and (not (org-at-property-p))
  16508. auto-fill-function)))
  16509. (org--newline indent arg interactive))))))
  16510. (defun org-return-and-maybe-indent ()
  16511. "Goto next table row, or insert a newline, maybe indented.
  16512. Call `org-table-next-row' or `org-return', depending on context.
  16513. See the individual commands for more information.
  16514. When inserting a newline, if `org-adapt-indentation' is t:
  16515. indent the line if `electric-indent-mode' is disabled, don't
  16516. indent it if it is enabled."
  16517. (interactive)
  16518. (org-return (not electric-indent-mode)))
  16519. (defun org-ctrl-c-tab (&optional arg)
  16520. "Toggle columns width in a table, or show children.
  16521. Call `org-table-toggle-column-width' if point is in a table.
  16522. Otherwise provide a compact view of the children. ARG is the
  16523. level to hide."
  16524. (interactive "p")
  16525. (cond
  16526. ((org-at-table-p)
  16527. (call-interactively #'org-table-toggle-column-width))
  16528. ((org-before-first-heading-p)
  16529. (save-excursion
  16530. (org-flag-above-first-heading)
  16531. (outline-hide-sublevels (or arg 1))))
  16532. (t
  16533. (outline-hide-subtree)
  16534. (org-show-children arg))))
  16535. (defun org-ctrl-c-star ()
  16536. "Compute table, or change heading status of lines.
  16537. Calls `org-table-recalculate' or `org-toggle-heading',
  16538. depending on context."
  16539. (interactive)
  16540. (cond
  16541. ((org-at-table-p)
  16542. (call-interactively 'org-table-recalculate))
  16543. (t
  16544. ;; Convert all lines in region to list items
  16545. (call-interactively 'org-toggle-heading))))
  16546. (defun org-ctrl-c-minus ()
  16547. "Insert separator line in table or modify bullet status of line.
  16548. Also turns a plain line or a region of lines into list items.
  16549. Calls `org-table-insert-hline', `org-toggle-item', or
  16550. `org-cycle-list-bullet', depending on context."
  16551. (interactive)
  16552. (cond
  16553. ((org-at-table-p)
  16554. (call-interactively 'org-table-insert-hline))
  16555. ((org-region-active-p)
  16556. (call-interactively 'org-toggle-item))
  16557. ((org-in-item-p)
  16558. (call-interactively 'org-cycle-list-bullet))
  16559. (t
  16560. (call-interactively 'org-toggle-item))))
  16561. (defun org-toggle-heading (&optional nstars)
  16562. "Convert headings to normal text, or items or text to headings.
  16563. If there is no active region, only convert the current line.
  16564. With a `\\[universal-argument]' prefix, convert the whole list at
  16565. point into heading.
  16566. In a region:
  16567. - If the first non blank line is a headline, remove the stars
  16568. from all headlines in the region.
  16569. - If it is a normal line, turn each and every normal line (i.e.,
  16570. not an heading or an item) in the region into headings. If you
  16571. want to convert only the first line of this region, use one
  16572. universal prefix argument.
  16573. - If it is a plain list item, turn all plain list items into headings.
  16574. When converting a line into a heading, the number of stars is chosen
  16575. such that the lines become children of the current entry. However,
  16576. when a numeric prefix argument is given, its value determines the
  16577. number of stars to add."
  16578. (interactive "P")
  16579. (let ((skip-blanks
  16580. ;; Return beginning of first non-blank line, starting from
  16581. ;; line at POS.
  16582. (lambda (pos)
  16583. (save-excursion
  16584. (goto-char pos)
  16585. (while (org-at-comment-p) (forward-line))
  16586. (skip-chars-forward " \r\t\n")
  16587. (point-at-bol))))
  16588. beg end toggled)
  16589. ;; Determine boundaries of changes. If a universal prefix has
  16590. ;; been given, put the list in a region. If region ends at a bol,
  16591. ;; do not consider the last line to be in the region.
  16592. (when (and current-prefix-arg (org-at-item-p))
  16593. (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  16594. (org-mark-element))
  16595. (if (org-region-active-p)
  16596. (setq beg (funcall skip-blanks (region-beginning))
  16597. end (copy-marker (save-excursion
  16598. (goto-char (region-end))
  16599. (if (bolp) (point) (point-at-eol)))))
  16600. (setq beg (funcall skip-blanks (point-at-bol))
  16601. end (copy-marker (point-at-eol))))
  16602. ;; Ensure inline tasks don't count as headings.
  16603. (org-with-limited-levels
  16604. (save-excursion
  16605. (goto-char beg)
  16606. (cond
  16607. ;; Case 1. Started at an heading: de-star headings.
  16608. ((org-at-heading-p)
  16609. (while (< (point) end)
  16610. (when (org-at-heading-p t)
  16611. (looking-at org-outline-regexp) (replace-match "")
  16612. (setq toggled t))
  16613. (forward-line)))
  16614. ;; Case 2. Started at an item: change items into headlines.
  16615. ;; One star will be added by `org-list-to-subtree'.
  16616. ((org-at-item-p)
  16617. (while (< (point) end)
  16618. (when (org-at-item-p)
  16619. ;; Pay attention to cases when region ends before list.
  16620. (let* ((struct (org-list-struct))
  16621. (list-end
  16622. (min (org-list-get-bottom-point struct) (1+ end))))
  16623. (save-restriction
  16624. (narrow-to-region (point) list-end)
  16625. (insert (org-list-to-subtree
  16626. (org-list-to-lisp t)
  16627. (pcase (org-current-level)
  16628. (`nil 1)
  16629. (l (1+ (org-reduced-level l)))))
  16630. "\n")))
  16631. (setq toggled t))
  16632. (forward-line)))
  16633. ;; Case 3. Started at normal text: make every line an heading,
  16634. ;; skipping headlines and items.
  16635. (t (let* ((stars
  16636. (make-string
  16637. (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  16638. (add-stars
  16639. (cond (nstars "") ; stars from prefix only
  16640. ((equal stars "") "*") ; before first heading
  16641. (org-odd-levels-only "**") ; inside heading, odd
  16642. (t "*"))) ; inside heading, oddeven
  16643. (rpl (concat stars add-stars " "))
  16644. (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  16645. (while (< (point) (if (equal nstars '(4)) lend end))
  16646. (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  16647. (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  16648. (replace-match (concat rpl (match-string 2))) (setq toggled t))
  16649. (forward-line)))))))
  16650. (unless toggled (message "Cannot toggle heading from here"))))
  16651. (defun org-meta-return (&optional arg)
  16652. "Insert a new heading or wrap a region in a table.
  16653. Calls `org-insert-heading', `org-insert-item' or
  16654. `org-table-wrap-region', depending on context. When called with
  16655. an argument, unconditionally call `org-insert-heading'."
  16656. (interactive "P")
  16657. (org-check-before-invisible-edit 'insert)
  16658. (or (run-hook-with-args-until-success 'org-metareturn-hook)
  16659. (call-interactively (cond (arg #'org-insert-heading)
  16660. ((org-at-table-p) #'org-table-wrap-region)
  16661. ((org-in-item-p) #'org-insert-item)
  16662. (t #'org-insert-heading)))))
  16663. ;;; Menu entries
  16664. (defsubst org-in-subtree-not-table-p ()
  16665. "Are we in a subtree and not in a table?"
  16666. (and (not (org-before-first-heading-p))
  16667. (not (org-at-table-p))))
  16668. ;; Define the Org mode menus
  16669. (easy-menu-define org-org-menu org-mode-map "Org menu."
  16670. `("Org"
  16671. ("Show/Hide"
  16672. ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  16673. ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  16674. ["Sparse Tree..." org-sparse-tree t]
  16675. ["Reveal Context" org-reveal t]
  16676. ["Show All" org-show-all t]
  16677. "--"
  16678. ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  16679. "--"
  16680. ["New Heading" org-insert-heading t]
  16681. ("Navigate Headings"
  16682. ["Up" outline-up-heading t]
  16683. ["Next" outline-next-visible-heading t]
  16684. ["Previous" outline-previous-visible-heading t]
  16685. ["Next Same Level" outline-forward-same-level t]
  16686. ["Previous Same Level" outline-backward-same-level t]
  16687. "--"
  16688. ["Jump" org-goto t])
  16689. ("Edit Structure"
  16690. ["Move Subtree Up" org-metaup (org-at-heading-p)]
  16691. ["Move Subtree Down" org-metadown (org-at-heading-p)]
  16692. "--"
  16693. ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
  16694. ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
  16695. ["Paste Subtree" org-paste-special (not (org-at-table-p))]
  16696. "--"
  16697. ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  16698. "--"
  16699. ["Copy visible text" org-copy-visible t]
  16700. "--"
  16701. ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  16702. ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  16703. ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
  16704. ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
  16705. "--"
  16706. ["Sort Region/Children" org-sort t]
  16707. "--"
  16708. ["Convert to odd levels" org-convert-to-odd-levels t]
  16709. ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  16710. ("Editing"
  16711. ["Emphasis..." org-emphasize t]
  16712. ["Add block structure" org-insert-structure-template t]
  16713. ["Edit Source Example" org-edit-special t]
  16714. "--"
  16715. ["Footnote new/jump" org-footnote-action t]
  16716. ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  16717. ("Archive"
  16718. ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  16719. "--"
  16720. ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  16721. ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  16722. ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  16723. "--"
  16724. ("Hyperlinks"
  16725. ["Store Link (Global)" org-store-link t]
  16726. ["Find existing link to here" org-occur-link-in-agenda-files t]
  16727. ["Insert Link" org-insert-link t]
  16728. ["Follow Link" org-open-at-point t]
  16729. "--"
  16730. ["Next link" org-next-link t]
  16731. ["Previous link" org-previous-link t]
  16732. "--"
  16733. ["Descriptive Links"
  16734. org-toggle-link-display
  16735. :style radio
  16736. :selected org-descriptive-links
  16737. ]
  16738. ["Literal Links"
  16739. org-toggle-link-display
  16740. :style radio
  16741. :selected (not org-descriptive-links)])
  16742. "--"
  16743. ("TODO Lists"
  16744. ["TODO/DONE/-" org-todo t]
  16745. ("Select keyword"
  16746. ["Next keyword" org-shiftright (org-at-heading-p)]
  16747. ["Previous keyword" org-shiftleft (org-at-heading-p)]
  16748. ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  16749. ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  16750. ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  16751. ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  16752. ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  16753. "--"
  16754. ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  16755. :selected org-enforce-todo-dependencies :style toggle :active t]
  16756. "Settings for tree at point"
  16757. ["Do Children sequentially" org-toggle-ordered-property :style radio
  16758. :selected (org-entry-get nil "ORDERED")
  16759. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16760. ["Do Children parallel" org-toggle-ordered-property :style radio
  16761. :selected (not (org-entry-get nil "ORDERED"))
  16762. :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  16763. "--"
  16764. ["Set Priority" org-priority t]
  16765. ["Priority Up" org-shiftup t]
  16766. ["Priority Down" org-shiftdown t]
  16767. "--"
  16768. ["Get news from all feeds" org-feed-update-all t]
  16769. ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  16770. ["Customize feeds" (customize-variable 'org-feed-alist) t])
  16771. ("TAGS and Properties"
  16772. ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  16773. ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  16774. "--"
  16775. ["Set property" org-set-property (not (org-before-first-heading-p))]
  16776. ["Column view of properties" org-columns t]
  16777. ["Insert Column View DBlock" org-columns-insert-dblock t])
  16778. ("Dates and Scheduling"
  16779. ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  16780. ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  16781. ("Change Date"
  16782. ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  16783. ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  16784. ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  16785. ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  16786. ["Compute Time Range" org-evaluate-time-range t]
  16787. ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  16788. ["Deadline" org-deadline (not (org-before-first-heading-p))]
  16789. "--"
  16790. ["Custom time format" org-toggle-time-stamp-overlays
  16791. :style radio :selected org-display-custom-times]
  16792. "--"
  16793. ["Goto Calendar" org-goto-calendar t]
  16794. ["Date from Calendar" org-date-from-calendar t]
  16795. "--"
  16796. ["Start/Restart Timer" org-timer-start t]
  16797. ["Pause/Continue Timer" org-timer-pause-or-continue t]
  16798. ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  16799. ["Insert Timer String" org-timer t]
  16800. ["Insert Timer Item" org-timer-item t])
  16801. ("Logging work"
  16802. ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  16803. ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  16804. ["Clock out" org-clock-out t]
  16805. ["Clock cancel" org-clock-cancel t]
  16806. "--"
  16807. ["Mark as default task" org-clock-mark-default-task t]
  16808. ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  16809. ["Goto running clock" org-clock-goto t]
  16810. "--"
  16811. ["Display times" org-clock-display t]
  16812. ["Create clock table" org-clock-report t]
  16813. "--"
  16814. ["Record DONE time"
  16815. (progn (setq org-log-done (not org-log-done))
  16816. (message "Switching to %s will %s record a timestamp"
  16817. (car org-done-keywords)
  16818. (if org-log-done "automatically" "not")))
  16819. :style toggle :selected org-log-done])
  16820. "--"
  16821. ["Agenda Command..." org-agenda t]
  16822. ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  16823. ("File List for Agenda")
  16824. ("Special views current file"
  16825. ["TODO Tree" org-show-todo-tree t]
  16826. ["Check Deadlines" org-check-deadlines t]
  16827. ["Tags/Property tree" org-match-sparse-tree t])
  16828. "--"
  16829. ["Export/Publish..." org-export-dispatch t]
  16830. ("LaTeX"
  16831. ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  16832. :style toggle :selected org-cdlatex-mode]
  16833. ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  16834. ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  16835. ["Modify math symbol" org-cdlatex-math-modify
  16836. (org-inside-LaTeX-fragment-p)]
  16837. ["Insert citation" org-reftex-citation t])
  16838. "--"
  16839. ("Documentation"
  16840. ["Show Version" org-version t]
  16841. ["Info Documentation" org-info t]
  16842. ["Browse Org News" org-browse-news t])
  16843. ("Customize"
  16844. ["Browse Org Group" org-customize t]
  16845. "--"
  16846. ["Expand This Menu" org-create-customize-menu t])
  16847. ["Send bug report" org-submit-bug-report t]
  16848. "--"
  16849. ("Refresh/Reload"
  16850. ["Refresh setup current buffer" org-mode-restart t]
  16851. ["Reload Org (after update)" org-reload t]
  16852. ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  16853. (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  16854. '("Table"
  16855. ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  16856. ["Next Field" org-cycle (org-at-table-p)]
  16857. ["Previous Field" org-shifttab (org-at-table-p)]
  16858. ["Next Row" org-return (org-at-table-p)]
  16859. "--"
  16860. ["Blank Field" org-table-blank-field (org-at-table-p)]
  16861. ["Edit Field" org-table-edit-field (org-at-table-p)]
  16862. ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  16863. "--"
  16864. ("Column"
  16865. ["Move Column Left" org-metaleft (org-at-table-p)]
  16866. ["Move Column Right" org-metaright (org-at-table-p)]
  16867. ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  16868. ["Insert Column" org-shiftmetaright (org-at-table-p)]
  16869. ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  16870. ("Row"
  16871. ["Move Row Up" org-metaup (org-at-table-p)]
  16872. ["Move Row Down" org-metadown (org-at-table-p)]
  16873. ["Delete Row" org-shiftmetaup (org-at-table-p)]
  16874. ["Insert Row" org-shiftmetadown (org-at-table-p)]
  16875. ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  16876. "--"
  16877. ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  16878. ("Rectangle"
  16879. ["Copy Rectangle" org-copy-special (org-at-table-p)]
  16880. ["Cut Rectangle" org-cut-special (org-at-table-p)]
  16881. ["Paste Rectangle" org-paste-special (org-at-table-p)]
  16882. ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  16883. "--"
  16884. ("Calculate"
  16885. ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  16886. ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  16887. ["Edit Formulas" org-edit-special (org-at-table-p)]
  16888. "--"
  16889. ["Recalculate line" org-table-recalculate (org-at-table-p)]
  16890. ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  16891. ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  16892. "--"
  16893. ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  16894. "--"
  16895. ["Sum Column/Rectangle" org-table-sum
  16896. (or (org-at-table-p) (org-region-active-p))]
  16897. ["Which Column?" org-table-current-column (org-at-table-p)])
  16898. ["Debug Formulas"
  16899. org-table-toggle-formula-debugger
  16900. :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  16901. ["Show Col/Row Numbers"
  16902. org-table-toggle-coordinate-overlays
  16903. :style toggle
  16904. :selected (bound-and-true-p org-table-overlay-coordinates)]
  16905. "--"
  16906. ["Create" org-table-create (not (org-at-table-p))]
  16907. ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  16908. ["Import from File" org-table-import (not (org-at-table-p))]
  16909. ["Export to File" org-table-export (org-at-table-p)]
  16910. "--"
  16911. ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  16912. "--"
  16913. ("Plot"
  16914. ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  16915. ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  16916. (defun org-info (&optional node)
  16917. "Read documentation for Org in the info system.
  16918. With optional NODE, go directly to that node."
  16919. (interactive)
  16920. (info (format "(org)%s" (or node ""))))
  16921. (defun org-browse-news ()
  16922. "Browse the news for the latest major release."
  16923. (interactive)
  16924. (browse-url "https://orgmode.org/Changes.html"))
  16925. ;;;###autoload
  16926. (defun org-submit-bug-report ()
  16927. "Submit a bug report on Org via mail.
  16928. Don't hesitate to report any problems or inaccurate documentation.
  16929. If you don't have setup sending mail from (X)Emacs, please copy the
  16930. output buffer into your mail program, as it gives us important
  16931. information about your Org version and configuration."
  16932. (interactive)
  16933. (require 'reporter)
  16934. (defvar reporter-prompt-for-summary-p)
  16935. (org-load-modules-maybe)
  16936. (org-require-autoloaded-modules)
  16937. (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  16938. (reporter-submit-bug-report
  16939. "emacs-orgmode@gnu.org"
  16940. (org-version nil 'full)
  16941. (let (list)
  16942. (save-window-excursion
  16943. (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  16944. (delete-other-windows)
  16945. (erase-buffer)
  16946. (insert "You are about to submit a bug report to the Org mailing list.
  16947. If your report is about Org installation, please read this section:
  16948. https://orgmode.org/org.html#Installation
  16949. Please read https://orgmode.org/org.html#Feedback on how to make
  16950. a good report, it will help Org contributors fixing your problem.
  16951. Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  16952. if the issue you are about to raise has already been dealt with.
  16953. We also would like to add your full Org and Outline configuration
  16954. to the bug report. It will help us debugging the issue.
  16955. *HOWEVER*, some variables you have customized may contain private
  16956. information. The names of customers, colleagues, or friends, might
  16957. appear in the form of file names, tags, todo states or search strings.
  16958. If you answer \"yes\" to the prompt, you might want to check and remove
  16959. such private information before sending the email.")
  16960. (add-text-properties (point-min) (point-max) '(face org-warning))
  16961. (when (yes-or-no-p "Include your Org configuration ")
  16962. (mapatoms
  16963. (lambda (v)
  16964. (and (boundp v)
  16965. (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  16966. (or (and (symbol-value v)
  16967. (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  16968. (and
  16969. (get v 'custom-type) (get v 'standard-value)
  16970. (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
  16971. (push v list)))))
  16972. (kill-buffer (get-buffer "*Warn about privacy*"))
  16973. list))
  16974. nil nil
  16975. "Remember to cover the basics, that is, what you expected to happen and
  16976. what in fact did happen. You don't know how to make a good report? See
  16977. https://orgmode.org/manual/Feedback.html#Feedback
  16978. Your bug report will be posted to the Org mailing list.
  16979. ------------------------------------------------------------------------")
  16980. (save-excursion
  16981. (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  16982. (replace-match "\\1[BUG] \\3 [\\2]")))))
  16983. (defun org-install-agenda-files-menu ()
  16984. "Install agenda file menu."
  16985. (let ((bl (buffer-list)))
  16986. (save-excursion
  16987. (while bl
  16988. (set-buffer (pop bl))
  16989. (when (derived-mode-p 'org-mode) (setq bl nil)))
  16990. (when (derived-mode-p 'org-mode)
  16991. (easy-menu-change
  16992. '("Org") "File List for Agenda"
  16993. (append
  16994. (list
  16995. ["Edit File List" (org-edit-agenda-file-list) t]
  16996. ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  16997. ["Remove Current File from List" org-remove-file t]
  16998. ["Cycle through agenda files" org-cycle-agenda-files t]
  16999. ["Occur in all agenda files" org-occur-in-agenda-files t]
  17000. "--")
  17001. (mapcar 'org-file-menu-entry
  17002. ;; Prevent initialization from failing.
  17003. (ignore-errors (org-agenda-files t)))))))))
  17004. ;;;; Documentation
  17005. (defun org-require-autoloaded-modules ()
  17006. (interactive)
  17007. (mapc #'require
  17008. '(org-agenda org-archive org-attach org-clock org-colview org-id
  17009. org-table org-timer)))
  17010. ;;;###autoload
  17011. (defun org-reload (&optional uncompiled)
  17012. "Reload all Org Lisp files.
  17013. With prefix arg UNCOMPILED, load the uncompiled versions."
  17014. (interactive "P")
  17015. (require 'loadhist)
  17016. (let* ((org-dir (org-find-library-dir "org"))
  17017. (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  17018. (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
  17019. (remove-re (format "\\`%s\\'"
  17020. (regexp-opt '("org" "org-loaddefs" "org-version"))))
  17021. (feats (delete-dups
  17022. (mapcar 'file-name-sans-extension
  17023. (mapcar 'file-name-nondirectory
  17024. (delq nil
  17025. (mapcar 'feature-file
  17026. features))))))
  17027. (lfeat (append
  17028. (sort
  17029. (setq feats
  17030. (delq nil (mapcar
  17031. (lambda (f)
  17032. (if (and (string-match feature-re f)
  17033. (not (string-match remove-re f)))
  17034. f nil))
  17035. feats)))
  17036. 'string-lessp)
  17037. (list "org-version" "org")))
  17038. (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
  17039. (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  17040. load-uncore load-misses)
  17041. (setq load-misses
  17042. (delq 't
  17043. (mapcar (lambda (f)
  17044. (or (org-load-noerror-mustsuffix (concat org-dir f))
  17045. (and (string= org-dir contrib-dir)
  17046. (org-load-noerror-mustsuffix (concat contrib-dir f)))
  17047. (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  17048. (push f load-uncore)
  17049. 't)
  17050. f))
  17051. lfeat)))
  17052. (when load-uncore
  17053. (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  17054. (if (> (length load-uncore) 1) "s were" " was")
  17055. (reverse load-uncore)))
  17056. (if load-misses
  17057. (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  17058. (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  17059. (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  17060. ;;;###autoload
  17061. (defun org-customize ()
  17062. "Call the customize function with org as argument."
  17063. (interactive)
  17064. (org-load-modules-maybe)
  17065. (org-require-autoloaded-modules)
  17066. (customize-browse 'org))
  17067. (defun org-create-customize-menu ()
  17068. "Create a full customization menu for Org mode, insert it into the menu."
  17069. (interactive)
  17070. (org-load-modules-maybe)
  17071. (org-require-autoloaded-modules)
  17072. (easy-menu-change
  17073. '("Org") "Customize"
  17074. `(["Browse Org group" org-customize t]
  17075. "--"
  17076. ,(customize-menu-create 'org)
  17077. ["Set" Custom-set t]
  17078. ["Save" Custom-save t]
  17079. ["Reset to Current" Custom-reset-current t]
  17080. ["Reset to Saved" Custom-reset-saved t]
  17081. ["Reset to Standard Settings" Custom-reset-standard t]))
  17082. (message "\"Org\"-menu now contains full customization menu"))
  17083. ;;;; Miscellaneous stuff
  17084. ;;; Generally useful functions
  17085. (defun org-in-clocktable-p ()
  17086. "Check if the cursor is in a clocktable."
  17087. (let ((pos (point)) start)
  17088. (save-excursion
  17089. (end-of-line 1)
  17090. (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  17091. (setq start (match-beginning 0))
  17092. (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  17093. (>= (match-end 0) pos)
  17094. start))))
  17095. (defun org-in-verbatim-emphasis ()
  17096. (save-match-data
  17097. (and (org-in-regexp org-verbatim-re 2)
  17098. (>= (point) (match-beginning 3))
  17099. (<= (point) (match-end 4)))))
  17100. (defun org-goto-marker-or-bmk (marker &optional bookmark)
  17101. "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
  17102. (if (and marker (marker-buffer marker)
  17103. (buffer-live-p (marker-buffer marker)))
  17104. (progn
  17105. (pop-to-buffer-same-window (marker-buffer marker))
  17106. (when (or (> marker (point-max)) (< marker (point-min)))
  17107. (widen))
  17108. (goto-char marker)
  17109. (org-show-context 'org-goto))
  17110. (if bookmark
  17111. (bookmark-jump bookmark)
  17112. (error "Cannot find location"))))
  17113. (defun org-quote-csv-field (s)
  17114. "Quote field for inclusion in CSV material."
  17115. (if (string-match "[\",]" s)
  17116. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  17117. s))
  17118. (defun org-force-self-insert (N)
  17119. "Needed to enforce self-insert under remapping."
  17120. (interactive "p")
  17121. (self-insert-command N))
  17122. (defun org-quote-vert (s)
  17123. "Replace \"|\" with \"\\vert\"."
  17124. (while (string-match "|" s)
  17125. (setq s (replace-match "\\vert" t t s)))
  17126. s)
  17127. (defun org-uuidgen-p (s)
  17128. "Is S an ID created by UUIDGEN?"
  17129. (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  17130. (defun org-in-src-block-p (&optional inside)
  17131. "Whether point is in a code source block.
  17132. When INSIDE is non-nil, don't consider we are within a source
  17133. block when point is at #+BEGIN_SRC or #+END_SRC."
  17134. (let ((case-fold-search t))
  17135. (or (and (eq (get-char-property (point) 'src-block) t))
  17136. (and (not inside)
  17137. (save-match-data
  17138. (save-excursion
  17139. (beginning-of-line)
  17140. (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
  17141. (defun org-context ()
  17142. "Return a list of contexts of the current cursor position.
  17143. If several contexts apply, all are returned.
  17144. Each context entry is a list with a symbol naming the context, and
  17145. two positions indicating start and end of the context. Possible
  17146. contexts are:
  17147. :headline anywhere in a headline
  17148. :headline-stars on the leading stars in a headline
  17149. :todo-keyword on a TODO keyword (including DONE) in a headline
  17150. :tags on the TAGS in a headline
  17151. :priority on the priority cookie in a headline
  17152. :item on the first line of a plain list item
  17153. :item-bullet on the bullet/number of a plain list item
  17154. :checkbox on the checkbox in a plain list item
  17155. :table in an Org table
  17156. :table-special on a special filed in a table
  17157. :table-table in a table.el table
  17158. :clocktable in a clocktable
  17159. :src-block in a source block
  17160. :link on a hyperlink
  17161. :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  17162. :latex-fragment on a LaTeX fragment
  17163. :latex-preview on a LaTeX fragment with overlaid preview image
  17164. This function expects the position to be visible because it uses font-lock
  17165. faces as a help to recognize the following contexts: :table-special, :link,
  17166. and :keyword."
  17167. (let* ((f (get-text-property (point) 'face))
  17168. (faces (if (listp f) f (list f)))
  17169. (case-fold-search t)
  17170. (p (point)) clist o)
  17171. ;; First the large context
  17172. (cond
  17173. ((org-at-heading-p t)
  17174. (push (list :headline (point-at-bol) (point-at-eol)) clist)
  17175. (when (progn
  17176. (beginning-of-line 1)
  17177. (looking-at org-todo-line-tags-regexp))
  17178. (push (org-point-in-group p 1 :headline-stars) clist)
  17179. (push (org-point-in-group p 2 :todo-keyword) clist)
  17180. (push (org-point-in-group p 4 :tags) clist))
  17181. (goto-char p)
  17182. (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  17183. (when (looking-at "\\[#[A-Z0-9]\\]")
  17184. (push (org-point-in-group p 0 :priority) clist)))
  17185. ((org-at-item-p)
  17186. (push (org-point-in-group p 2 :item-bullet) clist)
  17187. (push (list :item (point-at-bol)
  17188. (save-excursion (org-end-of-item) (point)))
  17189. clist)
  17190. (and (org-at-item-checkbox-p)
  17191. (push (org-point-in-group p 0 :checkbox) clist)))
  17192. ((org-at-table-p)
  17193. (push (list :table (org-table-begin) (org-table-end)) clist)
  17194. (when (memq 'org-formula faces)
  17195. (push (list :table-special
  17196. (previous-single-property-change p 'face)
  17197. (next-single-property-change p 'face))
  17198. clist)))
  17199. ((org-at-table-p 'any)
  17200. (push (list :table-table) clist)))
  17201. (goto-char p)
  17202. (let ((case-fold-search t))
  17203. ;; New the "medium" contexts: clocktables, source blocks
  17204. (cond ((org-in-clocktable-p)
  17205. (push (list :clocktable
  17206. (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  17207. (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  17208. (match-beginning 1))
  17209. (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  17210. (match-end 0)))
  17211. clist))
  17212. ((org-in-src-block-p)
  17213. (push (list :src-block
  17214. (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  17215. (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  17216. (match-beginning 1))
  17217. (and (search-forward "#+END_SRC" nil t)
  17218. (match-beginning 0)))
  17219. clist))))
  17220. (goto-char p)
  17221. ;; Now the small context
  17222. (cond
  17223. ((org-at-timestamp-p)
  17224. (push (org-point-in-group p 0 :timestamp) clist))
  17225. ((memq 'org-link faces)
  17226. (push (list :link
  17227. (previous-single-property-change p 'face)
  17228. (next-single-property-change p 'face))
  17229. clist))
  17230. ((memq 'org-special-keyword faces)
  17231. (push (list :keyword
  17232. (previous-single-property-change p 'face)
  17233. (next-single-property-change p 'face))
  17234. clist))
  17235. ((setq o (cl-some
  17236. (lambda (o)
  17237. (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  17238. o))
  17239. (overlays-at (point))))
  17240. (push (list :latex-fragment
  17241. (overlay-start o) (overlay-end o))
  17242. clist)
  17243. (push (list :latex-preview
  17244. (overlay-start o) (overlay-end o))
  17245. clist))
  17246. ((org-inside-LaTeX-fragment-p)
  17247. ;; FIXME: positions wrong.
  17248. (push (list :latex-fragment (point) (point)) clist)))
  17249. (setq clist (nreverse (delq nil clist)))
  17250. clist))
  17251. (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  17252. "Non-nil when point is between matches of START-RE and END-RE.
  17253. Also return a non-nil value when point is on one of the matches.
  17254. Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  17255. buffer positions. Default values are the positions of headlines
  17256. surrounding the point.
  17257. The functions returns a cons cell whose car (resp. cdr) is the
  17258. position before START-RE (resp. after END-RE)."
  17259. (save-match-data
  17260. (let ((pos (point))
  17261. (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  17262. (limit-down (or lim-down (save-excursion (outline-next-heading))))
  17263. beg end)
  17264. (save-excursion
  17265. ;; Point is on a block when on START-RE or if START-RE can be
  17266. ;; found before it...
  17267. (and (or (org-in-regexp start-re)
  17268. (re-search-backward start-re limit-up t))
  17269. (setq beg (match-beginning 0))
  17270. ;; ... and END-RE after it...
  17271. (goto-char (match-end 0))
  17272. (re-search-forward end-re limit-down t)
  17273. (> (setq end (match-end 0)) pos)
  17274. ;; ... without another START-RE in-between.
  17275. (goto-char (match-beginning 0))
  17276. (not (re-search-backward start-re (1+ beg) t))
  17277. ;; Return value.
  17278. (cons beg end))))))
  17279. (defun org-in-block-p (names)
  17280. "Non-nil when point belongs to a block whose name belongs to NAMES.
  17281. NAMES is a list of strings containing names of blocks.
  17282. Return first block name matched, or nil. Beware that in case of
  17283. nested blocks, the returned name may not belong to the closest
  17284. block from point."
  17285. (save-match-data
  17286. (catch 'exit
  17287. (let ((case-fold-search t)
  17288. (lim-up (save-excursion (outline-previous-heading)))
  17289. (lim-down (save-excursion (outline-next-heading))))
  17290. (dolist (name names)
  17291. (let ((n (regexp-quote name)))
  17292. (when (org-between-regexps-p
  17293. (concat "^[ \t]*#\\+begin_" n)
  17294. (concat "^[ \t]*#\\+end_" n)
  17295. lim-up lim-down)
  17296. (throw 'exit n)))))
  17297. nil)))
  17298. (defun org-occur-in-agenda-files (regexp &optional _nlines)
  17299. "Call `multi-occur' with buffers for all agenda files."
  17300. (interactive "sOrg-files matching: ")
  17301. (let* ((files (org-agenda-files))
  17302. (tnames (mapcar #'file-truename files))
  17303. (extra org-agenda-text-search-extra-files))
  17304. (when (eq (car extra) 'agenda-archives)
  17305. (setq extra (cdr extra))
  17306. (setq files (org-add-archive-files files)))
  17307. (dolist (f extra)
  17308. (unless (member (file-truename f) tnames)
  17309. (unless (member f files) (setq files (append files (list f))))
  17310. (setq tnames (append tnames (list (file-truename f))))))
  17311. (multi-occur
  17312. (mapcar (lambda (x)
  17313. (with-current-buffer
  17314. ;; FIXME: Why not just (find-file-noselect x)?
  17315. ;; Is it to avoid the "revert buffer" prompt?
  17316. (or (get-file-buffer x) (find-file-noselect x))
  17317. (widen)
  17318. (current-buffer)))
  17319. files)
  17320. regexp)))
  17321. (add-hook 'occur-mode-find-occurrence-hook
  17322. (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
  17323. (defun org-occur-link-in-agenda-files ()
  17324. "Create a link and search for it in the agendas.
  17325. The link is not stored in `org-stored-links', it is just created
  17326. for the search purpose."
  17327. (interactive)
  17328. (let ((link (condition-case nil
  17329. (org-store-link nil)
  17330. (error "Unable to create a link to here"))))
  17331. (org-occur-in-agenda-files (regexp-quote link))))
  17332. (defun org-back-over-empty-lines ()
  17333. "Move backwards over whitespace, to the beginning of the first empty line.
  17334. Returns the number of empty lines passed."
  17335. (let ((pos (point)))
  17336. (if (cdr (assq 'heading org-blank-before-new-entry))
  17337. (skip-chars-backward " \t\n\r")
  17338. (unless (eobp)
  17339. (forward-line -1)))
  17340. (beginning-of-line 2)
  17341. (goto-char (min (point) pos))
  17342. (count-lines (point) pos)))
  17343. ;;; TODO: Only called once, from ox-odt which should probably use
  17344. ;;; org-export-inline-image-p or something.
  17345. (defun org-file-image-p (file)
  17346. "Return non-nil if FILE is an image."
  17347. (save-match-data
  17348. (string-match (image-file-name-regexp) file)))
  17349. (defun org-get-cursor-date (&optional with-time)
  17350. "Return the date at cursor in as a time.
  17351. This works in the calendar and in the agenda, anywhere else it just
  17352. returns the current time.
  17353. If WITH-TIME is non-nil, returns the time of the event at point (in
  17354. the agenda) or the current time of the day; otherwise returns the
  17355. earliest time on the cursor date that Org treats as that date
  17356. (bearing in mind `org-extend-today-until')."
  17357. (let (date day defd tp hod mod)
  17358. (when with-time
  17359. (setq tp (get-text-property (point) 'time))
  17360. (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  17361. (setq hod (string-to-number (match-string 1 tp))
  17362. mod (string-to-number (match-string 2 tp))))
  17363. (or tp (let ((now (decode-time)))
  17364. (setq hod (nth 2 now)
  17365. mod (nth 1 now)))))
  17366. (cond
  17367. ((eq major-mode 'calendar-mode)
  17368. (setq date (calendar-cursor-to-date)
  17369. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17370. (nth 1 date) (nth 0 date) (nth 2 date))))
  17371. ((eq major-mode 'org-agenda-mode)
  17372. (setq day (get-text-property (point) 'day))
  17373. (when day
  17374. (setq date (calendar-gregorian-from-absolute day)
  17375. defd (encode-time 0 (or mod 0) (or hod org-extend-today-until)
  17376. (nth 1 date) (nth 0 date) (nth 2 date))))))
  17377. (or defd (current-time))))
  17378. (defun org-mark-subtree (&optional up)
  17379. "Mark the current subtree.
  17380. This puts point at the start of the current subtree, and mark at
  17381. the end. If a numeric prefix UP is given, move up into the
  17382. hierarchy of headlines by UP levels before marking the subtree."
  17383. (interactive "P")
  17384. (org-with-limited-levels
  17385. (cond ((org-at-heading-p) (beginning-of-line))
  17386. ((org-before-first-heading-p) (user-error "Not in a subtree"))
  17387. (t (outline-previous-visible-heading 1))))
  17388. (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  17389. (if (called-interactively-p 'any)
  17390. (call-interactively 'org-mark-element)
  17391. (org-mark-element)))
  17392. ;;; Indentation
  17393. (defvar org-element-greater-elements)
  17394. (defun org--get-expected-indentation (element contentsp)
  17395. "Expected indentation column for current line, according to ELEMENT.
  17396. ELEMENT is an element containing point. CONTENTSP is non-nil
  17397. when indentation is to be computed according to contents of
  17398. ELEMENT."
  17399. (let ((type (org-element-type element))
  17400. (start (org-element-property :begin element))
  17401. (post-affiliated (org-element-property :post-affiliated element)))
  17402. (org-with-wide-buffer
  17403. (cond
  17404. (contentsp
  17405. (cl-case type
  17406. ((diary-sexp footnote-definition) 0)
  17407. ((headline inlinetask nil)
  17408. (if (not org-adapt-indentation) 0
  17409. (let ((level (org-current-level)))
  17410. (if level (1+ level) 0))))
  17411. ((item plain-list) (org-list-item-body-column post-affiliated))
  17412. (t
  17413. (goto-char start)
  17414. (current-indentation))))
  17415. ((memq type '(headline inlinetask nil))
  17416. (if (org-match-line "[ \t]*$")
  17417. (org--get-expected-indentation element t)
  17418. 0))
  17419. ((memq type '(diary-sexp footnote-definition)) 0)
  17420. ;; First paragraph of a footnote definition or an item.
  17421. ;; Indent like parent.
  17422. ((< (line-beginning-position) start)
  17423. (org--get-expected-indentation
  17424. (org-element-property :parent element) t))
  17425. ;; At first line: indent according to previous sibling, if any,
  17426. ;; ignoring footnote definitions and inline tasks, or parent's
  17427. ;; contents.
  17428. ((and ( = (line-beginning-position) start)
  17429. (eq org-adapt-indentation t))
  17430. (catch 'exit
  17431. (while t
  17432. (if (= (point-min) start) (throw 'exit 0)
  17433. (goto-char (1- start))
  17434. (let* ((previous (org-element-at-point))
  17435. (parent previous))
  17436. (while (and parent (<= (org-element-property :end parent) start))
  17437. (setq previous parent
  17438. parent (org-element-property :parent parent)))
  17439. (cond
  17440. ((not previous) (throw 'exit 0))
  17441. ((> (org-element-property :end previous) start)
  17442. (throw 'exit (org--get-expected-indentation previous t)))
  17443. ((memq (org-element-type previous)
  17444. '(footnote-definition inlinetask))
  17445. (setq start (org-element-property :begin previous)))
  17446. (t (goto-char (org-element-property :begin previous))
  17447. (throw 'exit
  17448. (if (bolp) (current-indentation)
  17449. ;; At first paragraph in an item or
  17450. ;; a footnote definition.
  17451. (org--get-expected-indentation
  17452. (org-element-property :parent previous) t))))))))))
  17453. ;; Otherwise, move to the first non-blank line above.
  17454. (t
  17455. (beginning-of-line)
  17456. (let ((pos (point)))
  17457. (skip-chars-backward " \r\t\n")
  17458. (cond
  17459. ;; Two blank lines end a footnote definition or a plain
  17460. ;; list. When we indent an empty line after them, the
  17461. ;; containing list or footnote definition is over, so it
  17462. ;; qualifies as a previous sibling. Therefore, we indent
  17463. ;; like its first line.
  17464. ((and (memq type '(footnote-definition plain-list))
  17465. (> (count-lines (point) pos) 2))
  17466. (goto-char start)
  17467. (current-indentation))
  17468. ;; Line above is the first one of a paragraph at the
  17469. ;; beginning of an item or a footnote definition. Indent
  17470. ;; like parent.
  17471. ((< (line-beginning-position) start)
  17472. (org--get-expected-indentation
  17473. (org-element-property :parent element) t))
  17474. ;; Line above is the beginning of an element, i.e., point
  17475. ;; was originally on the blank lines between element's start
  17476. ;; and contents.
  17477. ((= (line-beginning-position) post-affiliated)
  17478. (org--get-expected-indentation element t))
  17479. ;; POS is after contents in a greater element. Indent like
  17480. ;; the beginning of the element.
  17481. ((and (memq type org-element-greater-elements)
  17482. (let ((cend (org-element-property :contents-end element)))
  17483. (and cend (<= cend pos))))
  17484. ;; As a special case, if point is at the end of a footnote
  17485. ;; definition or an item, indent like the very last element
  17486. ;; within. If that last element is an item, indent like
  17487. ;; its contents.
  17488. (if (memq type '(footnote-definition item plain-list))
  17489. (let ((last (org-element-at-point)))
  17490. (goto-char pos)
  17491. (org--get-expected-indentation
  17492. last (eq (org-element-type last) 'item)))
  17493. (goto-char start)
  17494. (current-indentation)))
  17495. ;; In any other case, indent like the current line.
  17496. (t (current-indentation)))))
  17497. ;; Finally, no indentation is needed, fall back to 0.
  17498. (t (current-indentation))))))
  17499. (defun org--align-node-property ()
  17500. "Align node property at point.
  17501. Alignment is done according to `org-property-format', which see."
  17502. (when (save-excursion
  17503. (beginning-of-line)
  17504. (looking-at org-property-re))
  17505. (replace-match
  17506. (concat (match-string 4)
  17507. (org-trim
  17508. (format org-property-format (match-string 1) (match-string 3))))
  17509. t t)))
  17510. (defun org-indent-line ()
  17511. "Indent line depending on context.
  17512. Indentation is done according to the following rules:
  17513. - Footnote definitions, diary sexps, headlines and inline tasks
  17514. have to start at column 0.
  17515. - On the very first line of an element, consider, in order, the
  17516. next rules until one matches:
  17517. 1. If there's a sibling element before, ignoring footnote
  17518. definitions and inline tasks, indent like its first line.
  17519. 2. If element has a parent, indent like its contents. More
  17520. precisely, if parent is an item, indent after the bullet.
  17521. Else, indent like parent's first line.
  17522. 3. Otherwise, indent relatively to current level, if
  17523. `org-adapt-indentation' is t, or to left margin.
  17524. - On a blank line at the end of an element, indent according to
  17525. the type of the element. More precisely
  17526. 1. If element is a plain list, an item, or a footnote
  17527. definition, indent like the very last element within.
  17528. 2. If element is a paragraph, indent like its last non blank
  17529. line.
  17530. 3. Otherwise, indent like its very first line.
  17531. - In the code part of a source block, use language major mode
  17532. to indent current line if `org-src-tab-acts-natively' is
  17533. non-nil. If it is nil, do nothing.
  17534. - Otherwise, indent like the first non-blank line above.
  17535. The function doesn't indent an item as it could break the whole
  17536. list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  17537. `\\[org-shiftmetaright]'.
  17538. Also align node properties according to `org-property-format'."
  17539. (interactive)
  17540. (unless (or (org-at-heading-p)
  17541. (and (eq org-adapt-indentation 'headline-data)
  17542. (not (or (org-at-clock-log-p)
  17543. (org-at-planning-p)))
  17544. (save-excursion
  17545. (beginning-of-line 1)
  17546. (skip-chars-backward "\n")
  17547. (or (org-at-heading-p)
  17548. (looking-back ":END:.*" (point-at-bol))))))
  17549. (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
  17550. (type (org-element-type element)))
  17551. (cond ((and (memq type '(plain-list item))
  17552. (= (line-beginning-position)
  17553. (org-element-property :post-affiliated element)))
  17554. nil)
  17555. ((and (eq type 'latex-environment)
  17556. (>= (point) (org-element-property :post-affiliated element))
  17557. (< (point)
  17558. (org-with-point-at (org-element-property :end element)
  17559. (skip-chars-backward " \t\n")
  17560. (line-beginning-position 2))))
  17561. nil)
  17562. ((and (eq type 'src-block)
  17563. org-src-tab-acts-natively
  17564. (> (line-beginning-position)
  17565. (org-element-property :post-affiliated element))
  17566. (< (line-beginning-position)
  17567. (org-with-point-at (org-element-property :end element)
  17568. (skip-chars-backward " \t\n")
  17569. (line-beginning-position))))
  17570. ;; At the beginning of a blank line, do some preindentation. This
  17571. ;; signals org-src--edit-element to preserve the indentation on exit
  17572. (when (and (looking-at-p "^[[:space:]]*$")
  17573. (not org-src-preserve-indentation))
  17574. (let ((element (org-element-at-point))
  17575. block-content-ind some-ind)
  17576. (org-with-point-at (org-element-property :begin element)
  17577. (setq block-content-ind (+ (current-indentation)
  17578. org-edit-src-content-indentation))
  17579. (forward-line)
  17580. (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  17581. (backward-char)
  17582. (setq some-ind (if (looking-at-p "#\\+end_src")
  17583. block-content-ind (current-indentation))))
  17584. (indent-line-to (min block-content-ind some-ind))))
  17585. (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  17586. (t
  17587. (let ((column (org--get-expected-indentation element nil)))
  17588. ;; Preserve current column.
  17589. (if (<= (current-column) (current-indentation))
  17590. (indent-line-to column)
  17591. (save-excursion (indent-line-to column))))
  17592. ;; Align node property. Also preserve current column.
  17593. (when (eq type 'node-property)
  17594. (let ((column (current-column)))
  17595. (org--align-node-property)
  17596. (org-move-to-column column))))))))
  17597. (defun org-indent-region (start end)
  17598. "Indent each non-blank line in the region.
  17599. Called from a program, START and END specify the region to
  17600. indent. The function will not indent contents of example blocks,
  17601. verse blocks and export blocks as leading white spaces are
  17602. assumed to be significant there."
  17603. (interactive "r")
  17604. (save-excursion
  17605. (goto-char start)
  17606. (skip-chars-forward " \r\t\n")
  17607. (unless (eobp) (beginning-of-line))
  17608. (let ((indent-to
  17609. (lambda (ind pos)
  17610. ;; Set IND as indentation for all lines between point and
  17611. ;; POS. Blank lines are ignored. Leave point after POS
  17612. ;; once done.
  17613. (let ((limit (copy-marker pos)))
  17614. (while (< (point) limit)
  17615. (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  17616. (forward-line))
  17617. (set-marker limit nil))))
  17618. (end (copy-marker end)))
  17619. (while (< (point) end)
  17620. (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  17621. (let* ((element (org-element-at-point))
  17622. (type (org-element-type element))
  17623. (element-end (copy-marker (org-element-property :end element)))
  17624. (ind (org--get-expected-indentation element nil)))
  17625. (cond
  17626. ;; Element indented as a single block. Example blocks
  17627. ;; preserving indentation are a special case since the
  17628. ;; "contents" must not be indented whereas the block
  17629. ;; boundaries can.
  17630. ((or (memq type '(export-block latex-environment))
  17631. (and (eq type 'example-block)
  17632. (not
  17633. (or org-src-preserve-indentation
  17634. (org-element-property :preserve-indent element)))))
  17635. (let ((offset (- ind (current-indentation))))
  17636. (unless (zerop offset)
  17637. (indent-rigidly (org-element-property :begin element)
  17638. (org-element-property :end element)
  17639. offset)))
  17640. (goto-char element-end))
  17641. ;; Elements indented line wise. Be sure to exclude
  17642. ;; example blocks (preserving indentation) and source
  17643. ;; blocks from this category as they are treated
  17644. ;; specially later.
  17645. ((or (memq type '(paragraph table table-row))
  17646. (not (or (org-element-property :contents-begin element)
  17647. (memq type '(example-block src-block)))))
  17648. (when (eq type 'node-property)
  17649. (org--align-node-property)
  17650. (beginning-of-line))
  17651. (funcall indent-to ind (min element-end end)))
  17652. ;; Elements consisting of three parts: before the
  17653. ;; contents, the contents, and after the contents. The
  17654. ;; contents are treated specially, according to the
  17655. ;; element type, or not indented at all. Other parts are
  17656. ;; indented as a single block.
  17657. (t
  17658. (let* ((post (copy-marker
  17659. (org-element-property :post-affiliated element)))
  17660. (cbeg
  17661. (copy-marker
  17662. (cond
  17663. ((not (org-element-property :contents-begin element))
  17664. ;; Fake contents for source blocks.
  17665. (org-with-wide-buffer
  17666. (goto-char post)
  17667. (line-beginning-position 2)))
  17668. ((memq type '(footnote-definition item plain-list))
  17669. ;; Contents in these elements could start on
  17670. ;; the same line as the beginning of the
  17671. ;; element. Make sure we start indenting
  17672. ;; from the second line.
  17673. (org-with-wide-buffer
  17674. (goto-char post)
  17675. (end-of-line)
  17676. (skip-chars-forward " \r\t\n")
  17677. (if (eobp) (point) (line-beginning-position))))
  17678. (t (org-element-property :contents-begin element)))))
  17679. (cend (copy-marker
  17680. (or (org-element-property :contents-end element)
  17681. ;; Fake contents for source blocks.
  17682. (org-with-wide-buffer
  17683. (goto-char element-end)
  17684. (skip-chars-backward " \r\t\n")
  17685. (line-beginning-position)))
  17686. t)))
  17687. ;; Do not change items indentation individually as it
  17688. ;; might break the list as a whole. On the other
  17689. ;; hand, when at a plain list, indent it as a whole.
  17690. (cond ((eq type 'plain-list)
  17691. (let ((offset (- ind (current-indentation))))
  17692. (unless (zerop offset)
  17693. (indent-rigidly (org-element-property :begin element)
  17694. (org-element-property :end element)
  17695. offset))
  17696. (goto-char cbeg)))
  17697. ((eq type 'item) (goto-char cbeg))
  17698. (t (funcall indent-to ind (min cbeg end))))
  17699. (when (< (point) end)
  17700. (cl-case type
  17701. ((example-block verse-block))
  17702. (src-block
  17703. ;; In a source block, indent source code
  17704. ;; according to language major mode, but only if
  17705. ;; `org-src-tab-acts-natively' is non-nil.
  17706. (when (and (< (point) end) org-src-tab-acts-natively)
  17707. (ignore-errors
  17708. (org-babel-do-in-edit-buffer
  17709. (indent-region (point-min) (point-max))))))
  17710. (t (org-indent-region (point) (min cend end))))
  17711. (goto-char (min cend end))
  17712. (when (< (point) end)
  17713. (funcall indent-to ind (min element-end end))))
  17714. (set-marker post nil)
  17715. (set-marker cbeg nil)
  17716. (set-marker cend nil))))
  17717. (set-marker element-end nil))))
  17718. (set-marker end nil))))
  17719. (defun org-indent-drawer ()
  17720. "Indent the drawer at point."
  17721. (interactive)
  17722. (unless (save-excursion
  17723. (beginning-of-line)
  17724. (looking-at-p org-drawer-regexp))
  17725. (user-error "Not at a drawer"))
  17726. (let ((element (org-element-at-point)))
  17727. (unless (memq (org-element-type element) '(drawer property-drawer))
  17728. (user-error "Not at a drawer"))
  17729. (org-with-wide-buffer
  17730. (org-indent-region (org-element-property :begin element)
  17731. (org-element-property :end element))))
  17732. (message "Drawer at point indented"))
  17733. (defun org-indent-block ()
  17734. "Indent the block at point."
  17735. (interactive)
  17736. (unless (save-excursion
  17737. (beginning-of-line)
  17738. (let ((case-fold-search t))
  17739. (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  17740. (user-error "Not at a block"))
  17741. (let ((element (org-element-at-point)))
  17742. (unless (memq (org-element-type element)
  17743. '(comment-block center-block dynamic-block example-block
  17744. export-block quote-block special-block
  17745. src-block verse-block))
  17746. (user-error "Not at a block"))
  17747. (org-with-wide-buffer
  17748. (org-indent-region (org-element-property :begin element)
  17749. (org-element-property :end element))))
  17750. (message "Block at point indented"))
  17751. ;;; Filling
  17752. ;; We use our own fill-paragraph and auto-fill functions.
  17753. ;; `org-fill-paragraph' relies on adaptive filling and context
  17754. ;; checking. Appropriate `fill-prefix' is computed with
  17755. ;; `org-adaptive-fill-function'.
  17756. ;; `org-auto-fill-function' takes care of auto-filling. It calls
  17757. ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  17758. ;; `org-adaptive-fill-function' value. Internally,
  17759. ;; `org-comment-line-break-function' breaks the line.
  17760. ;; `org-setup-filling' installs filling and auto-filling related
  17761. ;; variables during `org-mode' initialization.
  17762. (defun org-setup-filling ()
  17763. (require 'org-element)
  17764. ;; Prevent auto-fill from inserting unwanted new items.
  17765. (when (boundp 'fill-nobreak-predicate)
  17766. (setq-local
  17767. fill-nobreak-predicate
  17768. (org-uniquify
  17769. (append fill-nobreak-predicate
  17770. '(org-fill-line-break-nobreak-p
  17771. org-fill-n-macro-as-item-nobreak-p
  17772. org-fill-paragraph-with-timestamp-nobreak-p)))))
  17773. (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  17774. (setq-local paragraph-start paragraph-ending)
  17775. (setq-local paragraph-separate paragraph-ending))
  17776. (setq-local fill-paragraph-function 'org-fill-paragraph)
  17777. (setq-local auto-fill-inhibit-regexp nil)
  17778. (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  17779. (setq-local normal-auto-fill-function 'org-auto-fill-function)
  17780. (setq-local comment-line-break-function 'org-comment-line-break-function))
  17781. (defun org-fill-line-break-nobreak-p ()
  17782. "Non-nil when a new line at point would create an Org line break."
  17783. (save-excursion
  17784. (skip-chars-backward " \t")
  17785. (skip-chars-backward "\\\\")
  17786. (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  17787. (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  17788. "Non-nil when a new line at point would split a timestamp."
  17789. (and (org-at-timestamp-p 'lax)
  17790. (not (looking-at org-ts-regexp-both))))
  17791. (defun org-fill-n-macro-as-item-nobreak-p ()
  17792. "Non-nil when a new line at point would create a new list."
  17793. ;; During export, a "n" macro followed by a dot or a closing
  17794. ;; parenthesis can end up being parsed as a new list item.
  17795. (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  17796. (defun org-adaptive-fill-function ()
  17797. "Compute a fill prefix for the current line.
  17798. Return fill prefix, as a string, or nil if current line isn't
  17799. meant to be filled. For convenience, if `adaptive-fill-regexp'
  17800. matches in paragraphs or comments, use it."
  17801. (org-with-wide-buffer
  17802. (unless (org-at-heading-p)
  17803. (let* ((p (line-beginning-position))
  17804. (element (save-excursion
  17805. (beginning-of-line)
  17806. (org-element-at-point)))
  17807. (type (org-element-type element))
  17808. (post-affiliated (org-element-property :post-affiliated element)))
  17809. (unless (< p post-affiliated)
  17810. (cl-case type
  17811. (comment
  17812. (save-excursion
  17813. (beginning-of-line)
  17814. (looking-at "[ \t]*")
  17815. (concat (match-string 0) "# ")))
  17816. (footnote-definition "")
  17817. ((item plain-list)
  17818. (make-string (org-list-item-body-column post-affiliated) ?\s))
  17819. (paragraph
  17820. ;; Fill prefix is usually the same as the current line,
  17821. ;; unless the paragraph is at the beginning of an item.
  17822. (let ((parent (org-element-property :parent element)))
  17823. (save-excursion
  17824. (beginning-of-line)
  17825. (cond ((eq (org-element-type parent) 'item)
  17826. (make-string (org-list-item-body-column
  17827. (org-element-property :begin parent))
  17828. ?\s))
  17829. ((and adaptive-fill-regexp
  17830. ;; Locally disable
  17831. ;; `adaptive-fill-function' to let
  17832. ;; `fill-context-prefix' handle
  17833. ;; `adaptive-fill-regexp' variable.
  17834. (let (adaptive-fill-function)
  17835. (fill-context-prefix
  17836. post-affiliated
  17837. (org-element-property :end element)))))
  17838. ((looking-at "[ \t]+") (match-string 0))
  17839. (t "")))))
  17840. (comment-block
  17841. ;; Only fill contents if P is within block boundaries.
  17842. (let* ((cbeg (save-excursion (goto-char post-affiliated)
  17843. (forward-line)
  17844. (point)))
  17845. (cend (save-excursion
  17846. (goto-char (org-element-property :end element))
  17847. (skip-chars-backward " \r\t\n")
  17848. (line-beginning-position))))
  17849. (when (and (>= p cbeg) (< p cend))
  17850. (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  17851. (match-string 0)
  17852. ""))))))))))
  17853. (defun org-fill-element (&optional justify)
  17854. "Fill element at point, when applicable.
  17855. This function only applies to comment blocks, comments, example
  17856. blocks and paragraphs. Also, as a special case, re-align table
  17857. when point is at one.
  17858. If JUSTIFY is non-nil (interactively, with prefix argument),
  17859. justify as well. If `sentence-end-double-space' is non-nil, then
  17860. period followed by one space does not end a sentence, so don't
  17861. break a line there. The variable `fill-column' controls the
  17862. width for filling.
  17863. For convenience, when point is at a plain list, an item or
  17864. a footnote definition, try to fill the first paragraph within."
  17865. (with-syntax-table org-mode-transpose-word-syntax-table
  17866. ;; Move to end of line in order to get the first paragraph within
  17867. ;; a plain list or a footnote definition.
  17868. (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  17869. ;; First check if point is in a blank line at the beginning of
  17870. ;; the buffer. In that case, ignore filling.
  17871. (cl-case (org-element-type element)
  17872. ;; Use major mode filling function is source blocks.
  17873. (src-block (org-babel-do-in-edit-buffer
  17874. (push-mark (point-min))
  17875. (goto-char (point-max))
  17876. (setq mark-active t)
  17877. (funcall-interactively #'fill-paragraph justify 'region)))
  17878. ;; Align Org tables, leave table.el tables as-is.
  17879. (table-row (org-table-align) t)
  17880. (table
  17881. (when (eq (org-element-property :type element) 'org)
  17882. (save-excursion
  17883. (goto-char (org-element-property :post-affiliated element))
  17884. (org-table-align)))
  17885. t)
  17886. (paragraph
  17887. ;; Paragraphs may contain `line-break' type objects.
  17888. (let ((beg (max (point-min)
  17889. (org-element-property :contents-begin element)))
  17890. (end (min (point-max)
  17891. (org-element-property :contents-end element))))
  17892. ;; Do nothing if point is at an affiliated keyword.
  17893. (if (< (line-end-position) beg) t
  17894. ;; Fill paragraph, taking line breaks into account.
  17895. (save-excursion
  17896. (goto-char beg)
  17897. (let ((cuts (list beg)))
  17898. (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  17899. (when (eq 'line-break
  17900. (org-element-type
  17901. (save-excursion (backward-char)
  17902. (org-element-context))))
  17903. (push (point) cuts)))
  17904. (dolist (c (delq end cuts))
  17905. (fill-region-as-paragraph c end justify)
  17906. (setq end c))))
  17907. t)))
  17908. ;; Contents of `comment-block' type elements should be
  17909. ;; filled as plain text, but only if point is within block
  17910. ;; markers.
  17911. (comment-block
  17912. (let* ((case-fold-search t)
  17913. (beg (save-excursion
  17914. (goto-char (org-element-property :begin element))
  17915. (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  17916. (forward-line)
  17917. (point)))
  17918. (end (save-excursion
  17919. (goto-char (org-element-property :end element))
  17920. (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  17921. (line-beginning-position))))
  17922. (if (or (< (point) beg) (> (point) end)) t
  17923. (fill-region-as-paragraph
  17924. (save-excursion (end-of-line)
  17925. (re-search-backward "^[ \t]*$" beg 'move)
  17926. (line-beginning-position))
  17927. (save-excursion (beginning-of-line)
  17928. (re-search-forward "^[ \t]*$" end 'move)
  17929. (line-beginning-position))
  17930. justify))))
  17931. ;; Fill comments.
  17932. (comment
  17933. (let ((begin (org-element-property :post-affiliated element))
  17934. (end (org-element-property :end element)))
  17935. (when (and (>= (point) begin) (<= (point) end))
  17936. (let ((begin (save-excursion
  17937. (end-of-line)
  17938. (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  17939. (progn (forward-line) (point))
  17940. begin)))
  17941. (end (save-excursion
  17942. (end-of-line)
  17943. (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  17944. (1- (line-beginning-position))
  17945. (skip-chars-backward " \r\t\n")
  17946. (line-end-position)))))
  17947. ;; Do not fill comments when at a blank line.
  17948. (when (> end begin)
  17949. (let ((fill-prefix
  17950. (save-excursion
  17951. (beginning-of-line)
  17952. (looking-at "[ \t]*#")
  17953. (let ((comment-prefix (match-string 0)))
  17954. (goto-char (match-end 0))
  17955. (if (looking-at adaptive-fill-regexp)
  17956. (concat comment-prefix (match-string 0))
  17957. (concat comment-prefix " "))))))
  17958. (save-excursion
  17959. (fill-region-as-paragraph begin end justify))))))
  17960. t))
  17961. ;; Ignore every other element.
  17962. (otherwise t)))))
  17963. (defun org-fill-paragraph (&optional justify region)
  17964. "Fill element at point, when applicable.
  17965. This function only applies to comment blocks, comments, example
  17966. blocks and paragraphs. Also, as a special case, re-align table
  17967. when point is at one.
  17968. For convenience, when point is at a plain list, an item or
  17969. a footnote definition, try to fill the first paragraph within.
  17970. If JUSTIFY is non-nil (interactively, with prefix argument),
  17971. justify as well. If `sentence-end-double-space' is non-nil, then
  17972. period followed by one space does not end a sentence, so don't
  17973. break a line there. The variable `fill-column' controls the
  17974. width for filling.
  17975. The REGION argument is non-nil if called interactively; in that
  17976. case, if Transient Mark mode is enabled and the mark is active,
  17977. fill each of the elements in the active region, instead of just
  17978. filling the current element."
  17979. (interactive (progn
  17980. (barf-if-buffer-read-only)
  17981. (list (when current-prefix-arg 'full) t)))
  17982. (let ((hash (and (not (buffer-modified-p))
  17983. (org-buffer-hash))))
  17984. (cond
  17985. ((and region transient-mark-mode mark-active
  17986. (not (eq (region-beginning) (region-end))))
  17987. (let ((origin (point-marker))
  17988. (start (region-beginning)))
  17989. (unwind-protect
  17990. (progn
  17991. (goto-char (region-end))
  17992. (skip-chars-backward " \t\n")
  17993. (while (> (point) start)
  17994. (org-fill-element justify)
  17995. (org-backward-paragraph)))
  17996. (goto-char origin)
  17997. (set-marker origin nil))))
  17998. (t
  17999. (save-excursion
  18000. (when (org-match-line "[ \t]*$")
  18001. (skip-chars-forward " \t\n"))
  18002. (org-fill-element justify))))
  18003. ;; If we didn't change anything in the buffer (and the buffer was
  18004. ;; previously unmodified), then flip the modification status back
  18005. ;; to "unchanged".
  18006. (when (and hash (equal hash (org-buffer-hash)))
  18007. (set-buffer-modified-p nil))
  18008. ;; Return non-nil.
  18009. t))
  18010. (defun org-auto-fill-function ()
  18011. "Auto-fill function."
  18012. ;; Check if auto-filling is meaningful.
  18013. (let ((fc (current-fill-column)))
  18014. (when (and fc (> (current-column) fc))
  18015. (let* ((fill-prefix (org-adaptive-fill-function))
  18016. ;; Enforce empty fill prefix, if required. Otherwise, it
  18017. ;; will be computed again.
  18018. (adaptive-fill-mode (not (equal fill-prefix ""))))
  18019. (when fill-prefix (do-auto-fill))))))
  18020. (defun org-comment-line-break-function (&optional soft)
  18021. "Break line at point and indent, continuing comment if within one.
  18022. The inserted newline is marked hard if variable
  18023. `use-hard-newlines' is true, unless optional argument SOFT is
  18024. non-nil."
  18025. (if soft (insert-and-inherit ?\n) (newline 1))
  18026. (save-excursion (forward-char -1) (delete-horizontal-space))
  18027. (delete-horizontal-space)
  18028. (indent-to-left-margin)
  18029. (insert-before-markers-and-inherit fill-prefix))
  18030. ;;; Fixed Width Areas
  18031. (defun org-toggle-fixed-width ()
  18032. "Toggle fixed-width markup.
  18033. Add or remove fixed-width markup on current line, whenever it
  18034. makes sense. Return an error otherwise.
  18035. If a region is active and if it contains only fixed-width areas
  18036. or blank lines, remove all fixed-width markup in it. If the
  18037. region contains anything else, convert all non-fixed-width lines
  18038. to fixed-width ones.
  18039. Blank lines at the end of the region are ignored unless the
  18040. region only contains such lines."
  18041. (interactive)
  18042. (if (not (org-region-active-p))
  18043. ;; No region:
  18044. ;;
  18045. ;; Remove fixed width marker only in a fixed-with element.
  18046. ;;
  18047. ;; Add fixed width maker in paragraphs, in blank lines after
  18048. ;; elements or at the beginning of a headline or an inlinetask,
  18049. ;; and before any one-line elements (e.g., a clock).
  18050. (progn
  18051. (beginning-of-line)
  18052. (let* ((element (org-element-at-point))
  18053. (type (org-element-type element)))
  18054. (cond
  18055. ((and (eq type 'fixed-width)
  18056. (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  18057. (replace-match
  18058. "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  18059. ((and (memq type '(babel-call clock comment diary-sexp headline
  18060. horizontal-rule keyword paragraph
  18061. planning))
  18062. (<= (org-element-property :post-affiliated element) (point)))
  18063. (skip-chars-forward " \t")
  18064. (insert ": "))
  18065. ((and (looking-at-p "[ \t]*$")
  18066. (or (eq type 'inlinetask)
  18067. (save-excursion
  18068. (skip-chars-forward " \r\t\n")
  18069. (<= (org-element-property :end element) (point)))))
  18070. (delete-region (point) (line-end-position))
  18071. (org-indent-line)
  18072. (insert ": "))
  18073. (t (user-error "Cannot insert a fixed-width line here")))))
  18074. ;; Region active.
  18075. (let* ((begin (save-excursion
  18076. (goto-char (region-beginning))
  18077. (line-beginning-position)))
  18078. (end (copy-marker
  18079. (save-excursion
  18080. (goto-char (region-end))
  18081. (unless (eolp) (beginning-of-line))
  18082. (if (save-excursion (re-search-backward "\\S-" begin t))
  18083. (progn (skip-chars-backward " \r\t\n") (point))
  18084. (point)))))
  18085. (all-fixed-width-p
  18086. (catch 'not-all-p
  18087. (save-excursion
  18088. (goto-char begin)
  18089. (skip-chars-forward " \r\t\n")
  18090. (when (eobp) (throw 'not-all-p nil))
  18091. (while (< (point) end)
  18092. (let ((element (org-element-at-point)))
  18093. (if (eq (org-element-type element) 'fixed-width)
  18094. (goto-char (org-element-property :end element))
  18095. (throw 'not-all-p nil))))
  18096. t))))
  18097. (if all-fixed-width-p
  18098. (save-excursion
  18099. (goto-char begin)
  18100. (while (< (point) end)
  18101. (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  18102. (replace-match
  18103. "" nil nil nil
  18104. (if (= (line-end-position) (match-end 0)) 0 1)))
  18105. (forward-line)))
  18106. (let ((min-ind (point-max)))
  18107. ;; Find minimum indentation across all lines.
  18108. (save-excursion
  18109. (goto-char begin)
  18110. (if (not (save-excursion (re-search-forward "\\S-" end t)))
  18111. (setq min-ind 0)
  18112. (catch 'zerop
  18113. (while (< (point) end)
  18114. (unless (looking-at-p "[ \t]*$")
  18115. (let ((ind (current-indentation)))
  18116. (setq min-ind (min min-ind ind))
  18117. (when (zerop ind) (throw 'zerop t))))
  18118. (forward-line)))))
  18119. ;; Loop over all lines and add fixed-width markup everywhere
  18120. ;; but in fixed-width lines.
  18121. (save-excursion
  18122. (goto-char begin)
  18123. (while (< (point) end)
  18124. (cond
  18125. ((org-at-heading-p)
  18126. (insert ": ")
  18127. (forward-line)
  18128. (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  18129. (insert ":")
  18130. (forward-line)))
  18131. ((looking-at-p "[ \t]*:\\( \\|$\\)")
  18132. (let* ((element (org-element-at-point))
  18133. (element-end (org-element-property :end element)))
  18134. (if (eq (org-element-type element) 'fixed-width)
  18135. (progn (goto-char element-end)
  18136. (skip-chars-backward " \r\t\n")
  18137. (forward-line))
  18138. (let ((limit (min end element-end)))
  18139. (while (< (point) limit)
  18140. (org-move-to-column min-ind t)
  18141. (insert ": ")
  18142. (forward-line))))))
  18143. (t
  18144. (org-move-to-column min-ind t)
  18145. (insert ": ")
  18146. (forward-line)))))))
  18147. (set-marker end nil))))
  18148. ;;; Blocks
  18149. (defun org-block-map (function &optional start end)
  18150. "Call FUNCTION at the head of all source blocks in the current buffer.
  18151. Optional arguments START and END can be used to limit the range."
  18152. (let ((start (or start (point-min)))
  18153. (end (or end (point-max))))
  18154. (save-excursion
  18155. (goto-char start)
  18156. (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  18157. (save-excursion
  18158. (save-match-data
  18159. (goto-char (match-beginning 0))
  18160. (funcall function)))))))
  18161. (defun org-next-block (arg &optional backward block-regexp)
  18162. "Jump to the next block.
  18163. With a prefix argument ARG, jump forward ARG many blocks.
  18164. When BACKWARD is non-nil, jump to the previous block.
  18165. When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  18166. Match data is set according to this regexp when the function
  18167. returns.
  18168. Return point at beginning of the opening line of found block.
  18169. Throw an error if no block is found."
  18170. (interactive "p")
  18171. (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  18172. (case-fold-search t)
  18173. (search-fn (if backward #'re-search-backward #'re-search-forward))
  18174. (count (or arg 1))
  18175. (origin (point))
  18176. last-element)
  18177. (if backward (beginning-of-line) (end-of-line))
  18178. (while (and (> count 0) (funcall search-fn re nil t))
  18179. (let ((element (save-excursion
  18180. (goto-char (match-beginning 0))
  18181. (save-match-data (org-element-at-point)))))
  18182. (when (and (memq (org-element-type element)
  18183. '(center-block comment-block dynamic-block
  18184. example-block export-block quote-block
  18185. special-block src-block verse-block))
  18186. (<= (match-beginning 0)
  18187. (org-element-property :post-affiliated element)))
  18188. (setq last-element element)
  18189. (cl-decf count))))
  18190. (if (= count 0)
  18191. (prog1 (goto-char (org-element-property :post-affiliated last-element))
  18192. (save-match-data (org-show-context)))
  18193. (goto-char origin)
  18194. (user-error "No %s code blocks" (if backward "previous" "further")))))
  18195. (defun org-previous-block (arg &optional block-regexp)
  18196. "Jump to the previous block.
  18197. With a prefix argument ARG, jump backward ARG many source blocks.
  18198. When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  18199. (interactive "p")
  18200. (org-next-block arg t block-regexp))
  18201. ;;; Comments
  18202. ;; Org comments syntax is quite complex. It requires the entire line
  18203. ;; to be just a comment. Also, even with the right syntax at the
  18204. ;; beginning of line, some elements (e.g., verse-block or
  18205. ;; example-block) don't accept comments. Usual Emacs comment commands
  18206. ;; cannot cope with those requirements. Therefore, Org replaces them.
  18207. ;; Org still relies on 'comment-dwim', but cannot trust
  18208. ;; 'comment-only-p'. So, 'comment-region-function' and
  18209. ;; 'uncomment-region-function' both point
  18210. ;; to 'org-comment-or-uncomment-region'. Eventually,
  18211. ;; 'org-insert-comment' takes care of insertion of comments at the
  18212. ;; beginning of line.
  18213. ;; 'org-setup-comments-handling' install comments related variables
  18214. ;; during 'org-mode' initialization.
  18215. (defun org-setup-comments-handling ()
  18216. (interactive)
  18217. (setq-local comment-use-syntax nil)
  18218. (setq-local comment-start "# ")
  18219. (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  18220. (setq-local comment-insert-comment-function 'org-insert-comment)
  18221. (setq-local comment-region-function 'org-comment-or-uncomment-region)
  18222. (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  18223. (defun org-insert-comment ()
  18224. "Insert an empty comment above current line.
  18225. If the line is empty, insert comment at its beginning. When
  18226. point is within a source block, comment according to the related
  18227. major mode."
  18228. (if (let ((element (org-element-at-point)))
  18229. (and (eq (org-element-type element) 'src-block)
  18230. (< (save-excursion
  18231. (goto-char (org-element-property :post-affiliated element))
  18232. (line-end-position))
  18233. (point))
  18234. (> (save-excursion
  18235. (goto-char (org-element-property :end element))
  18236. (skip-chars-backward " \r\t\n")
  18237. (line-beginning-position))
  18238. (point))))
  18239. (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  18240. (beginning-of-line)
  18241. (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
  18242. (open-line 1))
  18243. (org-indent-line)
  18244. (insert "# ")))
  18245. (defvar comment-empty-lines) ; From newcomment.el.
  18246. (defun org-comment-or-uncomment-region (beg end &rest _)
  18247. "Comment or uncomment each non-blank line in the region.
  18248. Uncomment each non-blank line between BEG and END if it only
  18249. contains commented lines. Otherwise, comment them. If region is
  18250. strictly within a source block, use appropriate comment syntax."
  18251. (if (let ((element (org-element-at-point)))
  18252. (and (eq (org-element-type element) 'src-block)
  18253. (< (save-excursion
  18254. (goto-char (org-element-property :post-affiliated element))
  18255. (line-end-position))
  18256. beg)
  18257. (>= (save-excursion
  18258. (goto-char (org-element-property :end element))
  18259. (skip-chars-backward " \r\t\n")
  18260. (line-beginning-position))
  18261. end)))
  18262. ;; Translate region boundaries for the Org buffer to the source
  18263. ;; buffer.
  18264. (let ((offset (- end beg)))
  18265. (save-excursion
  18266. (goto-char beg)
  18267. (org-babel-do-in-edit-buffer
  18268. (comment-or-uncomment-region (point) (+ offset (point))))))
  18269. (save-restriction
  18270. ;; Restrict region
  18271. (narrow-to-region (save-excursion (goto-char beg)
  18272. (skip-chars-forward " \r\t\n" end)
  18273. (line-beginning-position))
  18274. (save-excursion (goto-char end)
  18275. (skip-chars-backward " \r\t\n" beg)
  18276. (line-end-position)))
  18277. (let ((uncommentp
  18278. ;; UNCOMMENTP is non-nil when every non blank line between
  18279. ;; BEG and END is a comment.
  18280. (save-excursion
  18281. (goto-char (point-min))
  18282. (while (and (not (eobp))
  18283. (let ((element (org-element-at-point)))
  18284. (and (eq (org-element-type element) 'comment)
  18285. (goto-char (min (point-max)
  18286. (org-element-property
  18287. :end element)))))))
  18288. (eobp))))
  18289. (if uncommentp
  18290. ;; Only blank lines and comments in region: uncomment it.
  18291. (save-excursion
  18292. (goto-char (point-min))
  18293. (while (not (eobp))
  18294. (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  18295. (replace-match "" nil nil nil 1))
  18296. (forward-line)))
  18297. ;; Comment each line in region.
  18298. (let ((min-indent (point-max)))
  18299. ;; First find the minimum indentation across all lines.
  18300. (save-excursion
  18301. (goto-char (point-min))
  18302. (while (and (not (eobp)) (not (zerop min-indent)))
  18303. (unless (looking-at "[ \t]*$")
  18304. (setq min-indent (min min-indent (current-indentation))))
  18305. (forward-line)))
  18306. ;; Then loop over all lines.
  18307. (save-excursion
  18308. (goto-char (point-min))
  18309. (while (not (eobp))
  18310. (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  18311. ;; Don't get fooled by invisible text (e.g. link path)
  18312. ;; when moving to column MIN-INDENT.
  18313. (let ((buffer-invisibility-spec nil))
  18314. (org-move-to-column min-indent t))
  18315. (insert comment-start))
  18316. (forward-line)))))))))
  18317. (defun org-comment-dwim (_arg)
  18318. "Call the comment command you mean.
  18319. Call `org-toggle-comment' if on a heading, otherwise call
  18320. `comment-dwim', within a source edit buffer if needed."
  18321. (interactive "*P")
  18322. (cond ((org-at-heading-p)
  18323. (call-interactively #'org-toggle-comment))
  18324. ((org-in-src-block-p)
  18325. (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  18326. (t (call-interactively #'comment-dwim))))
  18327. ;;; Timestamps API
  18328. ;; This section contains tools to operate on, or create, timestamp
  18329. ;; objects, as returned by, e.g. `org-element-context'.
  18330. (defun org-timestamp-from-string (s)
  18331. "Convert Org timestamp S, as a string, into a timestamp object.
  18332. Return nil if S is not a valid timestamp string."
  18333. (when (org-string-nw-p s)
  18334. (with-temp-buffer
  18335. (save-excursion (insert s))
  18336. (org-element-timestamp-parser))))
  18337. (defun org-timestamp-from-time (time &optional with-time inactive)
  18338. "Convert a time value into a timestamp object.
  18339. TIME is an Emacs internal time representation, as returned, e.g.,
  18340. by `current-time'.
  18341. When optional argument WITH-TIME is non-nil, return a timestamp
  18342. object with a time part, i.e., with hours and minutes.
  18343. Return an inactive timestamp if INACTIVE is non-nil. Otherwise,
  18344. return an active timestamp."
  18345. (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  18346. (org-element-create 'timestamp
  18347. (list :type (if inactive 'inactive 'active)
  18348. :year-start year
  18349. :month-start month
  18350. :day-start day
  18351. :hour-start (and with-time hour)
  18352. :minute-start (and with-time minute)))))
  18353. (defun org-timestamp-to-time (timestamp &optional end)
  18354. "Convert TIMESTAMP object into an Emacs internal time value.
  18355. Use end of date range or time range when END is non-nil.
  18356. Otherwise, use its start."
  18357. (apply #'encode-time 0
  18358. (mapcar
  18359. (lambda (prop) (or (org-element-property prop timestamp) 0))
  18360. (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  18361. '(:minute-start :hour-start :day-start :month-start
  18362. :year-start)))))
  18363. (defun org-timestamp-has-time-p (timestamp)
  18364. "Non-nil when TIMESTAMP has a time specified."
  18365. (org-element-property :hour-start timestamp))
  18366. (defun org-timestamp-format (timestamp format &optional end utc)
  18367. "Format a TIMESTAMP object into a string.
  18368. FORMAT is a format specifier to be passed to
  18369. `format-time-string'.
  18370. When optional argument END is non-nil, use end of date-range or
  18371. time-range, if possible.
  18372. When optional argument UTC is non-nil, time is be expressed as
  18373. Universal Time."
  18374. (format-time-string format (org-timestamp-to-time timestamp end)
  18375. (and utc t)))
  18376. (defun org-timestamp-split-range (timestamp &optional end)
  18377. "Extract a TIMESTAMP object from a date or time range.
  18378. END, when non-nil, means extract the end of the range.
  18379. Otherwise, extract its start.
  18380. Return a new timestamp object."
  18381. (let ((type (org-element-property :type timestamp)))
  18382. (if (memq type '(active inactive diary)) timestamp
  18383. (let ((split-ts (org-element-copy timestamp)))
  18384. ;; Set new type.
  18385. (org-element-put-property
  18386. split-ts :type (if (eq type 'active-range) 'active 'inactive))
  18387. ;; Copy start properties over end properties if END is
  18388. ;; non-nil. Otherwise, copy end properties over `start' ones.
  18389. (let ((p-alist '((:minute-start . :minute-end)
  18390. (:hour-start . :hour-end)
  18391. (:day-start . :day-end)
  18392. (:month-start . :month-end)
  18393. (:year-start . :year-end))))
  18394. (dolist (p-cell p-alist)
  18395. (org-element-put-property
  18396. split-ts
  18397. (funcall (if end #'car #'cdr) p-cell)
  18398. (org-element-property
  18399. (funcall (if end #'cdr #'car) p-cell) split-ts)))
  18400. ;; Eventually refresh `:raw-value'.
  18401. (org-element-put-property split-ts :raw-value nil)
  18402. (org-element-put-property
  18403. split-ts :raw-value (org-element-interpret-data split-ts)))))))
  18404. (defun org-timestamp-translate (timestamp &optional boundary)
  18405. "Translate TIMESTAMP object to custom format.
  18406. Format string is defined in `org-time-stamp-custom-formats',
  18407. which see.
  18408. When optional argument BOUNDARY is non-nil, it is either the
  18409. symbol `start' or `end'. In this case, only translate the
  18410. starting or ending part of TIMESTAMP if it is a date or time
  18411. range. Otherwise, translate both parts.
  18412. Return timestamp as-is if `org-display-custom-times' is nil or if
  18413. it has a `diary' type."
  18414. (let ((type (org-element-property :type timestamp)))
  18415. (if (or (not org-display-custom-times) (eq type 'diary))
  18416. (org-element-interpret-data timestamp)
  18417. (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
  18418. org-time-stamp-custom-formats)))
  18419. (if (and (not boundary) (memq type '(active-range inactive-range)))
  18420. (concat (org-timestamp-format timestamp fmt)
  18421. "--"
  18422. (org-timestamp-format timestamp fmt t))
  18423. (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
  18424. ;;; Other stuff
  18425. (defvar reftex-docstruct-symbol)
  18426. (defvar org--rds)
  18427. (defun org-reftex-citation ()
  18428. "Use `reftex-citation' to insert a citation into the buffer.
  18429. This looks for a line like
  18430. #+BIBLIOGRAPHY: foo plain option:-d
  18431. and derives from it that foo.bib is the bibliography file relevant
  18432. for this document. It then installs the necessary environment for RefTeX
  18433. to work in this buffer and calls `reftex-citation' to insert a citation
  18434. into the buffer.
  18435. Export of such citations to both LaTeX and HTML is handled by the contributed
  18436. package ox-bibtex by Taru Karttunen."
  18437. (interactive)
  18438. (let ((reftex-docstruct-symbol 'org--rds)
  18439. org--rds bib)
  18440. (org-with-wide-buffer
  18441. (let ((case-fold-search t)
  18442. (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  18443. (if (not (save-excursion
  18444. (or (re-search-forward re nil t)
  18445. (re-search-backward re nil t))))
  18446. (user-error "No bibliography defined in file")
  18447. (setq bib (concat (match-string 1) ".bib")
  18448. org--rds (list (list 'bib bib))))))
  18449. (call-interactively 'reftex-citation)))
  18450. ;;;; Functions extending outline functionality
  18451. (defun org-beginning-of-line (&optional n)
  18452. "Go to the beginning of the current visible line.
  18453. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18454. symbol `reversed', on the first attempt move to where the
  18455. headline text starts, and only move to beginning of line when the
  18456. cursor is already before the start of the text of the headline.
  18457. If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  18458. start of the text on the second attempt.
  18459. With argument N not nil or 1, move forward N - 1 lines first."
  18460. (interactive "^p")
  18461. (let ((origin (point))
  18462. (special (pcase org-special-ctrl-a/e
  18463. (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  18464. deactivate-mark)
  18465. ;; First move to a visible line.
  18466. (if (bound-and-true-p visual-line-mode)
  18467. (beginning-of-visual-line n)
  18468. (move-beginning-of-line n)
  18469. ;; `move-beginning-of-line' may leave point after invisible
  18470. ;; characters if line starts with such of these (e.g., with
  18471. ;; a link at column 0). Really move to the beginning of the
  18472. ;; current visible line.
  18473. (beginning-of-line))
  18474. (cond
  18475. ;; No special behavior. Point is already at the beginning of
  18476. ;; a line, logical or visual.
  18477. ((not special))
  18478. ;; `beginning-of-visual-line' left point before logical beginning
  18479. ;; of line: point is at the beginning of a visual line. Bail
  18480. ;; out.
  18481. ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  18482. ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  18483. ;; At a headline, special position is before the title, but
  18484. ;; after any TODO keyword or priority cookie.
  18485. (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  18486. (line-end-position)))
  18487. (bol (point)))
  18488. (if (eq special 'reversed)
  18489. (when (and (= origin bol) (eq last-command this-command))
  18490. (goto-char refpos))
  18491. (when (or (> origin refpos) (= origin bol))
  18492. (goto-char refpos)))))
  18493. ((and (looking-at org-list-full-item-re)
  18494. (memq (org-element-type (save-match-data (org-element-at-point)))
  18495. '(item plain-list)))
  18496. ;; Set special position at first white space character after
  18497. ;; bullet, and check-box, if any.
  18498. (let ((after-bullet
  18499. (let ((box (match-end 3)))
  18500. (cond ((not box) (match-end 1))
  18501. ((eq (char-after box) ?\s) (1+ box))
  18502. (t box)))))
  18503. (if (eq special 'reversed)
  18504. (when (and (= (point) origin) (eq last-command this-command))
  18505. (goto-char after-bullet))
  18506. (when (or (> origin after-bullet) (= (point) origin))
  18507. (goto-char after-bullet)))))
  18508. ;; No special context. Point is already at beginning of line.
  18509. (t nil))))
  18510. (defun org-end-of-line (&optional n)
  18511. "Go to the end of the line, but before ellipsis, if any.
  18512. If this is a headline, and `org-special-ctrl-a/e' is not nil or
  18513. symbol `reversed', ignore tags on the first attempt, and only
  18514. move to after the tags when the cursor is already beyond the end
  18515. of the headline.
  18516. If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  18517. on the second attempt.
  18518. With argument N not nil or 1, move forward N - 1 lines first."
  18519. (interactive "^p")
  18520. (let ((origin (point))
  18521. (special (pcase org-special-ctrl-a/e
  18522. (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  18523. deactivate-mark)
  18524. ;; First move to a visible line.
  18525. (if (bound-and-true-p visual-line-mode)
  18526. (beginning-of-visual-line n)
  18527. (move-beginning-of-line n))
  18528. (cond
  18529. ;; At a headline, with tags.
  18530. ((and special
  18531. (save-excursion
  18532. (beginning-of-line)
  18533. (let ((case-fold-search nil))
  18534. (looking-at org-complex-heading-regexp)))
  18535. (match-end 5))
  18536. (let ((tags (save-excursion
  18537. (goto-char (match-beginning 5))
  18538. (skip-chars-backward " \t")
  18539. (point)))
  18540. (visual-end (and (bound-and-true-p visual-line-mode)
  18541. (save-excursion
  18542. (end-of-visual-line)
  18543. (point)))))
  18544. ;; If `end-of-visual-line' brings us before end of line or
  18545. ;; even tags, i.e., the headline spans over multiple visual
  18546. ;; lines, move there.
  18547. (cond ((and visual-end
  18548. (< visual-end tags)
  18549. (<= origin visual-end))
  18550. (goto-char visual-end))
  18551. ((eq special 'reversed)
  18552. (if (and (= origin (line-end-position))
  18553. (eq this-command last-command))
  18554. (goto-char tags)
  18555. (end-of-line)))
  18556. (t
  18557. (if (or (< origin tags) (= origin (line-end-position)))
  18558. (goto-char tags)
  18559. (end-of-line))))))
  18560. ((bound-and-true-p visual-line-mode)
  18561. (let ((bol (line-beginning-position)))
  18562. (end-of-visual-line)
  18563. ;; If `end-of-visual-line' gets us past the ellipsis at the
  18564. ;; end of a line, backtrack and use `end-of-line' instead.
  18565. (when (/= bol (line-beginning-position))
  18566. (goto-char bol)
  18567. (end-of-line))))
  18568. (t (end-of-line)))))
  18569. (defun org-backward-sentence (&optional _arg)
  18570. "Go to beginning of sentence, or beginning of table field.
  18571. This will call `backward-sentence' or `org-table-beginning-of-field',
  18572. depending on context."
  18573. (interactive)
  18574. (let* ((element (org-element-at-point))
  18575. (contents-begin (org-element-property :contents-begin element))
  18576. (table (org-element-lineage element '(table) t)))
  18577. (if (and table
  18578. (> (point) contents-begin)
  18579. (<= (point) (org-element-property :contents-end table)))
  18580. (call-interactively #'org-table-beginning-of-field)
  18581. (save-restriction
  18582. (when (and contents-begin
  18583. (< (point-min) contents-begin)
  18584. (> (point) contents-begin))
  18585. (narrow-to-region contents-begin
  18586. (org-element-property :contents-end element)))
  18587. (call-interactively #'backward-sentence)))))
  18588. (defun org-forward-sentence (&optional _arg)
  18589. "Go to end of sentence, or end of table field.
  18590. This will call `forward-sentence' or `org-table-end-of-field',
  18591. depending on context."
  18592. (interactive)
  18593. (if (and (org-at-heading-p)
  18594. (save-restriction (skip-chars-forward " \t") (not (eolp))))
  18595. (save-restriction
  18596. (narrow-to-region (line-beginning-position) (line-end-position))
  18597. (call-interactively #'forward-sentence))
  18598. (let* ((element (org-element-at-point))
  18599. (contents-end (org-element-property :contents-end element))
  18600. (table (org-element-lineage element '(table) t)))
  18601. (if (and table
  18602. (>= (point) (org-element-property :contents-begin table))
  18603. (< (point) contents-end))
  18604. (call-interactively #'org-table-end-of-field)
  18605. (save-restriction
  18606. (when (and contents-end
  18607. (> (point-max) contents-end)
  18608. ;; Skip blank lines between elements.
  18609. (< (org-element-property :end element)
  18610. (save-excursion (goto-char contents-end)
  18611. (skip-chars-forward " \r\t\n"))))
  18612. (narrow-to-region (org-element-property :contents-begin element)
  18613. contents-end))
  18614. ;; End of heading is considered as the end of a sentence.
  18615. (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  18616. (call-interactively #'forward-sentence)))))))
  18617. (defun org-kill-line (&optional _arg)
  18618. "Kill line, to tags or end of line."
  18619. (interactive)
  18620. (cond
  18621. ((or (not org-special-ctrl-k)
  18622. (bolp)
  18623. (not (org-at-heading-p)))
  18624. (when (and (get-char-property (line-end-position) 'invisible)
  18625. org-ctrl-k-protect-subtree
  18626. (or (eq org-ctrl-k-protect-subtree 'error)
  18627. (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  18628. (user-error
  18629. (substitute-command-keys
  18630. "`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  18631. (call-interactively
  18632. (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  18633. ((org-match-line org-tag-line-re)
  18634. (let ((end (save-excursion
  18635. (goto-char (match-beginning 1))
  18636. (skip-chars-backward " \t")
  18637. (point))))
  18638. (if (<= end (point)) ;on tags part
  18639. (kill-region (point) (line-end-position))
  18640. (kill-region (point) end)))
  18641. ;; Only align tags when we are still on a heading:
  18642. (if (org-at-heading-p) (org-align-tags)))
  18643. (t (kill-region (point) (line-end-position)))))
  18644. (defun org-yank (&optional arg)
  18645. "Yank. If the kill is a subtree, treat it specially.
  18646. This command will look at the current kill and check if is a single
  18647. subtree, or a series of subtrees[1]. If it passes the test, and if the
  18648. cursor is at the beginning of a line or after the stars of a currently
  18649. empty headline, then the yank is handled specially. How exactly depends
  18650. on the value of the following variables.
  18651. `org-yank-folded-subtrees'
  18652. By default, this variable is non-nil, which results in
  18653. subtree(s) being folded after insertion, except if doing so
  18654. would swallow text after the yanked text.
  18655. `org-yank-adjusted-subtrees'
  18656. When non-nil (the default value is nil), the subtree will be
  18657. promoted or demoted in order to fit into the local outline tree
  18658. structure, which means that the level will be adjusted so that it
  18659. becomes the smaller one of the two *visible* surrounding headings.
  18660. Any prefix to this command will cause `yank' to be called directly with
  18661. no special treatment. In particular, a simple `\\[universal-argument]' prefix \
  18662. will just
  18663. plainly yank the text as it is.
  18664. \[1] The test checks if the first non-white line is a heading
  18665. and if there are no other headings with fewer stars."
  18666. (interactive "P")
  18667. (org-yank-generic 'yank arg))
  18668. (defun org-yank-generic (command arg)
  18669. "Perform some yank-like command.
  18670. This function implements the behavior described in the `org-yank'
  18671. documentation. However, it has been generalized to work for any
  18672. interactive command with similar behavior."
  18673. ;; pretend to be command COMMAND
  18674. (setq this-command command)
  18675. (if arg
  18676. (call-interactively command)
  18677. (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  18678. (and (org-kill-is-subtree-p)
  18679. (or (bolp)
  18680. (and (looking-at "[ \t]*$")
  18681. (string-match
  18682. "\\`\\*+\\'"
  18683. (buffer-substring (point-at-bol) (point)))))))
  18684. swallowp)
  18685. (cond
  18686. ((and subtreep org-yank-folded-subtrees)
  18687. (let ((beg (point))
  18688. end)
  18689. (if (and subtreep org-yank-adjusted-subtrees)
  18690. (org-paste-subtree nil nil 'for-yank)
  18691. (call-interactively command))
  18692. (setq end (point))
  18693. (goto-char beg)
  18694. (when (and (bolp) subtreep
  18695. (not (setq swallowp
  18696. (org-yank-folding-would-swallow-text beg end))))
  18697. (org-with-limited-levels
  18698. (or (looking-at org-outline-regexp)
  18699. (re-search-forward org-outline-regexp-bol end t))
  18700. (while (and (< (point) end) (looking-at org-outline-regexp))
  18701. (org-flag-subtree t)
  18702. (org-cycle-show-empty-lines 'folded)
  18703. (condition-case nil
  18704. (outline-forward-same-level 1)
  18705. (error (goto-char end))))))
  18706. (when swallowp
  18707. (message
  18708. "Inserted text not folded because that would swallow text"))
  18709. (goto-char end)
  18710. (skip-chars-forward " \t\n\r")
  18711. (beginning-of-line 1)
  18712. (push-mark beg 'nomsg)))
  18713. ((and subtreep org-yank-adjusted-subtrees)
  18714. (let ((beg (point-at-bol)))
  18715. (org-paste-subtree nil nil 'for-yank)
  18716. (push-mark beg 'nomsg)))
  18717. (t
  18718. (call-interactively command))))))
  18719. (defun org-yank-folding-would-swallow-text (beg end)
  18720. "Would `hide-subtree' at BEG swallow any text after END?"
  18721. (let (level)
  18722. (org-with-limited-levels
  18723. (save-excursion
  18724. (goto-char beg)
  18725. (when (or (looking-at org-outline-regexp)
  18726. (re-search-forward org-outline-regexp-bol end t))
  18727. (setq level (org-outline-level)))
  18728. (goto-char end)
  18729. (skip-chars-forward " \t\r\n\v\f")
  18730. (not (or (eobp)
  18731. (and (bolp) (looking-at-p org-outline-regexp)
  18732. (<= (org-outline-level) level))))))))
  18733. (defun org-back-to-heading (&optional invisible-ok)
  18734. "Call `outline-back-to-heading', but provide a better error message."
  18735. (condition-case nil
  18736. (outline-back-to-heading invisible-ok)
  18737. (error
  18738. (user-error "Before first headline at position %d in buffer %s"
  18739. (point) (current-buffer)))))
  18740. (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  18741. "Go back to heading or first point in buffer.
  18742. If point is before first heading go to first point in buffer
  18743. instead of back to heading."
  18744. (condition-case nil
  18745. (outline-back-to-heading invisible-ok)
  18746. (error
  18747. (goto-char (point-min)))))
  18748. (defun org-before-first-heading-p ()
  18749. "Before first heading?"
  18750. (org-with-limited-levels
  18751. (save-excursion
  18752. (end-of-line)
  18753. (null (re-search-backward org-outline-regexp-bol nil t)))))
  18754. (defun org-at-heading-p (&optional _)
  18755. "Non-nil when on a headline."
  18756. (outline-on-heading-p t))
  18757. (defun org-in-commented-heading-p (&optional no-inheritance)
  18758. "Non-nil if point is under a commented heading.
  18759. This function also checks ancestors of the current headline,
  18760. unless optional argument NO-INHERITANCE is non-nil."
  18761. (cond
  18762. ((org-before-first-heading-p) nil)
  18763. ((let ((headline (nth 4 (org-heading-components))))
  18764. (and headline
  18765. (let ((case-fold-search nil))
  18766. (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
  18767. headline)))))
  18768. (no-inheritance nil)
  18769. (t
  18770. (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
  18771. (defun org-in-archived-heading-p (&optional no-inheritance)
  18772. "Non-nil if point is under an archived heading.
  18773. This function also checks ancestors of the current headline,
  18774. unless optional argument NO-INHERITANCE is non-nil."
  18775. (cond
  18776. ((org-before-first-heading-p) nil)
  18777. ((let ((tags (org-get-tags nil 'local)))
  18778. (and tags
  18779. (cl-some (apply-partially #'string= org-archive-tag) tags))))
  18780. (no-inheritance nil)
  18781. (t
  18782. (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p))))))
  18783. (defun org-at-comment-p nil
  18784. "Return t if cursor is in a commented line."
  18785. (save-excursion
  18786. (save-match-data
  18787. (beginning-of-line)
  18788. (looking-at org-comment-regexp))))
  18789. (defun org-at-keyword-p nil
  18790. "Return t if cursor is at a keyword-line."
  18791. (save-excursion
  18792. (move-beginning-of-line 1)
  18793. (looking-at org-keyword-regexp)))
  18794. (defun org-at-drawer-p nil
  18795. "Return t if cursor is at a drawer keyword."
  18796. (save-excursion
  18797. (move-beginning-of-line 1)
  18798. (looking-at org-drawer-regexp)))
  18799. (defun org-at-block-p nil
  18800. "Return t if cursor is at a block keyword."
  18801. (save-excursion
  18802. (move-beginning-of-line 1)
  18803. (looking-at org-block-regexp)))
  18804. (defun org-point-at-end-of-empty-headline ()
  18805. "If point is at the end of an empty headline, return t, else nil.
  18806. If the heading only contains a TODO keyword, it is still considered
  18807. empty."
  18808. (let ((case-fold-search nil))
  18809. (and (looking-at "[ \t]*$")
  18810. org-todo-line-regexp
  18811. (save-excursion
  18812. (beginning-of-line)
  18813. (looking-at org-todo-line-regexp)
  18814. (string= (match-string 3) "")))))
  18815. (defun org-at-heading-or-item-p ()
  18816. (or (org-at-heading-p) (org-at-item-p)))
  18817. (defun org-up-heading-all (arg)
  18818. "Move to the heading line of which the present line is a subheading.
  18819. This function considers both visible and invisible heading lines.
  18820. With argument, move up ARG levels."
  18821. (outline-up-heading arg t))
  18822. (defvar-local org--up-heading-cache nil
  18823. "Buffer-local `org-up-heading-safe' cache.")
  18824. (defvar-local org--up-heading-cache-tick nil
  18825. "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  18826. (defun org-up-heading-safe ()
  18827. "Move to the heading line of which the present line is a subheading.
  18828. This version will not throw an error. It will return the level of the
  18829. headline found, or nil if no higher level is found.
  18830. Also, this function will be a lot faster than `outline-up-heading',
  18831. because it relies on stars being the outline starters. This can really
  18832. make a significant difference in outlines with very many siblings."
  18833. (when (ignore-errors (org-back-to-heading t))
  18834. (let (level-cache)
  18835. (unless org--up-heading-cache
  18836. (setq org--up-heading-cache (make-hash-table)))
  18837. (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18838. (setq level-cache (gethash (point) org--up-heading-cache)))
  18839. (when (<= (point-min) (car level-cache) (point-max))
  18840. ;; Parent is inside accessible part of the buffer.
  18841. (progn (goto-char (car level-cache))
  18842. (cdr level-cache)))
  18843. ;; Buffer modified. Invalidate cache.
  18844. (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  18845. (setq-local org--up-heading-cache-tick
  18846. (buffer-chars-modified-tick))
  18847. (clrhash org--up-heading-cache))
  18848. (let* ((level-up (1- (funcall outline-level)))
  18849. (pos (point))
  18850. (result (and (> level-up 0)
  18851. (re-search-backward
  18852. (format "^\\*\\{1,%d\\} " level-up) nil t)
  18853. (funcall outline-level))))
  18854. (when result (puthash pos (cons (point) result) org--up-heading-cache))
  18855. result)))))
  18856. (defun org-up-heading-or-point-min ()
  18857. "Move to the heading line of which the present is a subheading, or point-min.
  18858. This version is needed to make point-min behave like a virtual
  18859. heading of level 0 for property-inheritance. It will return the
  18860. level of the headline found (down to 0) or nil if already at a
  18861. point before the first headline or at point-min."
  18862. (when (ignore-errors (org-back-to-heading t))
  18863. (if (< 1 (funcall outline-level))
  18864. (org-up-heading-safe)
  18865. (unless (= (point) (point-min)) (goto-char (point-min))))))
  18866. (defun org-first-sibling-p ()
  18867. "Is this heading the first child of its parents?"
  18868. (interactive)
  18869. (let ((re org-outline-regexp-bol)
  18870. level l)
  18871. (unless (org-at-heading-p t)
  18872. (user-error "Not at a heading"))
  18873. (setq level (funcall outline-level))
  18874. (save-excursion
  18875. (if (not (re-search-backward re nil t))
  18876. t
  18877. (setq l (funcall outline-level))
  18878. (< l level)))))
  18879. (defun org-goto-sibling (&optional previous)
  18880. "Goto the next sibling, even if it is invisible.
  18881. When PREVIOUS is set, go to the previous sibling instead. Returns t
  18882. when a sibling was found. When none is found, return nil and don't
  18883. move point."
  18884. (let ((fun (if previous 're-search-backward 're-search-forward))
  18885. (pos (point))
  18886. (re org-outline-regexp-bol)
  18887. level l)
  18888. (when (ignore-errors (org-back-to-heading t))
  18889. (setq level (funcall outline-level))
  18890. (catch 'exit
  18891. (or previous (forward-char 1))
  18892. (while (funcall fun re nil t)
  18893. (setq l (funcall outline-level))
  18894. (when (< l level) (goto-char pos) (throw 'exit nil))
  18895. (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  18896. (goto-char pos)
  18897. nil))))
  18898. (defun org-show-siblings ()
  18899. "Show all siblings of the current headline."
  18900. (save-excursion
  18901. (while (org-goto-sibling) (org-flag-heading nil)))
  18902. (save-excursion
  18903. (while (org-goto-sibling 'previous)
  18904. (org-flag-heading nil))))
  18905. (defun org-goto-first-child ()
  18906. "Goto the first child, even if it is invisible.
  18907. Return t when a child was found. Otherwise don't move point and
  18908. return nil."
  18909. (let (level (pos (point)) (re org-outline-regexp-bol))
  18910. (when (org-back-to-heading-or-point-min t)
  18911. (setq level (org-outline-level))
  18912. (forward-char 1)
  18913. (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  18914. (progn (goto-char (match-beginning 0)) t)
  18915. (goto-char pos) nil))))
  18916. (defun org-show-hidden-entry ()
  18917. "Show an entry where even the heading is hidden."
  18918. (save-excursion
  18919. (org-show-entry)))
  18920. (defun org-flag-heading (flag &optional entry)
  18921. "Flag the current heading. FLAG non-nil means make invisible.
  18922. When ENTRY is non-nil, show the entire entry."
  18923. (save-excursion
  18924. (org-back-to-heading t)
  18925. ;; Check if we should show the entire entry
  18926. (if (not entry)
  18927. (org-flag-region
  18928. (line-end-position 0) (line-end-position) flag 'outline)
  18929. (org-show-entry)
  18930. (save-excursion
  18931. (and (outline-next-heading)
  18932. (org-flag-heading nil))))))
  18933. (defun org-get-next-sibling ()
  18934. "Move to next heading of the same level, and return point.
  18935. If there is no such heading, return nil.
  18936. This is like outline-next-sibling, but invisible headings are ok."
  18937. (let ((level (funcall outline-level)))
  18938. (outline-next-heading)
  18939. (while (and (not (eobp)) (> (funcall outline-level) level))
  18940. (outline-next-heading))
  18941. (unless (or (eobp) (< (funcall outline-level) level))
  18942. (point))))
  18943. (defun org-get-previous-sibling ()
  18944. "Move to previous heading of the same level, and return point.
  18945. If there is no such heading, return nil."
  18946. (let ((opoint (point))
  18947. (level (funcall outline-level)))
  18948. (outline-previous-heading)
  18949. (when (and (/= (point) opoint) (outline-on-heading-p t))
  18950. (while (and (> (funcall outline-level) level)
  18951. (not (bobp)))
  18952. (outline-previous-heading))
  18953. (unless (< (funcall outline-level) level)
  18954. (point)))))
  18955. (defun org-end-of-subtree (&optional invisible-ok to-heading)
  18956. "Goto to the end of a subtree."
  18957. ;; This contains an exact copy of the original function, but it uses
  18958. ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  18959. ;; trees and before first headline. And is uses an invisible-ok argument.
  18960. ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  18961. ;; Furthermore, when used inside Org, finding the end of a large subtree
  18962. ;; with many children and grandchildren etc, this can be much faster
  18963. ;; than the outline version.
  18964. (org-back-to-heading-or-point-min invisible-ok)
  18965. (let ((first t)
  18966. (level (funcall outline-level)))
  18967. (cond ((= level 0)
  18968. (goto-char (point-max)))
  18969. ((and (derived-mode-p 'org-mode) (< level 1000))
  18970. ;; A true heading (not a plain list item), in Org
  18971. ;; This means we can easily find the end by looking
  18972. ;; only for the right number of stars. Using a regexp to do
  18973. ;; this is so much faster than using a Lisp loop.
  18974. (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  18975. (forward-char 1)
  18976. (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  18977. (t
  18978. ;; something else, do it the slow way
  18979. (while (and (not (eobp))
  18980. (or first (> (funcall outline-level) level)))
  18981. (setq first nil)
  18982. (outline-next-heading))))
  18983. (unless to-heading
  18984. (when (memq (preceding-char) '(?\n ?\^M))
  18985. ;; Go to end of line before heading
  18986. (forward-char -1)
  18987. (when (memq (preceding-char) '(?\n ?\^M))
  18988. ;; leave blank line before heading
  18989. (forward-char -1)))))
  18990. (point))
  18991. (defun org-end-of-meta-data (&optional full)
  18992. "Skip planning line and properties drawer in current entry.
  18993. When optional argument FULL is t, also skip planning information,
  18994. clocking lines and any kind of drawer.
  18995. When FULL is non-nil but not t, skip planning information,
  18996. properties, clocking lines and logbook drawers."
  18997. (org-back-to-heading t)
  18998. (forward-line)
  18999. ;; Skip planning information.
  19000. (when (looking-at-p org-planning-line-re) (forward-line))
  19001. ;; Skip property drawer.
  19002. (when (looking-at org-property-drawer-re)
  19003. (goto-char (match-end 0))
  19004. (forward-line))
  19005. ;; When FULL is not nil, skip more.
  19006. (when (and full (not (org-at-heading-p)))
  19007. (catch 'exit
  19008. (let ((end (save-excursion (outline-next-heading) (point)))
  19009. (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  19010. (while (not (eobp))
  19011. (cond ;; Skip clock lines.
  19012. ((looking-at-p re) (forward-line))
  19013. ;; Skip logbook drawer.
  19014. ((looking-at-p org-logbook-drawer-re)
  19015. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19016. (forward-line)
  19017. (throw 'exit t)))
  19018. ;; When FULL is t, skip regular drawer too.
  19019. ((and (eq full t) (looking-at-p org-drawer-regexp))
  19020. (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  19021. (forward-line)
  19022. (throw 'exit t)))
  19023. (t (throw 'exit t))))))))
  19024. (defun org--line-fully-invisible-p ()
  19025. "Return non-nil if the current line is fully invisible."
  19026. (let ((line-beg (line-beginning-position))
  19027. (line-pos (1- (line-end-position)))
  19028. (is-invisible t))
  19029. (while (and (< line-beg line-pos) is-invisible)
  19030. (setq is-invisible (org-invisible-p line-pos))
  19031. (setq line-pos (1- line-pos)))
  19032. is-invisible))
  19033. (defun org-forward-heading-same-level (arg &optional invisible-ok)
  19034. "Move forward to the ARG'th subheading at same level as this one.
  19035. Stop at the first and last subheadings of a superior heading.
  19036. Normally this only looks at visible headings, but when INVISIBLE-OK is
  19037. non-nil it will also look at invisible ones."
  19038. (interactive "p")
  19039. (let ((backward? (and arg (< arg 0))))
  19040. (if (org-before-first-heading-p)
  19041. (if backward? (goto-char (point-min)) (outline-next-heading))
  19042. (org-back-to-heading invisible-ok)
  19043. (unless backward? (end-of-line)) ;do not match current headline
  19044. (let ((level (- (match-end 0) (match-beginning 0) 1))
  19045. (f (if backward? #'re-search-backward #'re-search-forward))
  19046. (count (if arg (abs arg) 1))
  19047. (result (point)))
  19048. (while (and (> count 0)
  19049. (funcall f org-outline-regexp-bol nil 'move))
  19050. (let ((l (- (match-end 0) (match-beginning 0) 1)))
  19051. (cond ((< l level) (setq count 0))
  19052. ((and (= l level)
  19053. (or invisible-ok
  19054. ;; FIXME: See commit a700fadd72 and the
  19055. ;; related discussion on why using
  19056. ;; `org--line-fully-invisible-p' is needed
  19057. ;; here, which is to serve the needs of an
  19058. ;; external package. If the change is
  19059. ;; wrong regarding Org itself, it should
  19060. ;; be removed.
  19061. (not (org--line-fully-invisible-p))))
  19062. (cl-decf count)
  19063. (when (= l level) (setq result (point)))))))
  19064. (goto-char result))
  19065. (beginning-of-line))))
  19066. (defun org-backward-heading-same-level (arg &optional invisible-ok)
  19067. "Move backward to the ARG'th subheading at same level as this one.
  19068. Stop at the first and last subheadings of a superior heading."
  19069. (interactive "p")
  19070. (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  19071. (defun org-next-visible-heading (arg)
  19072. "Move to the next visible heading line.
  19073. With ARG, repeats or can move backward if negative."
  19074. (interactive "p")
  19075. (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  19076. (if (< arg 0)
  19077. (beginning-of-line)
  19078. (end-of-line))
  19079. (while (and (< arg 0) (re-search-backward regexp nil :move))
  19080. (unless (bobp)
  19081. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19082. (`(outline . ,o)
  19083. (goto-char (overlay-start o))
  19084. (re-search-backward regexp nil :move))
  19085. (_ nil))))
  19086. (cl-incf arg))
  19087. (while (and (> arg 0) (re-search-forward regexp nil t))
  19088. (while (pcase (get-char-property-and-overlay (point) 'invisible)
  19089. (`(outline . ,o)
  19090. (goto-char (overlay-end o))
  19091. (re-search-forward regexp nil :move))
  19092. (_
  19093. (end-of-line)
  19094. nil))) ;leave the loop
  19095. (cl-decf arg))
  19096. (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  19097. (defun org-previous-visible-heading (arg)
  19098. "Move to the previous visible heading.
  19099. With ARG, repeats or can move forward if negative."
  19100. (interactive "p")
  19101. (org-next-visible-heading (- arg)))
  19102. (defun org-forward-paragraph (&optional arg)
  19103. "Move forward by a paragraph, or equivalent, unit.
  19104. With argument ARG, do it ARG times;
  19105. a negative argument ARG = -N means move backward N paragraphs.
  19106. The function moves point between two structural
  19107. elements (paragraphs, tables, lists, etc.).
  19108. It also provides the following special moves for convenience:
  19109. - on a table or a property drawer, move to its beginning;
  19110. - on comment, example, export, source and verse blocks, stop
  19111. at blank lines;
  19112. - skip consecutive clocks, diary S-exps, and keywords."
  19113. (interactive "^p")
  19114. (unless arg (setq arg 1))
  19115. (if (< arg 0) (org-backward-paragraph (- arg))
  19116. (while (and (> arg 0) (not (eobp)))
  19117. (org--forward-paragraph-once)
  19118. (cl-decf arg))
  19119. ;; Return moves left.
  19120. arg))
  19121. (defun org-backward-paragraph (&optional arg)
  19122. "Move backward by a paragraph, or equivalent, unit.
  19123. With argument ARG, do it ARG times;
  19124. a negative argument ARG = -N means move forward N paragraphs.
  19125. The function moves point between two structural
  19126. elements (paragraphs, tables, lists, etc.).
  19127. It also provides the following special moves for convenience:
  19128. - on a table or a property drawer, move to its beginning;
  19129. - on comment, example, export, source and verse blocks, stop
  19130. at blank lines;
  19131. - skip consecutive clocks, diary S-exps, and keywords."
  19132. (interactive "^p")
  19133. (unless arg (setq arg 1))
  19134. (if (< arg 0) (org-forward-paragraph (- arg))
  19135. (while (and (> arg 0) (not (bobp)))
  19136. (org--backward-paragraph-once)
  19137. (cl-decf arg))
  19138. ;; Return moves left.
  19139. arg))
  19140. (defun org--paragraph-at-point ()
  19141. "Return paragraph, or equivalent, element at point.
  19142. Paragraph element at point is the element at point, with the
  19143. following special cases:
  19144. - treat table rows (resp. node properties) as the table
  19145. \(resp. property drawer) containing them.
  19146. - treat plain lists with an item every line as a whole.
  19147. - treat consecutive keywords, clocks, and diary-sexps as a single
  19148. block.
  19149. Function may return a real element, or a pseudo-element with type
  19150. `pseudo-paragraph'."
  19151. (let* ((e (org-element-at-point))
  19152. (type (org-element-type e))
  19153. ;; If we need to fake a new pseudo-element, triplet is
  19154. ;;
  19155. ;; (BEG END PARENT)
  19156. ;;
  19157. ;; where BEG and END are element boundaries, and PARENT the
  19158. ;; element containing it, or nil.
  19159. (triplet
  19160. (cond
  19161. ((memq type '(table property-drawer))
  19162. (list (org-element-property :begin e)
  19163. (org-element-property :end e)
  19164. (org-element-property :parent e)))
  19165. ((memq type '(node-property table-row))
  19166. (let ((e (org-element-property :parent e)))
  19167. (list (org-element-property :begin e)
  19168. (org-element-property :end e)
  19169. (org-element-property :parent e))))
  19170. ((memq type '(clock diary-sexp keyword))
  19171. (let* ((regexp (pcase type
  19172. (`clock org-clock-line-re)
  19173. (`diary-sexp "%%(")
  19174. (_ org-keyword-regexp)))
  19175. (end (if (< 0 (org-element-property :post-blank e))
  19176. (org-element-property :end e)
  19177. (org-with-wide-buffer
  19178. (forward-line)
  19179. (while (looking-at regexp) (forward-line))
  19180. (skip-chars-forward " \t\n")
  19181. (line-beginning-position))))
  19182. (begin (org-with-point-at (org-element-property :begin e)
  19183. (while (and (not (bobp)) (looking-at regexp))
  19184. (forward-line -1))
  19185. ;; We may have gotten one line too far.
  19186. (if (looking-at regexp)
  19187. (point)
  19188. (line-beginning-position 2)))))
  19189. (list begin end (org-element-property :parent e))))
  19190. ;; Find the full plain list containing point, the check it
  19191. ;; contains exactly one line per item.
  19192. ((let ((l (org-element-lineage e '(plain-list) t)))
  19193. (while (memq (org-element-type (org-element-property :parent l))
  19194. '(item plain-list))
  19195. (setq l (org-element-property :parent l)))
  19196. (and l
  19197. (org-with-point-at (org-element-property :post-affiliated l)
  19198. (forward-line (length (org-element-property :structure l)))
  19199. (= (point) (org-element-property :contents-end l)))
  19200. ;; Return value.
  19201. (list (org-element-property :begin l)
  19202. (org-element-property :end l)
  19203. (org-element-property :parent l)))))
  19204. (t nil)))) ;no triplet: return element
  19205. (pcase triplet
  19206. (`(,b ,e ,p)
  19207. (org-element-create
  19208. 'pseudo-paragraph
  19209. (list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  19210. (_ e))))
  19211. (defun org--forward-paragraph-once ()
  19212. "Move forward to end of paragraph or equivalent, once.
  19213. See `org-forward-paragraph'."
  19214. (interactive)
  19215. (save-restriction
  19216. (widen)
  19217. (skip-chars-forward " \t\n")
  19218. (cond
  19219. ((eobp) nil)
  19220. ;; When inside a folded part, move out of it.
  19221. ((pcase (get-char-property-and-overlay (point) 'invisible)
  19222. (`(,(or `outline `org-hide-block) . ,o)
  19223. (goto-char (overlay-end o))
  19224. (forward-line)
  19225. t)
  19226. (_ nil)))
  19227. (t
  19228. (let* ((element (org--paragraph-at-point))
  19229. (type (org-element-type element))
  19230. (contents-begin (org-element-property :contents-begin element))
  19231. (end (org-element-property :end element))
  19232. (post-affiliated (org-element-property :post-affiliated element)))
  19233. (cond
  19234. ((eq type 'plain-list)
  19235. (forward-char)
  19236. (org--forward-paragraph-once))
  19237. ;; If the element is folded, skip it altogether.
  19238. ((pcase (org-with-point-at post-affiliated
  19239. (get-char-property-and-overlay (line-end-position)
  19240. 'invisible))
  19241. (`(,(or `outline `org-hide-block) . ,o)
  19242. (goto-char (overlay-end o))
  19243. (forward-line)
  19244. t)
  19245. (_ nil)))
  19246. ;; At a greater element, move inside.
  19247. ((and contents-begin
  19248. (> contents-begin (point))
  19249. (not (eq type 'paragraph)))
  19250. (goto-char contents-begin)
  19251. ;; Items and footnote definitions contents may not start at
  19252. ;; the beginning of the line. In this case, skip until the
  19253. ;; next paragraph.
  19254. (cond
  19255. ((not (bolp)) (org--forward-paragraph-once))
  19256. ((org-previous-line-empty-p) (forward-line -1))
  19257. (t nil)))
  19258. ;; Move between empty lines in some blocks.
  19259. ((memq type '(comment-block example-block export-block src-block
  19260. verse-block))
  19261. (let ((contents-start
  19262. (org-with-point-at post-affiliated
  19263. (line-beginning-position 2))))
  19264. (if (< (point) contents-start)
  19265. (goto-char contents-start)
  19266. (let ((contents-end
  19267. (org-with-point-at end
  19268. (skip-chars-backward " \t\n")
  19269. (line-beginning-position))))
  19270. (cond
  19271. ((>= (point) contents-end)
  19272. (goto-char end)
  19273. (skip-chars-backward " \t\n")
  19274. (forward-line))
  19275. ((re-search-forward "^[ \t]*\n" contents-end :move)
  19276. (forward-line -1))
  19277. (t nil))))))
  19278. (t
  19279. ;; Move to element's end.
  19280. (goto-char end)
  19281. (skip-chars-backward " \t\n")
  19282. (forward-line))))))))
  19283. (defun org--backward-paragraph-once ()
  19284. "Move backward to start of paragraph or equivalent, once.
  19285. See `org-backward-paragraph'."
  19286. (interactive)
  19287. (save-restriction
  19288. (widen)
  19289. (cond
  19290. ((bobp) nil)
  19291. ;; Blank lines at the beginning of the buffer.
  19292. ((and (org-match-line "^[ \t]*$")
  19293. (save-excursion (skip-chars-backward " \t\n") (bobp)))
  19294. (goto-char (point-min)))
  19295. ;; When inside a folded part, move out of it.
  19296. ((pcase (get-char-property-and-overlay (1- (point)) 'invisible)
  19297. (`(,(or `outline `org-hide-block) . ,o)
  19298. (goto-char (1- (overlay-start o)))
  19299. (org--backward-paragraph-once)
  19300. t)
  19301. (_ nil)))
  19302. (t
  19303. (let* ((element (org--paragraph-at-point))
  19304. (type (org-element-type element))
  19305. (begin (org-element-property :begin element))
  19306. (post-affiliated (org-element-property :post-affiliated element))
  19307. (contents-end (org-element-property :contents-end element))
  19308. (end (org-element-property :end element))
  19309. (parent (org-element-property :parent element))
  19310. (reach
  19311. ;; Move to the visible empty line above position P, or
  19312. ;; to position P. Return t.
  19313. (lambda (p)
  19314. (goto-char p)
  19315. (when (and (org-previous-line-empty-p)
  19316. (let ((end (line-end-position 0)))
  19317. (or (= end (point-min))
  19318. (not (org-invisible-p (1- end))))))
  19319. (forward-line -1))
  19320. t)))
  19321. (cond
  19322. ;; Already at the beginning of an element.
  19323. ((= begin (point))
  19324. (cond
  19325. ;; There is a blank line above. Move there.
  19326. ((and (org-previous-line-empty-p)
  19327. (let ((lep (line-end-position 0)))
  19328. ;; When the first headline start at point 2, don't choke while
  19329. ;; checking with `org-invisible-p'.
  19330. (or (= lep 1)
  19331. (not (org-invisible-p (1- (line-end-position 0)))))))
  19332. (forward-line -1))
  19333. ;; At the beginning of the first element within a greater
  19334. ;; element. Move to the beginning of the greater element.
  19335. ((and parent (= begin (org-element-property :contents-begin parent)))
  19336. (funcall reach (org-element-property :begin parent)))
  19337. ;; Since we have to move anyway, find the beginning
  19338. ;; position of the element above.
  19339. (t
  19340. (forward-char -1)
  19341. (org--backward-paragraph-once))))
  19342. ;; Skip paragraphs at the very beginning of footnote
  19343. ;; definitions or items.
  19344. ((and (eq type 'paragraph)
  19345. (org-with-point-at begin (not (bolp))))
  19346. (funcall reach (progn (goto-char begin) (line-beginning-position))))
  19347. ;; If the element is folded, skip it altogether.
  19348. ((org-with-point-at post-affiliated
  19349. (org-invisible-p (line-end-position) t))
  19350. (funcall reach begin))
  19351. ;; At the end of a greater element, move inside.
  19352. ((and contents-end
  19353. (<= contents-end (point))
  19354. (not (eq type 'paragraph)))
  19355. (cond
  19356. ((memq type '(footnote-definition plain-list))
  19357. (skip-chars-backward " \t\n")
  19358. (org--backward-paragraph-once))
  19359. ((= contents-end (point))
  19360. (forward-char -1)
  19361. (org--backward-paragraph-once))
  19362. (t
  19363. (goto-char contents-end))))
  19364. ;; Move between empty lines in some blocks.
  19365. ((and (memq type '(comment-block example-block export-block src-block
  19366. verse-block))
  19367. (let ((contents-start
  19368. (org-with-point-at post-affiliated
  19369. (line-beginning-position 2))))
  19370. (when (> (point) contents-start)
  19371. (let ((contents-end
  19372. (org-with-point-at end
  19373. (skip-chars-backward " \t\n")
  19374. (line-beginning-position))))
  19375. (if (> (point) contents-end)
  19376. (progn (goto-char contents-end) t)
  19377. (skip-chars-backward " \t\n" begin)
  19378. (re-search-backward "^[ \t]*\n" contents-start :move)
  19379. t))))))
  19380. ;; Move to element's start.
  19381. (t
  19382. (funcall reach begin))))))))
  19383. (defun org-forward-element ()
  19384. "Move forward by one element.
  19385. Move to the next element at the same level, when possible."
  19386. (interactive)
  19387. (cond ((eobp) (user-error "Cannot move further down"))
  19388. ((org-with-limited-levels (org-at-heading-p))
  19389. (let ((origin (point)))
  19390. (goto-char (org-end-of-subtree nil t))
  19391. (unless (org-with-limited-levels (org-at-heading-p))
  19392. (goto-char origin)
  19393. (user-error "Cannot move further down"))))
  19394. (t
  19395. (let* ((elem (org-element-at-point))
  19396. (end (org-element-property :end elem))
  19397. (parent (org-element-property :parent elem)))
  19398. (cond ((and parent (= (org-element-property :contents-end parent) end))
  19399. (goto-char (org-element-property :end parent)))
  19400. ((integer-or-marker-p end) (goto-char end))
  19401. (t (message "No element at point")))))))
  19402. (defun org-backward-element ()
  19403. "Move backward by one element.
  19404. Move to the previous element at the same level, when possible."
  19405. (interactive)
  19406. (cond ((bobp) (user-error "Cannot move further up"))
  19407. ((org-with-limited-levels (org-at-heading-p))
  19408. ;; At a headline, move to the previous one, if any, or stay
  19409. ;; here.
  19410. (let ((origin (point)))
  19411. (org-with-limited-levels (org-backward-heading-same-level 1))
  19412. ;; When current headline has no sibling above, move to its
  19413. ;; parent.
  19414. (when (= (point) origin)
  19415. (or (org-with-limited-levels (org-up-heading-safe))
  19416. (progn (goto-char origin)
  19417. (user-error "Cannot move further up"))))))
  19418. (t
  19419. (let* ((elem (org-element-at-point))
  19420. (beg (org-element-property :begin elem)))
  19421. (cond
  19422. ;; Move to beginning of current element if point isn't
  19423. ;; there already.
  19424. ((null beg) (message "No element at point"))
  19425. ((/= (point) beg) (goto-char beg))
  19426. (t (goto-char beg)
  19427. (skip-chars-backward " \r\t\n")
  19428. (unless (bobp)
  19429. (let ((prev (org-element-at-point)))
  19430. (goto-char (org-element-property :begin prev))
  19431. (while (and (setq prev (org-element-property :parent prev))
  19432. (<= (org-element-property :end prev) beg))
  19433. (goto-char (org-element-property :begin prev)))))))))))
  19434. (defun org-up-element ()
  19435. "Move to upper element."
  19436. (interactive)
  19437. (if (org-with-limited-levels (org-at-heading-p))
  19438. (unless (org-up-heading-safe) (user-error "No surrounding element"))
  19439. (let* ((elem (org-element-at-point))
  19440. (parent (org-element-property :parent elem)))
  19441. (if parent (goto-char (org-element-property :begin parent))
  19442. (if (org-with-limited-levels (org-before-first-heading-p))
  19443. (user-error "No surrounding element")
  19444. (org-with-limited-levels (org-back-to-heading)))))))
  19445. (defun org-down-element ()
  19446. "Move to inner element."
  19447. (interactive)
  19448. (let ((element (org-element-at-point)))
  19449. (cond
  19450. ((memq (org-element-type element) '(plain-list table))
  19451. (goto-char (org-element-property :contents-begin element))
  19452. (forward-char))
  19453. ((memq (org-element-type element) org-element-greater-elements)
  19454. ;; If contents are hidden, first disclose them.
  19455. (when (org-invisible-p (line-end-position)) (org-cycle))
  19456. (goto-char (or (org-element-property :contents-begin element)
  19457. (user-error "No content for this element"))))
  19458. (t (user-error "No inner element")))))
  19459. (defun org-drag-element-backward ()
  19460. "Move backward element at point."
  19461. (interactive)
  19462. (let ((elem (or (org-element-at-point)
  19463. (user-error "No element at point"))))
  19464. (if (eq (org-element-type elem) 'headline)
  19465. ;; Preserve point when moving a whole tree, even if point was
  19466. ;; on blank lines below the headline.
  19467. (let ((offset (skip-chars-backward " \t\n")))
  19468. (unwind-protect (org-move-subtree-up)
  19469. (forward-char (- offset))))
  19470. (let ((prev-elem
  19471. (save-excursion
  19472. (goto-char (org-element-property :begin elem))
  19473. (skip-chars-backward " \r\t\n")
  19474. (unless (bobp)
  19475. (let* ((beg (org-element-property :begin elem))
  19476. (prev (org-element-at-point))
  19477. (up prev))
  19478. (while (and (setq up (org-element-property :parent up))
  19479. (<= (org-element-property :end up) beg))
  19480. (setq prev up))
  19481. prev)))))
  19482. ;; Error out if no previous element or previous element is
  19483. ;; a parent of the current one.
  19484. (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  19485. (user-error "Cannot drag element backward")
  19486. (let ((pos (point)))
  19487. (org-element-swap-A-B prev-elem elem)
  19488. (goto-char (+ (org-element-property :begin prev-elem)
  19489. (- pos (org-element-property :begin elem))))))))))
  19490. (defun org-drag-element-forward ()
  19491. "Move forward element at point."
  19492. (interactive)
  19493. (let* ((pos (point))
  19494. (elem (or (org-element-at-point)
  19495. (user-error "No element at point"))))
  19496. (when (= (point-max) (org-element-property :end elem))
  19497. (user-error "Cannot drag element forward"))
  19498. (goto-char (org-element-property :end elem))
  19499. (let ((next-elem (org-element-at-point)))
  19500. (when (or (org-element-nested-p elem next-elem)
  19501. (and (eq (org-element-type next-elem) 'headline)
  19502. (not (eq (org-element-type elem) 'headline))))
  19503. (goto-char pos)
  19504. (user-error "Cannot drag element forward"))
  19505. ;; Compute new position of point: it's shifted by NEXT-ELEM
  19506. ;; body's length (without final blanks) and by the length of
  19507. ;; blanks between ELEM and NEXT-ELEM.
  19508. (let ((size-next (- (save-excursion
  19509. (goto-char (org-element-property :end next-elem))
  19510. (skip-chars-backward " \r\t\n")
  19511. (forward-line)
  19512. ;; Small correction if buffer doesn't end
  19513. ;; with a newline character.
  19514. (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  19515. (org-element-property :begin next-elem)))
  19516. (size-blank (- (org-element-property :end elem)
  19517. (save-excursion
  19518. (goto-char (org-element-property :end elem))
  19519. (skip-chars-backward " \r\t\n")
  19520. (forward-line)
  19521. (point)))))
  19522. (org-element-swap-A-B elem next-elem)
  19523. (goto-char (+ pos size-next size-blank))))))
  19524. (defun org-drag-line-forward (arg)
  19525. "Drag the line at point ARG lines forward."
  19526. (interactive "p")
  19527. (dotimes (_ (abs arg))
  19528. (let ((c (current-column)))
  19529. (if (< 0 arg)
  19530. (progn
  19531. (beginning-of-line 2)
  19532. (transpose-lines 1)
  19533. (beginning-of-line 0))
  19534. (transpose-lines 1)
  19535. (beginning-of-line -1))
  19536. (org-move-to-column c))))
  19537. (defun org-drag-line-backward (arg)
  19538. "Drag the line at point ARG lines backward."
  19539. (interactive "p")
  19540. (org-drag-line-forward (- arg)))
  19541. (defun org-mark-element ()
  19542. "Put point at beginning of this element, mark at end.
  19543. Interactively, if this command is repeated or (in Transient Mark
  19544. mode) if the mark is active, it marks the next element after the
  19545. ones already marked."
  19546. (interactive)
  19547. (let (deactivate-mark)
  19548. (if (and (called-interactively-p 'any)
  19549. (or (and (eq last-command this-command) (mark t))
  19550. (and transient-mark-mode mark-active)))
  19551. (set-mark
  19552. (save-excursion
  19553. (goto-char (mark))
  19554. (goto-char (org-element-property :end (org-element-at-point)))
  19555. (point)))
  19556. (let ((element (org-element-at-point)))
  19557. (end-of-line)
  19558. (push-mark (min (point-max) (org-element-property :end element)) t t)
  19559. (goto-char (org-element-property :begin element))))))
  19560. (defun org-narrow-to-element ()
  19561. "Narrow buffer to current element."
  19562. (interactive)
  19563. (let ((elem (org-element-at-point)))
  19564. (cond
  19565. ((eq (car elem) 'headline)
  19566. (narrow-to-region
  19567. (org-element-property :begin elem)
  19568. (org-element-property :end elem)))
  19569. ((memq (car elem) org-element-greater-elements)
  19570. (narrow-to-region
  19571. (org-element-property :contents-begin elem)
  19572. (org-element-property :contents-end elem)))
  19573. (t
  19574. (narrow-to-region
  19575. (org-element-property :begin elem)
  19576. (org-element-property :end elem))))))
  19577. (defun org-transpose-element ()
  19578. "Transpose current and previous elements, keeping blank lines between.
  19579. Point is moved after both elements."
  19580. (interactive)
  19581. (org-skip-whitespace)
  19582. (let ((end (org-element-property :end (org-element-at-point))))
  19583. (org-drag-element-backward)
  19584. (goto-char end)))
  19585. (defun org-unindent-buffer ()
  19586. "Un-indent the visible part of the buffer.
  19587. Relative indentation (between items, inside blocks, etc.) isn't
  19588. modified."
  19589. (interactive)
  19590. (unless (eq major-mode 'org-mode)
  19591. (user-error "Cannot un-indent a buffer not in Org mode"))
  19592. (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  19593. (unindent-tree
  19594. (lambda (contents)
  19595. (dolist (element (reverse contents))
  19596. (if (memq (org-element-type element) '(headline section))
  19597. (funcall unindent-tree (org-element-contents element))
  19598. (save-excursion
  19599. (save-restriction
  19600. (narrow-to-region
  19601. (org-element-property :begin element)
  19602. (org-element-property :end element))
  19603. (org-do-remove-indentation))))))))
  19604. (funcall unindent-tree (org-element-contents parse-tree))))
  19605. (defun org-make-options-regexp (kwds &optional extra)
  19606. "Make a regular expression for keyword lines.
  19607. KWDS is a list of keywords, as strings. Optional argument EXTRA,
  19608. when non-nil, is a regexp matching keywords names."
  19609. (concat "^[ \t]*#\\+\\("
  19610. (regexp-opt kwds)
  19611. (and extra (concat (and kwds "\\|") extra))
  19612. "\\):[ \t]*\\(.*\\)"))
  19613. ;;; Conveniently switch to Info nodes
  19614. (defun org-info-find-node (&optional nodename)
  19615. "Find Info documentation NODENAME or Org documentation according context.
  19616. Started from `gnus-info-find-node'."
  19617. (interactive)
  19618. (Info-goto-node
  19619. (or nodename
  19620. (let ((default-org-info-node "(org) Top"))
  19621. (cond
  19622. ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  19623. ((eq 'org-mode major-mode)
  19624. (let* ((context (org-element-at-point))
  19625. (element-info-nodes ; compare to `org-element-all-elements'.
  19626. `((babel-call . "(org) Evaluating Code Blocks")
  19627. (center-block . "(org) Paragraphs")
  19628. (clock . ,default-org-info-node)
  19629. (comment . "(org) Comment Lines")
  19630. (comment-block . "(org) Comment Lines")
  19631. (diary-sexp . ,default-org-info-node)
  19632. (drawer . "(org) Drawers")
  19633. (dynamic-block . "(org) Dynamic Blocks")
  19634. (example-block . "(org) Literal Examples")
  19635. (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  19636. (fixed-width . ,default-org-info-node)
  19637. (footnote-definition . "(org) Creating Footnotes")
  19638. (headline . "(org) Document Structure")
  19639. (horizontal-rule . "(org) Built-in Table Editor")
  19640. (inlinetask . ,default-org-info-node)
  19641. (item . "(org) Plain Lists")
  19642. (keyword . "(org) Per-file keywords")
  19643. (latex-environment . "(org) LaTeX Export")
  19644. (node-property . "(org) Properties and Columns")
  19645. (paragraph . "(org) Paragraphs")
  19646. (plain-list . "(org) Plain Lists")
  19647. (planning . "(org) Deadlines and Scheduling")
  19648. (property-drawer . "(org) Properties and Columns")
  19649. (quote-block . "(org) Paragraphs")
  19650. (section . ,default-org-info-node)
  19651. (special-block . ,default-org-info-node)
  19652. (src-block . "(org) Working with Source Code")
  19653. (table . "(org) Tables")
  19654. (table-row . "(org) Tables")
  19655. (verse-block . "(org) Paragraphs"))))
  19656. (or (cdr (assoc (car context) element-info-nodes))
  19657. default-org-info-node)))
  19658. (t default-org-info-node))))))
  19659. ;;; Finish up
  19660. (add-hook 'org-mode-hook ;remove overlays when changing major mode
  19661. (lambda () (add-hook 'change-major-mode-hook
  19662. 'org-show-all 'append 'local)))
  19663. (provide 'org)
  19664. (run-hooks 'org-load-hook)
  19665. ;;; org.el ends here